PackageManagerService.java revision 2a9e3f8e6813716ab88ca54fd04ae047dc9aaaeb
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.isEnabledAndVisibleLPr(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.isEnabledAndVisibleLPr(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.isEnabledAndVisibleLPr(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.isEnabledAndVisibleLPr(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        flags = augmentFlagsForUser(flags, userId, null);
5755        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5756
5757        // writer
5758        synchronized (mPackages) {
5759            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5760            boolean[] tmpBools = new boolean[permissions.length];
5761            if (listUninstalled) {
5762                for (PackageSetting ps : mSettings.mPackages.values()) {
5763                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5764                }
5765            } else {
5766                for (PackageParser.Package pkg : mPackages.values()) {
5767                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5768                    if (ps != null) {
5769                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5770                                userId);
5771                    }
5772                }
5773            }
5774
5775            return new ParceledListSlice<PackageInfo>(list);
5776        }
5777    }
5778
5779    @Override
5780    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5781        if (!sUserManager.exists(userId)) return null;
5782        flags = augmentFlagsForUser(flags, userId, null);
5783        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5784
5785        // writer
5786        synchronized (mPackages) {
5787            ArrayList<ApplicationInfo> list;
5788            if (listUninstalled) {
5789                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5790                for (PackageSetting ps : mSettings.mPackages.values()) {
5791                    ApplicationInfo ai;
5792                    if (ps.pkg != null) {
5793                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5794                                ps.readUserState(userId), userId);
5795                    } else {
5796                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5797                    }
5798                    if (ai != null) {
5799                        list.add(ai);
5800                    }
5801                }
5802            } else {
5803                list = new ArrayList<ApplicationInfo>(mPackages.size());
5804                for (PackageParser.Package p : mPackages.values()) {
5805                    if (p.mExtras != null) {
5806                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5807                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5808                        if (ai != null) {
5809                            list.add(ai);
5810                        }
5811                    }
5812                }
5813            }
5814
5815            return new ParceledListSlice<ApplicationInfo>(list);
5816        }
5817    }
5818
5819    @Override
5820    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5821        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5822                "getEphemeralApplications");
5823        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5824                "getEphemeralApplications");
5825        synchronized (mPackages) {
5826            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5827                    .getEphemeralApplicationsLPw(userId);
5828            if (ephemeralApps != null) {
5829                return new ParceledListSlice<>(ephemeralApps);
5830            }
5831        }
5832        return null;
5833    }
5834
5835    @Override
5836    public boolean isEphemeralApplication(String packageName, int userId) {
5837        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5838                "isEphemeral");
5839        if (!isCallerSameApp(packageName)) {
5840            return false;
5841        }
5842        synchronized (mPackages) {
5843            PackageParser.Package pkg = mPackages.get(packageName);
5844            if (pkg != null) {
5845                return pkg.applicationInfo.isEphemeralApp();
5846            }
5847        }
5848        return false;
5849    }
5850
5851    @Override
5852    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5853        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5854                "getCookie");
5855        if (!isCallerSameApp(packageName)) {
5856            return null;
5857        }
5858        synchronized (mPackages) {
5859            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5860                    packageName, userId);
5861        }
5862    }
5863
5864    @Override
5865    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5866        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5867                "setCookie");
5868        if (!isCallerSameApp(packageName)) {
5869            return false;
5870        }
5871        synchronized (mPackages) {
5872            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5873                    packageName, cookie, userId);
5874        }
5875    }
5876
5877    @Override
5878    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5879        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5880                "getEphemeralApplicationIcon");
5881        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5882                "getEphemeralApplicationIcon");
5883        synchronized (mPackages) {
5884            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5885                    packageName, userId);
5886        }
5887    }
5888
5889    private boolean isCallerSameApp(String packageName) {
5890        PackageParser.Package pkg = mPackages.get(packageName);
5891        return pkg != null
5892                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5893    }
5894
5895    public List<ApplicationInfo> getPersistentApplications(int flags) {
5896        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5897
5898        // reader
5899        synchronized (mPackages) {
5900            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5901            final int userId = UserHandle.getCallingUserId();
5902            while (i.hasNext()) {
5903                final PackageParser.Package p = i.next();
5904                if (p.applicationInfo != null
5905                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5906                        && (!mSafeMode || isSystemApp(p))) {
5907                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5908                    if (ps != null) {
5909                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5910                                ps.readUserState(userId), userId);
5911                        if (ai != null) {
5912                            finalList.add(ai);
5913                        }
5914                    }
5915                }
5916            }
5917        }
5918
5919        return finalList;
5920    }
5921
5922    @Override
5923    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5924        if (!sUserManager.exists(userId)) return null;
5925        flags = augmentFlagsForUser(flags, userId, name);
5926        // reader
5927        synchronized (mPackages) {
5928            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5929            PackageSetting ps = provider != null
5930                    ? mSettings.mPackages.get(provider.owner.packageName)
5931                    : null;
5932            return ps != null
5933                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5934                    && (!mSafeMode || (provider.info.applicationInfo.flags
5935                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5936                    ? PackageParser.generateProviderInfo(provider, flags,
5937                            ps.readUserState(userId), userId)
5938                    : null;
5939        }
5940    }
5941
5942    /**
5943     * @deprecated
5944     */
5945    @Deprecated
5946    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5947        // reader
5948        synchronized (mPackages) {
5949            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5950                    .entrySet().iterator();
5951            final int userId = UserHandle.getCallingUserId();
5952            while (i.hasNext()) {
5953                Map.Entry<String, PackageParser.Provider> entry = i.next();
5954                PackageParser.Provider p = entry.getValue();
5955                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5956
5957                if (ps != null && p.syncable
5958                        && (!mSafeMode || (p.info.applicationInfo.flags
5959                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5960                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5961                            ps.readUserState(userId), userId);
5962                    if (info != null) {
5963                        outNames.add(entry.getKey());
5964                        outInfo.add(info);
5965                    }
5966                }
5967            }
5968        }
5969    }
5970
5971    @Override
5972    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5973            int uid, int flags) {
5974        final int userId = processName != null ? UserHandle.getUserId(uid)
5975                : UserHandle.getCallingUserId();
5976        if (!sUserManager.exists(userId)) return null;
5977        flags = augmentFlagsForUser(flags, userId, processName);
5978
5979        ArrayList<ProviderInfo> finalList = null;
5980        // reader
5981        synchronized (mPackages) {
5982            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5983            while (i.hasNext()) {
5984                final PackageParser.Provider p = i.next();
5985                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5986                if (ps != null && p.info.authority != null
5987                        && (processName == null
5988                                || (p.info.processName.equals(processName)
5989                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5990                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5991                        && (!mSafeMode
5992                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5993                    if (finalList == null) {
5994                        finalList = new ArrayList<ProviderInfo>(3);
5995                    }
5996                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5997                            ps.readUserState(userId), userId);
5998                    if (info != null) {
5999                        finalList.add(info);
6000                    }
6001                }
6002            }
6003        }
6004
6005        if (finalList != null) {
6006            Collections.sort(finalList, mProviderInitOrderSorter);
6007            return new ParceledListSlice<ProviderInfo>(finalList);
6008        }
6009
6010        return null;
6011    }
6012
6013    @Override
6014    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
6015            int flags) {
6016        // reader
6017        synchronized (mPackages) {
6018            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6019            return PackageParser.generateInstrumentationInfo(i, flags);
6020        }
6021    }
6022
6023    @Override
6024    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6025            int flags) {
6026        ArrayList<InstrumentationInfo> finalList =
6027            new ArrayList<InstrumentationInfo>();
6028
6029        // reader
6030        synchronized (mPackages) {
6031            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6032            while (i.hasNext()) {
6033                final PackageParser.Instrumentation p = i.next();
6034                if (targetPackage == null
6035                        || targetPackage.equals(p.info.targetPackage)) {
6036                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6037                            flags);
6038                    if (ii != null) {
6039                        finalList.add(ii);
6040                    }
6041                }
6042            }
6043        }
6044
6045        return finalList;
6046    }
6047
6048    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6049        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6050        if (overlays == null) {
6051            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6052            return;
6053        }
6054        for (PackageParser.Package opkg : overlays.values()) {
6055            // Not much to do if idmap fails: we already logged the error
6056            // and we certainly don't want to abort installation of pkg simply
6057            // because an overlay didn't fit properly. For these reasons,
6058            // ignore the return value of createIdmapForPackagePairLI.
6059            createIdmapForPackagePairLI(pkg, opkg);
6060        }
6061    }
6062
6063    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6064            PackageParser.Package opkg) {
6065        if (!opkg.mTrustedOverlay) {
6066            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6067                    opkg.baseCodePath + ": overlay not trusted");
6068            return false;
6069        }
6070        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6071        if (overlaySet == null) {
6072            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6073                    opkg.baseCodePath + " but target package has no known overlays");
6074            return false;
6075        }
6076        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6077        // TODO: generate idmap for split APKs
6078        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6079            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6080                    + opkg.baseCodePath);
6081            return false;
6082        }
6083        PackageParser.Package[] overlayArray =
6084            overlaySet.values().toArray(new PackageParser.Package[0]);
6085        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6086            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6087                return p1.mOverlayPriority - p2.mOverlayPriority;
6088            }
6089        };
6090        Arrays.sort(overlayArray, cmp);
6091
6092        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6093        int i = 0;
6094        for (PackageParser.Package p : overlayArray) {
6095            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6096        }
6097        return true;
6098    }
6099
6100    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6101        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6102        try {
6103            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6104        } finally {
6105            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6106        }
6107    }
6108
6109    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6110        final File[] files = dir.listFiles();
6111        if (ArrayUtils.isEmpty(files)) {
6112            Log.d(TAG, "No files in app dir " + dir);
6113            return;
6114        }
6115
6116        if (DEBUG_PACKAGE_SCANNING) {
6117            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6118                    + " flags=0x" + Integer.toHexString(parseFlags));
6119        }
6120
6121        for (File file : files) {
6122            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6123                    && !PackageInstallerService.isStageName(file.getName());
6124            if (!isPackage) {
6125                // Ignore entries which are not packages
6126                continue;
6127            }
6128            try {
6129                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6130                        scanFlags, currentTime, null);
6131            } catch (PackageManagerException e) {
6132                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6133
6134                // Delete invalid userdata apps
6135                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6136                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6137                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6138                    if (file.isDirectory()) {
6139                        mInstaller.rmPackageDir(file.getAbsolutePath());
6140                    } else {
6141                        file.delete();
6142                    }
6143                }
6144            }
6145        }
6146    }
6147
6148    private static File getSettingsProblemFile() {
6149        File dataDir = Environment.getDataDirectory();
6150        File systemDir = new File(dataDir, "system");
6151        File fname = new File(systemDir, "uiderrors.txt");
6152        return fname;
6153    }
6154
6155    static void reportSettingsProblem(int priority, String msg) {
6156        logCriticalInfo(priority, msg);
6157    }
6158
6159    static void logCriticalInfo(int priority, String msg) {
6160        Slog.println(priority, TAG, msg);
6161        EventLogTags.writePmCriticalInfo(msg);
6162        try {
6163            File fname = getSettingsProblemFile();
6164            FileOutputStream out = new FileOutputStream(fname, true);
6165            PrintWriter pw = new FastPrintWriter(out);
6166            SimpleDateFormat formatter = new SimpleDateFormat();
6167            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6168            pw.println(dateString + ": " + msg);
6169            pw.close();
6170            FileUtils.setPermissions(
6171                    fname.toString(),
6172                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6173                    -1, -1);
6174        } catch (java.io.IOException e) {
6175        }
6176    }
6177
6178    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6179            PackageParser.Package pkg, File srcFile, int parseFlags)
6180            throws PackageManagerException {
6181        if (ps != null
6182                && ps.codePath.equals(srcFile)
6183                && ps.timeStamp == srcFile.lastModified()
6184                && !isCompatSignatureUpdateNeeded(pkg)
6185                && !isRecoverSignatureUpdateNeeded(pkg)) {
6186            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6187            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6188            ArraySet<PublicKey> signingKs;
6189            synchronized (mPackages) {
6190                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6191            }
6192            if (ps.signatures.mSignatures != null
6193                    && ps.signatures.mSignatures.length != 0
6194                    && signingKs != null) {
6195                // Optimization: reuse the existing cached certificates
6196                // if the package appears to be unchanged.
6197                pkg.mSignatures = ps.signatures.mSignatures;
6198                pkg.mSigningKeys = signingKs;
6199                return;
6200            }
6201
6202            Slog.w(TAG, "PackageSetting for " + ps.name
6203                    + " is missing signatures.  Collecting certs again to recover them.");
6204        } else {
6205            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6206        }
6207
6208        try {
6209            pp.collectCertificates(pkg, parseFlags);
6210            pp.collectManifestDigest(pkg);
6211        } catch (PackageParserException e) {
6212            throw PackageManagerException.from(e);
6213        }
6214    }
6215
6216    /**
6217     *  Traces a package scan.
6218     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6219     */
6220    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6221            long currentTime, UserHandle user) throws PackageManagerException {
6222        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6223        try {
6224            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6225        } finally {
6226            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6227        }
6228    }
6229
6230    /**
6231     *  Scans a package and returns the newly parsed package.
6232     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6233     */
6234    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6235            long currentTime, UserHandle user) throws PackageManagerException {
6236        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6237        parseFlags |= mDefParseFlags;
6238        PackageParser pp = new PackageParser();
6239        pp.setSeparateProcesses(mSeparateProcesses);
6240        pp.setOnlyCoreApps(mOnlyCore);
6241        pp.setDisplayMetrics(mMetrics);
6242
6243        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6244            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6245        }
6246
6247        final PackageParser.Package pkg;
6248        try {
6249            pkg = pp.parsePackage(scanFile, parseFlags);
6250        } catch (PackageParserException e) {
6251            throw PackageManagerException.from(e);
6252        }
6253
6254        PackageSetting ps = null;
6255        PackageSetting updatedPkg;
6256        // reader
6257        synchronized (mPackages) {
6258            // Look to see if we already know about this package.
6259            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6260            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6261                // This package has been renamed to its original name.  Let's
6262                // use that.
6263                ps = mSettings.peekPackageLPr(oldName);
6264            }
6265            // If there was no original package, see one for the real package name.
6266            if (ps == null) {
6267                ps = mSettings.peekPackageLPr(pkg.packageName);
6268            }
6269            // Check to see if this package could be hiding/updating a system
6270            // package.  Must look for it either under the original or real
6271            // package name depending on our state.
6272            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6273            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6274        }
6275        boolean updatedPkgBetter = false;
6276        // First check if this is a system package that may involve an update
6277        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6278            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6279            // it needs to drop FLAG_PRIVILEGED.
6280            if (locationIsPrivileged(scanFile)) {
6281                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6282            } else {
6283                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6284            }
6285
6286            if (ps != null && !ps.codePath.equals(scanFile)) {
6287                // The path has changed from what was last scanned...  check the
6288                // version of the new path against what we have stored to determine
6289                // what to do.
6290                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6291                if (pkg.mVersionCode <= ps.versionCode) {
6292                    // The system package has been updated and the code path does not match
6293                    // Ignore entry. Skip it.
6294                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6295                            + " ignored: updated version " + ps.versionCode
6296                            + " better than this " + pkg.mVersionCode);
6297                    if (!updatedPkg.codePath.equals(scanFile)) {
6298                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6299                                + ps.name + " changing from " + updatedPkg.codePathString
6300                                + " to " + scanFile);
6301                        updatedPkg.codePath = scanFile;
6302                        updatedPkg.codePathString = scanFile.toString();
6303                        updatedPkg.resourcePath = scanFile;
6304                        updatedPkg.resourcePathString = scanFile.toString();
6305                    }
6306                    updatedPkg.pkg = pkg;
6307                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6308                            "Package " + ps.name + " at " + scanFile
6309                                    + " ignored: updated version " + ps.versionCode
6310                                    + " better than this " + pkg.mVersionCode);
6311                } else {
6312                    // The current app on the system partition is better than
6313                    // what we have updated to on the data partition; switch
6314                    // back to the system partition version.
6315                    // At this point, its safely assumed that package installation for
6316                    // apps in system partition will go through. If not there won't be a working
6317                    // version of the app
6318                    // writer
6319                    synchronized (mPackages) {
6320                        // Just remove the loaded entries from package lists.
6321                        mPackages.remove(ps.name);
6322                    }
6323
6324                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6325                            + " reverting from " + ps.codePathString
6326                            + ": new version " + pkg.mVersionCode
6327                            + " better than installed " + ps.versionCode);
6328
6329                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6330                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6331                    synchronized (mInstallLock) {
6332                        args.cleanUpResourcesLI();
6333                    }
6334                    synchronized (mPackages) {
6335                        mSettings.enableSystemPackageLPw(ps.name);
6336                    }
6337                    updatedPkgBetter = true;
6338                }
6339            }
6340        }
6341
6342        if (updatedPkg != null) {
6343            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6344            // initially
6345            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6346
6347            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6348            // flag set initially
6349            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6350                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6351            }
6352        }
6353
6354        // Verify certificates against what was last scanned
6355        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6356
6357        /*
6358         * A new system app appeared, but we already had a non-system one of the
6359         * same name installed earlier.
6360         */
6361        boolean shouldHideSystemApp = false;
6362        if (updatedPkg == null && ps != null
6363                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6364            /*
6365             * Check to make sure the signatures match first. If they don't,
6366             * wipe the installed application and its data.
6367             */
6368            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6369                    != PackageManager.SIGNATURE_MATCH) {
6370                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6371                        + " signatures don't match existing userdata copy; removing");
6372                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6373                ps = null;
6374            } else {
6375                /*
6376                 * If the newly-added system app is an older version than the
6377                 * already installed version, hide it. It will be scanned later
6378                 * and re-added like an update.
6379                 */
6380                if (pkg.mVersionCode <= ps.versionCode) {
6381                    shouldHideSystemApp = true;
6382                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6383                            + " but new version " + pkg.mVersionCode + " better than installed "
6384                            + ps.versionCode + "; hiding system");
6385                } else {
6386                    /*
6387                     * The newly found system app is a newer version that the
6388                     * one previously installed. Simply remove the
6389                     * already-installed application and replace it with our own
6390                     * while keeping the application data.
6391                     */
6392                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6393                            + " reverting from " + ps.codePathString + ": new version "
6394                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6395                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6396                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6397                    synchronized (mInstallLock) {
6398                        args.cleanUpResourcesLI();
6399                    }
6400                }
6401            }
6402        }
6403
6404        // The apk is forward locked (not public) if its code and resources
6405        // are kept in different files. (except for app in either system or
6406        // vendor path).
6407        // TODO grab this value from PackageSettings
6408        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6409            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6410                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6411            }
6412        }
6413
6414        // TODO: extend to support forward-locked splits
6415        String resourcePath = null;
6416        String baseResourcePath = null;
6417        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6418            if (ps != null && ps.resourcePathString != null) {
6419                resourcePath = ps.resourcePathString;
6420                baseResourcePath = ps.resourcePathString;
6421            } else {
6422                // Should not happen at all. Just log an error.
6423                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6424            }
6425        } else {
6426            resourcePath = pkg.codePath;
6427            baseResourcePath = pkg.baseCodePath;
6428        }
6429
6430        // Set application objects path explicitly.
6431        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6432        pkg.applicationInfo.setCodePath(pkg.codePath);
6433        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6434        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6435        pkg.applicationInfo.setResourcePath(resourcePath);
6436        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6437        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6438
6439        // Note that we invoke the following method only if we are about to unpack an application
6440        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6441                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6442
6443        /*
6444         * If the system app should be overridden by a previously installed
6445         * data, hide the system app now and let the /data/app scan pick it up
6446         * again.
6447         */
6448        if (shouldHideSystemApp) {
6449            synchronized (mPackages) {
6450                mSettings.disableSystemPackageLPw(pkg.packageName);
6451            }
6452        }
6453
6454        return scannedPkg;
6455    }
6456
6457    private static String fixProcessName(String defProcessName,
6458            String processName, int uid) {
6459        if (processName == null) {
6460            return defProcessName;
6461        }
6462        return processName;
6463    }
6464
6465    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6466            throws PackageManagerException {
6467        if (pkgSetting.signatures.mSignatures != null) {
6468            // Already existing package. Make sure signatures match
6469            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6470                    == PackageManager.SIGNATURE_MATCH;
6471            if (!match) {
6472                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6473                        == PackageManager.SIGNATURE_MATCH;
6474            }
6475            if (!match) {
6476                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6477                        == PackageManager.SIGNATURE_MATCH;
6478            }
6479            if (!match) {
6480                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6481                        + pkg.packageName + " signatures do not match the "
6482                        + "previously installed version; ignoring!");
6483            }
6484        }
6485
6486        // Check for shared user signatures
6487        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6488            // Already existing package. Make sure signatures match
6489            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6490                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6491            if (!match) {
6492                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6493                        == PackageManager.SIGNATURE_MATCH;
6494            }
6495            if (!match) {
6496                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6497                        == PackageManager.SIGNATURE_MATCH;
6498            }
6499            if (!match) {
6500                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6501                        "Package " + pkg.packageName
6502                        + " has no signatures that match those in shared user "
6503                        + pkgSetting.sharedUser.name + "; ignoring!");
6504            }
6505        }
6506    }
6507
6508    /**
6509     * Enforces that only the system UID or root's UID can call a method exposed
6510     * via Binder.
6511     *
6512     * @param message used as message if SecurityException is thrown
6513     * @throws SecurityException if the caller is not system or root
6514     */
6515    private static final void enforceSystemOrRoot(String message) {
6516        final int uid = Binder.getCallingUid();
6517        if (uid != Process.SYSTEM_UID && uid != 0) {
6518            throw new SecurityException(message);
6519        }
6520    }
6521
6522    @Override
6523    public void performFstrimIfNeeded() {
6524        enforceSystemOrRoot("Only the system can request fstrim");
6525
6526        // Before everything else, see whether we need to fstrim.
6527        try {
6528            IMountService ms = PackageHelper.getMountService();
6529            if (ms != null) {
6530                final boolean isUpgrade = isUpgrade();
6531                boolean doTrim = isUpgrade;
6532                if (doTrim) {
6533                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6534                } else {
6535                    final long interval = android.provider.Settings.Global.getLong(
6536                            mContext.getContentResolver(),
6537                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6538                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6539                    if (interval > 0) {
6540                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6541                        if (timeSinceLast > interval) {
6542                            doTrim = true;
6543                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6544                                    + "; running immediately");
6545                        }
6546                    }
6547                }
6548                if (doTrim) {
6549                    if (!isFirstBoot()) {
6550                        try {
6551                            ActivityManagerNative.getDefault().showBootMessage(
6552                                    mContext.getResources().getString(
6553                                            R.string.android_upgrading_fstrim), true);
6554                        } catch (RemoteException e) {
6555                        }
6556                    }
6557                    ms.runMaintenance();
6558                }
6559            } else {
6560                Slog.e(TAG, "Mount service unavailable!");
6561            }
6562        } catch (RemoteException e) {
6563            // Can't happen; MountService is local
6564        }
6565    }
6566
6567    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6568        List<ResolveInfo> ris = null;
6569        try {
6570            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6571                    intent, null, 0, userId);
6572        } catch (RemoteException e) {
6573        }
6574        ArraySet<String> pkgNames = new ArraySet<String>();
6575        if (ris != null) {
6576            for (ResolveInfo ri : ris) {
6577                pkgNames.add(ri.activityInfo.packageName);
6578            }
6579        }
6580        return pkgNames;
6581    }
6582
6583    @Override
6584    public void notifyPackageUse(String packageName) {
6585        synchronized (mPackages) {
6586            PackageParser.Package p = mPackages.get(packageName);
6587            if (p == null) {
6588                return;
6589            }
6590            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6591        }
6592    }
6593
6594    @Override
6595    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6596        return performDexOptTraced(packageName, instructionSet);
6597    }
6598
6599    public boolean performDexOpt(String packageName, String instructionSet) {
6600        return performDexOptTraced(packageName, instructionSet);
6601    }
6602
6603    private boolean performDexOptTraced(String packageName, String instructionSet) {
6604        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6605        try {
6606            return performDexOptInternal(packageName, instructionSet);
6607        } finally {
6608            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6609        }
6610    }
6611
6612    private boolean performDexOptInternal(String packageName, String instructionSet) {
6613        PackageParser.Package p;
6614        final String targetInstructionSet;
6615        synchronized (mPackages) {
6616            p = mPackages.get(packageName);
6617            if (p == null) {
6618                return false;
6619            }
6620            mPackageUsage.write(false);
6621
6622            targetInstructionSet = instructionSet != null ? instructionSet :
6623                    getPrimaryInstructionSet(p.applicationInfo);
6624            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6625                return false;
6626            }
6627        }
6628        long callingId = Binder.clearCallingIdentity();
6629        try {
6630            synchronized (mInstallLock) {
6631                final String[] instructionSets = new String[] { targetInstructionSet };
6632                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6633                        true /* inclDependencies */);
6634                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6635            }
6636        } finally {
6637            Binder.restoreCallingIdentity(callingId);
6638        }
6639    }
6640
6641    public ArraySet<String> getPackagesThatNeedDexOpt() {
6642        ArraySet<String> pkgs = null;
6643        synchronized (mPackages) {
6644            for (PackageParser.Package p : mPackages.values()) {
6645                if (DEBUG_DEXOPT) {
6646                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6647                }
6648                if (!p.mDexOptPerformed.isEmpty()) {
6649                    continue;
6650                }
6651                if (pkgs == null) {
6652                    pkgs = new ArraySet<String>();
6653                }
6654                pkgs.add(p.packageName);
6655            }
6656        }
6657        return pkgs;
6658    }
6659
6660    public void shutdown() {
6661        mPackageUsage.write(true);
6662    }
6663
6664    @Override
6665    public void forceDexOpt(String packageName) {
6666        enforceSystemOrRoot("forceDexOpt");
6667
6668        PackageParser.Package pkg;
6669        synchronized (mPackages) {
6670            pkg = mPackages.get(packageName);
6671            if (pkg == null) {
6672                throw new IllegalArgumentException("Missing package: " + packageName);
6673            }
6674        }
6675
6676        synchronized (mInstallLock) {
6677            final String[] instructionSets = new String[] {
6678                    getPrimaryInstructionSet(pkg.applicationInfo) };
6679
6680            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6681
6682            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6683                    true /* inclDependencies */);
6684
6685            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6686            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6687                throw new IllegalStateException("Failed to dexopt: " + res);
6688            }
6689        }
6690    }
6691
6692    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6693        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6694            Slog.w(TAG, "Unable to update from " + oldPkg.name
6695                    + " to " + newPkg.packageName
6696                    + ": old package not in system partition");
6697            return false;
6698        } else if (mPackages.get(oldPkg.name) != null) {
6699            Slog.w(TAG, "Unable to update from " + oldPkg.name
6700                    + " to " + newPkg.packageName
6701                    + ": old package still exists");
6702            return false;
6703        }
6704        return true;
6705    }
6706
6707    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6708            throws PackageManagerException {
6709        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6710        if (res != 0) {
6711            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6712                    "Failed to install " + packageName + ": " + res);
6713        }
6714
6715        final int[] users = sUserManager.getUserIds();
6716        for (int user : users) {
6717            if (user != 0) {
6718                res = mInstaller.createUserData(volumeUuid, packageName,
6719                        UserHandle.getUid(user, uid), user, seinfo);
6720                if (res != 0) {
6721                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6722                            "Failed to createUserData " + packageName + ": " + res);
6723                }
6724            }
6725        }
6726    }
6727
6728    private int removeDataDirsLI(String volumeUuid, String packageName) {
6729        int[] users = sUserManager.getUserIds();
6730        int res = 0;
6731        for (int user : users) {
6732            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6733            if (resInner < 0) {
6734                res = resInner;
6735            }
6736        }
6737
6738        return res;
6739    }
6740
6741    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6742        int[] users = sUserManager.getUserIds();
6743        int res = 0;
6744        for (int user : users) {
6745            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6746            if (resInner < 0) {
6747                res = resInner;
6748            }
6749        }
6750        return res;
6751    }
6752
6753    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6754            PackageParser.Package changingLib) {
6755        if (file.path != null) {
6756            usesLibraryFiles.add(file.path);
6757            return;
6758        }
6759        PackageParser.Package p = mPackages.get(file.apk);
6760        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6761            // If we are doing this while in the middle of updating a library apk,
6762            // then we need to make sure to use that new apk for determining the
6763            // dependencies here.  (We haven't yet finished committing the new apk
6764            // to the package manager state.)
6765            if (p == null || p.packageName.equals(changingLib.packageName)) {
6766                p = changingLib;
6767            }
6768        }
6769        if (p != null) {
6770            usesLibraryFiles.addAll(p.getAllCodePaths());
6771        }
6772    }
6773
6774    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6775            PackageParser.Package changingLib) throws PackageManagerException {
6776        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6777            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6778            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6779            for (int i=0; i<N; i++) {
6780                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6781                if (file == null) {
6782                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6783                            "Package " + pkg.packageName + " requires unavailable shared library "
6784                            + pkg.usesLibraries.get(i) + "; failing!");
6785                }
6786                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6787            }
6788            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6789            for (int i=0; i<N; i++) {
6790                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6791                if (file == null) {
6792                    Slog.w(TAG, "Package " + pkg.packageName
6793                            + " desires unavailable shared library "
6794                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6795                } else {
6796                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6797                }
6798            }
6799            N = usesLibraryFiles.size();
6800            if (N > 0) {
6801                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6802            } else {
6803                pkg.usesLibraryFiles = null;
6804            }
6805        }
6806    }
6807
6808    private static boolean hasString(List<String> list, List<String> which) {
6809        if (list == null) {
6810            return false;
6811        }
6812        for (int i=list.size()-1; i>=0; i--) {
6813            for (int j=which.size()-1; j>=0; j--) {
6814                if (which.get(j).equals(list.get(i))) {
6815                    return true;
6816                }
6817            }
6818        }
6819        return false;
6820    }
6821
6822    private void updateAllSharedLibrariesLPw() {
6823        for (PackageParser.Package pkg : mPackages.values()) {
6824            try {
6825                updateSharedLibrariesLPw(pkg, null);
6826            } catch (PackageManagerException e) {
6827                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6828            }
6829        }
6830    }
6831
6832    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6833            PackageParser.Package changingPkg) {
6834        ArrayList<PackageParser.Package> res = null;
6835        for (PackageParser.Package pkg : mPackages.values()) {
6836            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6837                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6838                if (res == null) {
6839                    res = new ArrayList<PackageParser.Package>();
6840                }
6841                res.add(pkg);
6842                try {
6843                    updateSharedLibrariesLPw(pkg, changingPkg);
6844                } catch (PackageManagerException e) {
6845                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6846                }
6847            }
6848        }
6849        return res;
6850    }
6851
6852    /**
6853     * Derive the value of the {@code cpuAbiOverride} based on the provided
6854     * value and an optional stored value from the package settings.
6855     */
6856    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6857        String cpuAbiOverride = null;
6858
6859        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6860            cpuAbiOverride = null;
6861        } else if (abiOverride != null) {
6862            cpuAbiOverride = abiOverride;
6863        } else if (settings != null) {
6864            cpuAbiOverride = settings.cpuAbiOverrideString;
6865        }
6866
6867        return cpuAbiOverride;
6868    }
6869
6870    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6871            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6872        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6873        try {
6874            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6875        } finally {
6876            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6877        }
6878    }
6879
6880    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6881            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6882        boolean success = false;
6883        try {
6884            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6885                    currentTime, user);
6886            success = true;
6887            return res;
6888        } finally {
6889            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6890                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6891            }
6892        }
6893    }
6894
6895    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6896            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6897        final File scanFile = new File(pkg.codePath);
6898        if (pkg.applicationInfo.getCodePath() == null ||
6899                pkg.applicationInfo.getResourcePath() == null) {
6900            // Bail out. The resource and code paths haven't been set.
6901            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6902                    "Code and resource paths haven't been set correctly");
6903        }
6904
6905        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6906            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6907        } else {
6908            // Only allow system apps to be flagged as core apps.
6909            pkg.coreApp = false;
6910        }
6911
6912        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6913            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6914        }
6915
6916        if (mCustomResolverComponentName != null &&
6917                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6918            setUpCustomResolverActivity(pkg);
6919        }
6920
6921        if (pkg.packageName.equals("android")) {
6922            synchronized (mPackages) {
6923                if (mAndroidApplication != null) {
6924                    Slog.w(TAG, "*************************************************");
6925                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6926                    Slog.w(TAG, " file=" + scanFile);
6927                    Slog.w(TAG, "*************************************************");
6928                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6929                            "Core android package being redefined.  Skipping.");
6930                }
6931
6932                // Set up information for our fall-back user intent resolution activity.
6933                mPlatformPackage = pkg;
6934                pkg.mVersionCode = mSdkVersion;
6935                mAndroidApplication = pkg.applicationInfo;
6936
6937                if (!mResolverReplaced) {
6938                    mResolveActivity.applicationInfo = mAndroidApplication;
6939                    mResolveActivity.name = ResolverActivity.class.getName();
6940                    mResolveActivity.packageName = mAndroidApplication.packageName;
6941                    mResolveActivity.processName = "system:ui";
6942                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6943                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6944                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6945                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6946                    mResolveActivity.exported = true;
6947                    mResolveActivity.enabled = true;
6948                    mResolveInfo.activityInfo = mResolveActivity;
6949                    mResolveInfo.priority = 0;
6950                    mResolveInfo.preferredOrder = 0;
6951                    mResolveInfo.match = 0;
6952                    mResolveComponentName = new ComponentName(
6953                            mAndroidApplication.packageName, mResolveActivity.name);
6954                }
6955            }
6956        }
6957
6958        if (DEBUG_PACKAGE_SCANNING) {
6959            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6960                Log.d(TAG, "Scanning package " + pkg.packageName);
6961        }
6962
6963        if (mPackages.containsKey(pkg.packageName)
6964                || mSharedLibraries.containsKey(pkg.packageName)) {
6965            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6966                    "Application package " + pkg.packageName
6967                    + " already installed.  Skipping duplicate.");
6968        }
6969
6970        // If we're only installing presumed-existing packages, require that the
6971        // scanned APK is both already known and at the path previously established
6972        // for it.  Previously unknown packages we pick up normally, but if we have an
6973        // a priori expectation about this package's install presence, enforce it.
6974        // With a singular exception for new system packages. When an OTA contains
6975        // a new system package, we allow the codepath to change from a system location
6976        // to the user-installed location. If we don't allow this change, any newer,
6977        // user-installed version of the application will be ignored.
6978        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6979            if (mExpectingBetter.containsKey(pkg.packageName)) {
6980                logCriticalInfo(Log.WARN,
6981                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6982            } else {
6983                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6984                if (known != null) {
6985                    if (DEBUG_PACKAGE_SCANNING) {
6986                        Log.d(TAG, "Examining " + pkg.codePath
6987                                + " and requiring known paths " + known.codePathString
6988                                + " & " + known.resourcePathString);
6989                    }
6990                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6991                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6992                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6993                                "Application package " + pkg.packageName
6994                                + " found at " + pkg.applicationInfo.getCodePath()
6995                                + " but expected at " + known.codePathString + "; ignoring.");
6996                    }
6997                }
6998            }
6999        }
7000
7001        // Initialize package source and resource directories
7002        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7003        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7004
7005        SharedUserSetting suid = null;
7006        PackageSetting pkgSetting = null;
7007
7008        if (!isSystemApp(pkg)) {
7009            // Only system apps can use these features.
7010            pkg.mOriginalPackages = null;
7011            pkg.mRealPackage = null;
7012            pkg.mAdoptPermissions = null;
7013        }
7014
7015        // writer
7016        synchronized (mPackages) {
7017            if (pkg.mSharedUserId != null) {
7018                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7019                if (suid == null) {
7020                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7021                            "Creating application package " + pkg.packageName
7022                            + " for shared user failed");
7023                }
7024                if (DEBUG_PACKAGE_SCANNING) {
7025                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7026                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7027                                + "): packages=" + suid.packages);
7028                }
7029            }
7030
7031            // Check if we are renaming from an original package name.
7032            PackageSetting origPackage = null;
7033            String realName = null;
7034            if (pkg.mOriginalPackages != null) {
7035                // This package may need to be renamed to a previously
7036                // installed name.  Let's check on that...
7037                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7038                if (pkg.mOriginalPackages.contains(renamed)) {
7039                    // This package had originally been installed as the
7040                    // original name, and we have already taken care of
7041                    // transitioning to the new one.  Just update the new
7042                    // one to continue using the old name.
7043                    realName = pkg.mRealPackage;
7044                    if (!pkg.packageName.equals(renamed)) {
7045                        // Callers into this function may have already taken
7046                        // care of renaming the package; only do it here if
7047                        // it is not already done.
7048                        pkg.setPackageName(renamed);
7049                    }
7050
7051                } else {
7052                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7053                        if ((origPackage = mSettings.peekPackageLPr(
7054                                pkg.mOriginalPackages.get(i))) != null) {
7055                            // We do have the package already installed under its
7056                            // original name...  should we use it?
7057                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7058                                // New package is not compatible with original.
7059                                origPackage = null;
7060                                continue;
7061                            } else if (origPackage.sharedUser != null) {
7062                                // Make sure uid is compatible between packages.
7063                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7064                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7065                                            + " to " + pkg.packageName + ": old uid "
7066                                            + origPackage.sharedUser.name
7067                                            + " differs from " + pkg.mSharedUserId);
7068                                    origPackage = null;
7069                                    continue;
7070                                }
7071                            } else {
7072                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7073                                        + pkg.packageName + " to old name " + origPackage.name);
7074                            }
7075                            break;
7076                        }
7077                    }
7078                }
7079            }
7080
7081            if (mTransferedPackages.contains(pkg.packageName)) {
7082                Slog.w(TAG, "Package " + pkg.packageName
7083                        + " was transferred to another, but its .apk remains");
7084            }
7085
7086            // Just create the setting, don't add it yet. For already existing packages
7087            // the PkgSetting exists already and doesn't have to be created.
7088            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7089                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7090                    pkg.applicationInfo.primaryCpuAbi,
7091                    pkg.applicationInfo.secondaryCpuAbi,
7092                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7093                    user, false);
7094            if (pkgSetting == null) {
7095                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7096                        "Creating application package " + pkg.packageName + " failed");
7097            }
7098
7099            if (pkgSetting.origPackage != null) {
7100                // If we are first transitioning from an original package,
7101                // fix up the new package's name now.  We need to do this after
7102                // looking up the package under its new name, so getPackageLP
7103                // can take care of fiddling things correctly.
7104                pkg.setPackageName(origPackage.name);
7105
7106                // File a report about this.
7107                String msg = "New package " + pkgSetting.realName
7108                        + " renamed to replace old package " + pkgSetting.name;
7109                reportSettingsProblem(Log.WARN, msg);
7110
7111                // Make a note of it.
7112                mTransferedPackages.add(origPackage.name);
7113
7114                // No longer need to retain this.
7115                pkgSetting.origPackage = null;
7116            }
7117
7118            if (realName != null) {
7119                // Make a note of it.
7120                mTransferedPackages.add(pkg.packageName);
7121            }
7122
7123            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7124                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7125            }
7126
7127            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7128                // Check all shared libraries and map to their actual file path.
7129                // We only do this here for apps not on a system dir, because those
7130                // are the only ones that can fail an install due to this.  We
7131                // will take care of the system apps by updating all of their
7132                // library paths after the scan is done.
7133                updateSharedLibrariesLPw(pkg, null);
7134            }
7135
7136            if (mFoundPolicyFile) {
7137                SELinuxMMAC.assignSeinfoValue(pkg);
7138            }
7139
7140            pkg.applicationInfo.uid = pkgSetting.appId;
7141            pkg.mExtras = pkgSetting;
7142            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7143                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7144                    // We just determined the app is signed correctly, so bring
7145                    // over the latest parsed certs.
7146                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7147                } else {
7148                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7149                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7150                                "Package " + pkg.packageName + " upgrade keys do not match the "
7151                                + "previously installed version");
7152                    } else {
7153                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7154                        String msg = "System package " + pkg.packageName
7155                            + " signature changed; retaining data.";
7156                        reportSettingsProblem(Log.WARN, msg);
7157                    }
7158                }
7159            } else {
7160                try {
7161                    verifySignaturesLP(pkgSetting, pkg);
7162                    // We just determined the app is signed correctly, so bring
7163                    // over the latest parsed certs.
7164                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7165                } catch (PackageManagerException e) {
7166                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7167                        throw e;
7168                    }
7169                    // The signature has changed, but this package is in the system
7170                    // image...  let's recover!
7171                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7172                    // However...  if this package is part of a shared user, but it
7173                    // doesn't match the signature of the shared user, let's fail.
7174                    // What this means is that you can't change the signatures
7175                    // associated with an overall shared user, which doesn't seem all
7176                    // that unreasonable.
7177                    if (pkgSetting.sharedUser != null) {
7178                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7179                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7180                            throw new PackageManagerException(
7181                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7182                                            "Signature mismatch for shared user : "
7183                                            + pkgSetting.sharedUser);
7184                        }
7185                    }
7186                    // File a report about this.
7187                    String msg = "System package " + pkg.packageName
7188                        + " signature changed; retaining data.";
7189                    reportSettingsProblem(Log.WARN, msg);
7190                }
7191            }
7192            // Verify that this new package doesn't have any content providers
7193            // that conflict with existing packages.  Only do this if the
7194            // package isn't already installed, since we don't want to break
7195            // things that are installed.
7196            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7197                final int N = pkg.providers.size();
7198                int i;
7199                for (i=0; i<N; i++) {
7200                    PackageParser.Provider p = pkg.providers.get(i);
7201                    if (p.info.authority != null) {
7202                        String names[] = p.info.authority.split(";");
7203                        for (int j = 0; j < names.length; j++) {
7204                            if (mProvidersByAuthority.containsKey(names[j])) {
7205                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7206                                final String otherPackageName =
7207                                        ((other != null && other.getComponentName() != null) ?
7208                                                other.getComponentName().getPackageName() : "?");
7209                                throw new PackageManagerException(
7210                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7211                                                "Can't install because provider name " + names[j]
7212                                                + " (in package " + pkg.applicationInfo.packageName
7213                                                + ") is already used by " + otherPackageName);
7214                            }
7215                        }
7216                    }
7217                }
7218            }
7219
7220            if (pkg.mAdoptPermissions != null) {
7221                // This package wants to adopt ownership of permissions from
7222                // another package.
7223                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7224                    final String origName = pkg.mAdoptPermissions.get(i);
7225                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7226                    if (orig != null) {
7227                        if (verifyPackageUpdateLPr(orig, pkg)) {
7228                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7229                                    + pkg.packageName);
7230                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7231                        }
7232                    }
7233                }
7234            }
7235        }
7236
7237        final String pkgName = pkg.packageName;
7238
7239        final long scanFileTime = scanFile.lastModified();
7240        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7241        pkg.applicationInfo.processName = fixProcessName(
7242                pkg.applicationInfo.packageName,
7243                pkg.applicationInfo.processName,
7244                pkg.applicationInfo.uid);
7245
7246        if (pkg != mPlatformPackage) {
7247            // This is a normal package, need to make its data directory.
7248            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7249                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7250
7251            boolean uidError = false;
7252            if (dataPath.exists()) {
7253                int currentUid = 0;
7254                try {
7255                    StructStat stat = Os.stat(dataPath.getPath());
7256                    currentUid = stat.st_uid;
7257                } catch (ErrnoException e) {
7258                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7259                }
7260
7261                // If we have mismatched owners for the data path, we have a problem.
7262                if (currentUid != pkg.applicationInfo.uid) {
7263                    boolean recovered = false;
7264                    if (currentUid == 0) {
7265                        // The directory somehow became owned by root.  Wow.
7266                        // This is probably because the system was stopped while
7267                        // installd was in the middle of messing with its libs
7268                        // directory.  Ask installd to fix that.
7269                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7270                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7271                        if (ret >= 0) {
7272                            recovered = true;
7273                            String msg = "Package " + pkg.packageName
7274                                    + " unexpectedly changed to uid 0; recovered to " +
7275                                    + pkg.applicationInfo.uid;
7276                            reportSettingsProblem(Log.WARN, msg);
7277                        }
7278                    }
7279                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7280                            || (scanFlags&SCAN_BOOTING) != 0)) {
7281                        // If this is a system app, we can at least delete its
7282                        // current data so the application will still work.
7283                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7284                        if (ret >= 0) {
7285                            // TODO: Kill the processes first
7286                            // Old data gone!
7287                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7288                                    ? "System package " : "Third party package ";
7289                            String msg = prefix + pkg.packageName
7290                                    + " has changed from uid: "
7291                                    + currentUid + " to "
7292                                    + pkg.applicationInfo.uid + "; old data erased";
7293                            reportSettingsProblem(Log.WARN, msg);
7294                            recovered = true;
7295                        }
7296                        if (!recovered) {
7297                            mHasSystemUidErrors = true;
7298                        }
7299                    } else if (!recovered) {
7300                        // If we allow this install to proceed, we will be broken.
7301                        // Abort, abort!
7302                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7303                                "scanPackageLI");
7304                    }
7305                    if (!recovered) {
7306                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7307                            + pkg.applicationInfo.uid + "/fs_"
7308                            + currentUid;
7309                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7310                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7311                        String msg = "Package " + pkg.packageName
7312                                + " has mismatched uid: "
7313                                + currentUid + " on disk, "
7314                                + pkg.applicationInfo.uid + " in settings";
7315                        // writer
7316                        synchronized (mPackages) {
7317                            mSettings.mReadMessages.append(msg);
7318                            mSettings.mReadMessages.append('\n');
7319                            uidError = true;
7320                            if (!pkgSetting.uidError) {
7321                                reportSettingsProblem(Log.ERROR, msg);
7322                            }
7323                        }
7324                    }
7325                }
7326
7327                // Ensure that directories are prepared
7328                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7329                        pkg.applicationInfo.seinfo);
7330
7331                if (mShouldRestoreconData) {
7332                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7333                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7334                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7335                }
7336            } else {
7337                if (DEBUG_PACKAGE_SCANNING) {
7338                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7339                        Log.v(TAG, "Want this data dir: " + dataPath);
7340                }
7341                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7342                        pkg.applicationInfo.seinfo);
7343            }
7344
7345            // Get all of our default paths setup
7346            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7347
7348            pkgSetting.uidError = uidError;
7349        }
7350
7351        final String path = scanFile.getPath();
7352        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7353
7354        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7355            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7356
7357            // Some system apps still use directory structure for native libraries
7358            // in which case we might end up not detecting abi solely based on apk
7359            // structure. Try to detect abi based on directory structure.
7360            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7361                    pkg.applicationInfo.primaryCpuAbi == null) {
7362                setBundledAppAbisAndRoots(pkg, pkgSetting);
7363                setNativeLibraryPaths(pkg);
7364            }
7365
7366        } else {
7367            if ((scanFlags & SCAN_MOVE) != 0) {
7368                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7369                // but we already have this packages package info in the PackageSetting. We just
7370                // use that and derive the native library path based on the new codepath.
7371                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7372                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7373            }
7374
7375            // Set native library paths again. For moves, the path will be updated based on the
7376            // ABIs we've determined above. For non-moves, the path will be updated based on the
7377            // ABIs we determined during compilation, but the path will depend on the final
7378            // package path (after the rename away from the stage path).
7379            setNativeLibraryPaths(pkg);
7380        }
7381
7382        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7383        final int[] userIds = sUserManager.getUserIds();
7384        synchronized (mInstallLock) {
7385            // Make sure all user data directories are ready to roll; we're okay
7386            // if they already exist
7387            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7388                for (int userId : userIds) {
7389                    if (userId != UserHandle.USER_SYSTEM) {
7390                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7391                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7392                                pkg.applicationInfo.seinfo);
7393                    }
7394                }
7395            }
7396
7397            // Create a native library symlink only if we have native libraries
7398            // and if the native libraries are 32 bit libraries. We do not provide
7399            // this symlink for 64 bit libraries.
7400            if (pkg.applicationInfo.primaryCpuAbi != null &&
7401                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7402                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7403                try {
7404                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7405                    for (int userId : userIds) {
7406                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7407                                nativeLibPath, userId) < 0) {
7408                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7409                                    "Failed linking native library dir (user=" + userId + ")");
7410                        }
7411                    }
7412                } finally {
7413                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7414                }
7415            }
7416        }
7417
7418        // This is a special case for the "system" package, where the ABI is
7419        // dictated by the zygote configuration (and init.rc). We should keep track
7420        // of this ABI so that we can deal with "normal" applications that run under
7421        // the same UID correctly.
7422        if (mPlatformPackage == pkg) {
7423            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7424                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7425        }
7426
7427        // If there's a mismatch between the abi-override in the package setting
7428        // and the abiOverride specified for the install. Warn about this because we
7429        // would've already compiled the app without taking the package setting into
7430        // account.
7431        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7432            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7433                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7434                        " for package: " + pkg.packageName);
7435            }
7436        }
7437
7438        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7439        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7440        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7441
7442        // Copy the derived override back to the parsed package, so that we can
7443        // update the package settings accordingly.
7444        pkg.cpuAbiOverride = cpuAbiOverride;
7445
7446        if (DEBUG_ABI_SELECTION) {
7447            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7448                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7449                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7450        }
7451
7452        // Push the derived path down into PackageSettings so we know what to
7453        // clean up at uninstall time.
7454        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7455
7456        if (DEBUG_ABI_SELECTION) {
7457            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7458                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7459                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7460        }
7461
7462        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7463            // We don't do this here during boot because we can do it all
7464            // at once after scanning all existing packages.
7465            //
7466            // We also do this *before* we perform dexopt on this package, so that
7467            // we can avoid redundant dexopts, and also to make sure we've got the
7468            // code and package path correct.
7469            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7470                    pkg, true /* boot complete */);
7471        }
7472
7473        if (mFactoryTest && pkg.requestedPermissions.contains(
7474                android.Manifest.permission.FACTORY_TEST)) {
7475            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7476        }
7477
7478        ArrayList<PackageParser.Package> clientLibPkgs = null;
7479
7480        // writer
7481        synchronized (mPackages) {
7482            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7483                // Only system apps can add new shared libraries.
7484                if (pkg.libraryNames != null) {
7485                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7486                        String name = pkg.libraryNames.get(i);
7487                        boolean allowed = false;
7488                        if (pkg.isUpdatedSystemApp()) {
7489                            // New library entries can only be added through the
7490                            // system image.  This is important to get rid of a lot
7491                            // of nasty edge cases: for example if we allowed a non-
7492                            // system update of the app to add a library, then uninstalling
7493                            // the update would make the library go away, and assumptions
7494                            // we made such as through app install filtering would now
7495                            // have allowed apps on the device which aren't compatible
7496                            // with it.  Better to just have the restriction here, be
7497                            // conservative, and create many fewer cases that can negatively
7498                            // impact the user experience.
7499                            final PackageSetting sysPs = mSettings
7500                                    .getDisabledSystemPkgLPr(pkg.packageName);
7501                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7502                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7503                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7504                                        allowed = true;
7505                                        break;
7506                                    }
7507                                }
7508                            }
7509                        } else {
7510                            allowed = true;
7511                        }
7512                        if (allowed) {
7513                            if (!mSharedLibraries.containsKey(name)) {
7514                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7515                            } else if (!name.equals(pkg.packageName)) {
7516                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7517                                        + name + " already exists; skipping");
7518                            }
7519                        } else {
7520                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7521                                    + name + " that is not declared on system image; skipping");
7522                        }
7523                    }
7524                    if ((scanFlags & SCAN_BOOTING) == 0) {
7525                        // If we are not booting, we need to update any applications
7526                        // that are clients of our shared library.  If we are booting,
7527                        // this will all be done once the scan is complete.
7528                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7529                    }
7530                }
7531            }
7532        }
7533
7534        // Request the ActivityManager to kill the process(only for existing packages)
7535        // so that we do not end up in a confused state while the user is still using the older
7536        // version of the application while the new one gets installed.
7537        if ((scanFlags & SCAN_REPLACING) != 0) {
7538            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7539
7540            killApplication(pkg.applicationInfo.packageName,
7541                        pkg.applicationInfo.uid, "replace pkg");
7542
7543            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7544        }
7545
7546        // Also need to kill any apps that are dependent on the library.
7547        if (clientLibPkgs != null) {
7548            for (int i=0; i<clientLibPkgs.size(); i++) {
7549                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7550                killApplication(clientPkg.applicationInfo.packageName,
7551                        clientPkg.applicationInfo.uid, "update lib");
7552            }
7553        }
7554
7555        // Make sure we're not adding any bogus keyset info
7556        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7557        ksms.assertScannedPackageValid(pkg);
7558
7559        // writer
7560        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7561
7562        boolean createIdmapFailed = false;
7563        synchronized (mPackages) {
7564            // We don't expect installation to fail beyond this point
7565
7566            // Add the new setting to mSettings
7567            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7568            // Add the new setting to mPackages
7569            mPackages.put(pkg.applicationInfo.packageName, pkg);
7570            // Make sure we don't accidentally delete its data.
7571            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7572            while (iter.hasNext()) {
7573                PackageCleanItem item = iter.next();
7574                if (pkgName.equals(item.packageName)) {
7575                    iter.remove();
7576                }
7577            }
7578
7579            // Take care of first install / last update times.
7580            if (currentTime != 0) {
7581                if (pkgSetting.firstInstallTime == 0) {
7582                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7583                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7584                    pkgSetting.lastUpdateTime = currentTime;
7585                }
7586            } else if (pkgSetting.firstInstallTime == 0) {
7587                // We need *something*.  Take time time stamp of the file.
7588                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7589            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7590                if (scanFileTime != pkgSetting.timeStamp) {
7591                    // A package on the system image has changed; consider this
7592                    // to be an update.
7593                    pkgSetting.lastUpdateTime = scanFileTime;
7594                }
7595            }
7596
7597            // Add the package's KeySets to the global KeySetManagerService
7598            ksms.addScannedPackageLPw(pkg);
7599
7600            int N = pkg.providers.size();
7601            StringBuilder r = null;
7602            int i;
7603            for (i=0; i<N; i++) {
7604                PackageParser.Provider p = pkg.providers.get(i);
7605                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7606                        p.info.processName, pkg.applicationInfo.uid);
7607                mProviders.addProvider(p);
7608                p.syncable = p.info.isSyncable;
7609                if (p.info.authority != null) {
7610                    String names[] = p.info.authority.split(";");
7611                    p.info.authority = null;
7612                    for (int j = 0; j < names.length; j++) {
7613                        if (j == 1 && p.syncable) {
7614                            // We only want the first authority for a provider to possibly be
7615                            // syncable, so if we already added this provider using a different
7616                            // authority clear the syncable flag. We copy the provider before
7617                            // changing it because the mProviders object contains a reference
7618                            // to a provider that we don't want to change.
7619                            // Only do this for the second authority since the resulting provider
7620                            // object can be the same for all future authorities for this provider.
7621                            p = new PackageParser.Provider(p);
7622                            p.syncable = false;
7623                        }
7624                        if (!mProvidersByAuthority.containsKey(names[j])) {
7625                            mProvidersByAuthority.put(names[j], p);
7626                            if (p.info.authority == null) {
7627                                p.info.authority = names[j];
7628                            } else {
7629                                p.info.authority = p.info.authority + ";" + names[j];
7630                            }
7631                            if (DEBUG_PACKAGE_SCANNING) {
7632                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7633                                    Log.d(TAG, "Registered content provider: " + names[j]
7634                                            + ", className = " + p.info.name + ", isSyncable = "
7635                                            + p.info.isSyncable);
7636                            }
7637                        } else {
7638                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7639                            Slog.w(TAG, "Skipping provider name " + names[j] +
7640                                    " (in package " + pkg.applicationInfo.packageName +
7641                                    "): name already used by "
7642                                    + ((other != null && other.getComponentName() != null)
7643                                            ? other.getComponentName().getPackageName() : "?"));
7644                        }
7645                    }
7646                }
7647                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7648                    if (r == null) {
7649                        r = new StringBuilder(256);
7650                    } else {
7651                        r.append(' ');
7652                    }
7653                    r.append(p.info.name);
7654                }
7655            }
7656            if (r != null) {
7657                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7658            }
7659
7660            N = pkg.services.size();
7661            r = null;
7662            for (i=0; i<N; i++) {
7663                PackageParser.Service s = pkg.services.get(i);
7664                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7665                        s.info.processName, pkg.applicationInfo.uid);
7666                mServices.addService(s);
7667                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7668                    if (r == null) {
7669                        r = new StringBuilder(256);
7670                    } else {
7671                        r.append(' ');
7672                    }
7673                    r.append(s.info.name);
7674                }
7675            }
7676            if (r != null) {
7677                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7678            }
7679
7680            N = pkg.receivers.size();
7681            r = null;
7682            for (i=0; i<N; i++) {
7683                PackageParser.Activity a = pkg.receivers.get(i);
7684                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7685                        a.info.processName, pkg.applicationInfo.uid);
7686                mReceivers.addActivity(a, "receiver");
7687                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7688                    if (r == null) {
7689                        r = new StringBuilder(256);
7690                    } else {
7691                        r.append(' ');
7692                    }
7693                    r.append(a.info.name);
7694                }
7695            }
7696            if (r != null) {
7697                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7698            }
7699
7700            N = pkg.activities.size();
7701            r = null;
7702            for (i=0; i<N; i++) {
7703                PackageParser.Activity a = pkg.activities.get(i);
7704                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7705                        a.info.processName, pkg.applicationInfo.uid);
7706                mActivities.addActivity(a, "activity");
7707                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7708                    if (r == null) {
7709                        r = new StringBuilder(256);
7710                    } else {
7711                        r.append(' ');
7712                    }
7713                    r.append(a.info.name);
7714                }
7715            }
7716            if (r != null) {
7717                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7718            }
7719
7720            N = pkg.permissionGroups.size();
7721            r = null;
7722            for (i=0; i<N; i++) {
7723                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7724                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7725                if (cur == null) {
7726                    mPermissionGroups.put(pg.info.name, pg);
7727                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7728                        if (r == null) {
7729                            r = new StringBuilder(256);
7730                        } else {
7731                            r.append(' ');
7732                        }
7733                        r.append(pg.info.name);
7734                    }
7735                } else {
7736                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7737                            + pg.info.packageName + " ignored: original from "
7738                            + cur.info.packageName);
7739                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7740                        if (r == null) {
7741                            r = new StringBuilder(256);
7742                        } else {
7743                            r.append(' ');
7744                        }
7745                        r.append("DUP:");
7746                        r.append(pg.info.name);
7747                    }
7748                }
7749            }
7750            if (r != null) {
7751                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7752            }
7753
7754            N = pkg.permissions.size();
7755            r = null;
7756            for (i=0; i<N; i++) {
7757                PackageParser.Permission p = pkg.permissions.get(i);
7758
7759                // Assume by default that we did not install this permission into the system.
7760                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7761
7762                // Now that permission groups have a special meaning, we ignore permission
7763                // groups for legacy apps to prevent unexpected behavior. In particular,
7764                // permissions for one app being granted to someone just becuase they happen
7765                // to be in a group defined by another app (before this had no implications).
7766                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7767                    p.group = mPermissionGroups.get(p.info.group);
7768                    // Warn for a permission in an unknown group.
7769                    if (p.info.group != null && p.group == null) {
7770                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7771                                + p.info.packageName + " in an unknown group " + p.info.group);
7772                    }
7773                }
7774
7775                ArrayMap<String, BasePermission> permissionMap =
7776                        p.tree ? mSettings.mPermissionTrees
7777                                : mSettings.mPermissions;
7778                BasePermission bp = permissionMap.get(p.info.name);
7779
7780                // Allow system apps to redefine non-system permissions
7781                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7782                    final boolean currentOwnerIsSystem = (bp.perm != null
7783                            && isSystemApp(bp.perm.owner));
7784                    if (isSystemApp(p.owner)) {
7785                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7786                            // It's a built-in permission and no owner, take ownership now
7787                            bp.packageSetting = pkgSetting;
7788                            bp.perm = p;
7789                            bp.uid = pkg.applicationInfo.uid;
7790                            bp.sourcePackage = p.info.packageName;
7791                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7792                        } else if (!currentOwnerIsSystem) {
7793                            String msg = "New decl " + p.owner + " of permission  "
7794                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7795                            reportSettingsProblem(Log.WARN, msg);
7796                            bp = null;
7797                        }
7798                    }
7799                }
7800
7801                if (bp == null) {
7802                    bp = new BasePermission(p.info.name, p.info.packageName,
7803                            BasePermission.TYPE_NORMAL);
7804                    permissionMap.put(p.info.name, bp);
7805                }
7806
7807                if (bp.perm == null) {
7808                    if (bp.sourcePackage == null
7809                            || bp.sourcePackage.equals(p.info.packageName)) {
7810                        BasePermission tree = findPermissionTreeLP(p.info.name);
7811                        if (tree == null
7812                                || tree.sourcePackage.equals(p.info.packageName)) {
7813                            bp.packageSetting = pkgSetting;
7814                            bp.perm = p;
7815                            bp.uid = pkg.applicationInfo.uid;
7816                            bp.sourcePackage = p.info.packageName;
7817                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7818                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7819                                if (r == null) {
7820                                    r = new StringBuilder(256);
7821                                } else {
7822                                    r.append(' ');
7823                                }
7824                                r.append(p.info.name);
7825                            }
7826                        } else {
7827                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7828                                    + p.info.packageName + " ignored: base tree "
7829                                    + tree.name + " is from package "
7830                                    + tree.sourcePackage);
7831                        }
7832                    } else {
7833                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7834                                + p.info.packageName + " ignored: original from "
7835                                + bp.sourcePackage);
7836                    }
7837                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7838                    if (r == null) {
7839                        r = new StringBuilder(256);
7840                    } else {
7841                        r.append(' ');
7842                    }
7843                    r.append("DUP:");
7844                    r.append(p.info.name);
7845                }
7846                if (bp.perm == p) {
7847                    bp.protectionLevel = p.info.protectionLevel;
7848                }
7849            }
7850
7851            if (r != null) {
7852                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7853            }
7854
7855            N = pkg.instrumentation.size();
7856            r = null;
7857            for (i=0; i<N; i++) {
7858                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7859                a.info.packageName = pkg.applicationInfo.packageName;
7860                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7861                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7862                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7863                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7864                a.info.dataDir = pkg.applicationInfo.dataDir;
7865                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7866                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7867
7868                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7869                // need other information about the application, like the ABI and what not ?
7870                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7871                mInstrumentation.put(a.getComponentName(), a);
7872                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7873                    if (r == null) {
7874                        r = new StringBuilder(256);
7875                    } else {
7876                        r.append(' ');
7877                    }
7878                    r.append(a.info.name);
7879                }
7880            }
7881            if (r != null) {
7882                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7883            }
7884
7885            if (pkg.protectedBroadcasts != null) {
7886                N = pkg.protectedBroadcasts.size();
7887                for (i=0; i<N; i++) {
7888                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7889                }
7890            }
7891
7892            pkgSetting.setTimeStamp(scanFileTime);
7893
7894            // Create idmap files for pairs of (packages, overlay packages).
7895            // Note: "android", ie framework-res.apk, is handled by native layers.
7896            if (pkg.mOverlayTarget != null) {
7897                // This is an overlay package.
7898                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7899                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7900                        mOverlays.put(pkg.mOverlayTarget,
7901                                new ArrayMap<String, PackageParser.Package>());
7902                    }
7903                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7904                    map.put(pkg.packageName, pkg);
7905                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7906                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7907                        createIdmapFailed = true;
7908                    }
7909                }
7910            } else if (mOverlays.containsKey(pkg.packageName) &&
7911                    !pkg.packageName.equals("android")) {
7912                // This is a regular package, with one or more known overlay packages.
7913                createIdmapsForPackageLI(pkg);
7914            }
7915        }
7916
7917        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7918
7919        if (createIdmapFailed) {
7920            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7921                    "scanPackageLI failed to createIdmap");
7922        }
7923        return pkg;
7924    }
7925
7926    /**
7927     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7928     * is derived purely on the basis of the contents of {@code scanFile} and
7929     * {@code cpuAbiOverride}.
7930     *
7931     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7932     */
7933    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7934                                 String cpuAbiOverride, boolean extractLibs)
7935            throws PackageManagerException {
7936        // TODO: We can probably be smarter about this stuff. For installed apps,
7937        // we can calculate this information at install time once and for all. For
7938        // system apps, we can probably assume that this information doesn't change
7939        // after the first boot scan. As things stand, we do lots of unnecessary work.
7940
7941        // Give ourselves some initial paths; we'll come back for another
7942        // pass once we've determined ABI below.
7943        setNativeLibraryPaths(pkg);
7944
7945        // We would never need to extract libs for forward-locked and external packages,
7946        // since the container service will do it for us. We shouldn't attempt to
7947        // extract libs from system app when it was not updated.
7948        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7949                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7950            extractLibs = false;
7951        }
7952
7953        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7954        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7955
7956        NativeLibraryHelper.Handle handle = null;
7957        try {
7958            handle = NativeLibraryHelper.Handle.create(pkg);
7959            // TODO(multiArch): This can be null for apps that didn't go through the
7960            // usual installation process. We can calculate it again, like we
7961            // do during install time.
7962            //
7963            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7964            // unnecessary.
7965            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7966
7967            // Null out the abis so that they can be recalculated.
7968            pkg.applicationInfo.primaryCpuAbi = null;
7969            pkg.applicationInfo.secondaryCpuAbi = null;
7970            if (isMultiArch(pkg.applicationInfo)) {
7971                // Warn if we've set an abiOverride for multi-lib packages..
7972                // By definition, we need to copy both 32 and 64 bit libraries for
7973                // such packages.
7974                if (pkg.cpuAbiOverride != null
7975                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7976                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7977                }
7978
7979                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7980                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7981                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7982                    if (extractLibs) {
7983                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7984                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7985                                useIsaSpecificSubdirs);
7986                    } else {
7987                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7988                    }
7989                }
7990
7991                maybeThrowExceptionForMultiArchCopy(
7992                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7993
7994                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7995                    if (extractLibs) {
7996                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7997                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7998                                useIsaSpecificSubdirs);
7999                    } else {
8000                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8001                    }
8002                }
8003
8004                maybeThrowExceptionForMultiArchCopy(
8005                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8006
8007                if (abi64 >= 0) {
8008                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8009                }
8010
8011                if (abi32 >= 0) {
8012                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8013                    if (abi64 >= 0) {
8014                        pkg.applicationInfo.secondaryCpuAbi = abi;
8015                    } else {
8016                        pkg.applicationInfo.primaryCpuAbi = abi;
8017                    }
8018                }
8019            } else {
8020                String[] abiList = (cpuAbiOverride != null) ?
8021                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8022
8023                // Enable gross and lame hacks for apps that are built with old
8024                // SDK tools. We must scan their APKs for renderscript bitcode and
8025                // not launch them if it's present. Don't bother checking on devices
8026                // that don't have 64 bit support.
8027                boolean needsRenderScriptOverride = false;
8028                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8029                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8030                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8031                    needsRenderScriptOverride = true;
8032                }
8033
8034                final int copyRet;
8035                if (extractLibs) {
8036                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8037                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8038                } else {
8039                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8040                }
8041
8042                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8043                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8044                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8045                }
8046
8047                if (copyRet >= 0) {
8048                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8049                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8050                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8051                } else if (needsRenderScriptOverride) {
8052                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8053                }
8054            }
8055        } catch (IOException ioe) {
8056            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8057        } finally {
8058            IoUtils.closeQuietly(handle);
8059        }
8060
8061        // Now that we've calculated the ABIs and determined if it's an internal app,
8062        // we will go ahead and populate the nativeLibraryPath.
8063        setNativeLibraryPaths(pkg);
8064    }
8065
8066    /**
8067     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8068     * i.e, so that all packages can be run inside a single process if required.
8069     *
8070     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8071     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8072     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8073     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8074     * updating a package that belongs to a shared user.
8075     *
8076     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8077     * adds unnecessary complexity.
8078     */
8079    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8080            PackageParser.Package scannedPackage, boolean bootComplete) {
8081        String requiredInstructionSet = null;
8082        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8083            requiredInstructionSet = VMRuntime.getInstructionSet(
8084                     scannedPackage.applicationInfo.primaryCpuAbi);
8085        }
8086
8087        PackageSetting requirer = null;
8088        for (PackageSetting ps : packagesForUser) {
8089            // If packagesForUser contains scannedPackage, we skip it. This will happen
8090            // when scannedPackage is an update of an existing package. Without this check,
8091            // we will never be able to change the ABI of any package belonging to a shared
8092            // user, even if it's compatible with other packages.
8093            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8094                if (ps.primaryCpuAbiString == null) {
8095                    continue;
8096                }
8097
8098                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8099                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8100                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8101                    // this but there's not much we can do.
8102                    String errorMessage = "Instruction set mismatch, "
8103                            + ((requirer == null) ? "[caller]" : requirer)
8104                            + " requires " + requiredInstructionSet + " whereas " + ps
8105                            + " requires " + instructionSet;
8106                    Slog.w(TAG, errorMessage);
8107                }
8108
8109                if (requiredInstructionSet == null) {
8110                    requiredInstructionSet = instructionSet;
8111                    requirer = ps;
8112                }
8113            }
8114        }
8115
8116        if (requiredInstructionSet != null) {
8117            String adjustedAbi;
8118            if (requirer != null) {
8119                // requirer != null implies that either scannedPackage was null or that scannedPackage
8120                // did not require an ABI, in which case we have to adjust scannedPackage to match
8121                // the ABI of the set (which is the same as requirer's ABI)
8122                adjustedAbi = requirer.primaryCpuAbiString;
8123                if (scannedPackage != null) {
8124                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8125                }
8126            } else {
8127                // requirer == null implies that we're updating all ABIs in the set to
8128                // match scannedPackage.
8129                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8130            }
8131
8132            for (PackageSetting ps : packagesForUser) {
8133                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8134                    if (ps.primaryCpuAbiString != null) {
8135                        continue;
8136                    }
8137
8138                    ps.primaryCpuAbiString = adjustedAbi;
8139                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8140                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8141                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8142                        mInstaller.rmdex(ps.codePathString,
8143                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8144                    }
8145                }
8146            }
8147        }
8148    }
8149
8150    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8151        synchronized (mPackages) {
8152            mResolverReplaced = true;
8153            // Set up information for custom user intent resolution activity.
8154            mResolveActivity.applicationInfo = pkg.applicationInfo;
8155            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8156            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8157            mResolveActivity.processName = pkg.applicationInfo.packageName;
8158            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8159            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8160                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8161            mResolveActivity.theme = 0;
8162            mResolveActivity.exported = true;
8163            mResolveActivity.enabled = true;
8164            mResolveInfo.activityInfo = mResolveActivity;
8165            mResolveInfo.priority = 0;
8166            mResolveInfo.preferredOrder = 0;
8167            mResolveInfo.match = 0;
8168            mResolveComponentName = mCustomResolverComponentName;
8169            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8170                    mResolveComponentName);
8171        }
8172    }
8173
8174    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8175        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8176
8177        // Set up information for ephemeral installer activity
8178        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8179        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8180        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8181        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8182        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8183        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8184                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8185        mEphemeralInstallerActivity.theme = 0;
8186        mEphemeralInstallerActivity.exported = true;
8187        mEphemeralInstallerActivity.enabled = true;
8188        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8189        mEphemeralInstallerInfo.priority = 0;
8190        mEphemeralInstallerInfo.preferredOrder = 0;
8191        mEphemeralInstallerInfo.match = 0;
8192
8193        if (DEBUG_EPHEMERAL) {
8194            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8195        }
8196    }
8197
8198    private static String calculateBundledApkRoot(final String codePathString) {
8199        final File codePath = new File(codePathString);
8200        final File codeRoot;
8201        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8202            codeRoot = Environment.getRootDirectory();
8203        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8204            codeRoot = Environment.getOemDirectory();
8205        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8206            codeRoot = Environment.getVendorDirectory();
8207        } else {
8208            // Unrecognized code path; take its top real segment as the apk root:
8209            // e.g. /something/app/blah.apk => /something
8210            try {
8211                File f = codePath.getCanonicalFile();
8212                File parent = f.getParentFile();    // non-null because codePath is a file
8213                File tmp;
8214                while ((tmp = parent.getParentFile()) != null) {
8215                    f = parent;
8216                    parent = tmp;
8217                }
8218                codeRoot = f;
8219                Slog.w(TAG, "Unrecognized code path "
8220                        + codePath + " - using " + codeRoot);
8221            } catch (IOException e) {
8222                // Can't canonicalize the code path -- shenanigans?
8223                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8224                return Environment.getRootDirectory().getPath();
8225            }
8226        }
8227        return codeRoot.getPath();
8228    }
8229
8230    /**
8231     * Derive and set the location of native libraries for the given package,
8232     * which varies depending on where and how the package was installed.
8233     */
8234    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8235        final ApplicationInfo info = pkg.applicationInfo;
8236        final String codePath = pkg.codePath;
8237        final File codeFile = new File(codePath);
8238        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8239        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8240
8241        info.nativeLibraryRootDir = null;
8242        info.nativeLibraryRootRequiresIsa = false;
8243        info.nativeLibraryDir = null;
8244        info.secondaryNativeLibraryDir = null;
8245
8246        if (isApkFile(codeFile)) {
8247            // Monolithic install
8248            if (bundledApp) {
8249                // If "/system/lib64/apkname" exists, assume that is the per-package
8250                // native library directory to use; otherwise use "/system/lib/apkname".
8251                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8252                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8253                        getPrimaryInstructionSet(info));
8254
8255                // This is a bundled system app so choose the path based on the ABI.
8256                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8257                // is just the default path.
8258                final String apkName = deriveCodePathName(codePath);
8259                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8260                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8261                        apkName).getAbsolutePath();
8262
8263                if (info.secondaryCpuAbi != null) {
8264                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8265                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8266                            secondaryLibDir, apkName).getAbsolutePath();
8267                }
8268            } else if (asecApp) {
8269                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8270                        .getAbsolutePath();
8271            } else {
8272                final String apkName = deriveCodePathName(codePath);
8273                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8274                        .getAbsolutePath();
8275            }
8276
8277            info.nativeLibraryRootRequiresIsa = false;
8278            info.nativeLibraryDir = info.nativeLibraryRootDir;
8279        } else {
8280            // Cluster install
8281            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8282            info.nativeLibraryRootRequiresIsa = true;
8283
8284            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8285                    getPrimaryInstructionSet(info)).getAbsolutePath();
8286
8287            if (info.secondaryCpuAbi != null) {
8288                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8289                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8290            }
8291        }
8292    }
8293
8294    /**
8295     * Calculate the abis and roots for a bundled app. These can uniquely
8296     * be determined from the contents of the system partition, i.e whether
8297     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8298     * of this information, and instead assume that the system was built
8299     * sensibly.
8300     */
8301    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8302                                           PackageSetting pkgSetting) {
8303        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8304
8305        // If "/system/lib64/apkname" exists, assume that is the per-package
8306        // native library directory to use; otherwise use "/system/lib/apkname".
8307        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8308        setBundledAppAbi(pkg, apkRoot, apkName);
8309        // pkgSetting might be null during rescan following uninstall of updates
8310        // to a bundled app, so accommodate that possibility.  The settings in
8311        // that case will be established later from the parsed package.
8312        //
8313        // If the settings aren't null, sync them up with what we've just derived.
8314        // note that apkRoot isn't stored in the package settings.
8315        if (pkgSetting != null) {
8316            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8317            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8318        }
8319    }
8320
8321    /**
8322     * Deduces the ABI of a bundled app and sets the relevant fields on the
8323     * parsed pkg object.
8324     *
8325     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8326     *        under which system libraries are installed.
8327     * @param apkName the name of the installed package.
8328     */
8329    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8330        final File codeFile = new File(pkg.codePath);
8331
8332        final boolean has64BitLibs;
8333        final boolean has32BitLibs;
8334        if (isApkFile(codeFile)) {
8335            // Monolithic install
8336            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8337            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8338        } else {
8339            // Cluster install
8340            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8341            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8342                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8343                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8344                has64BitLibs = (new File(rootDir, isa)).exists();
8345            } else {
8346                has64BitLibs = false;
8347            }
8348            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8349                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8350                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8351                has32BitLibs = (new File(rootDir, isa)).exists();
8352            } else {
8353                has32BitLibs = false;
8354            }
8355        }
8356
8357        if (has64BitLibs && !has32BitLibs) {
8358            // The package has 64 bit libs, but not 32 bit libs. Its primary
8359            // ABI should be 64 bit. We can safely assume here that the bundled
8360            // native libraries correspond to the most preferred ABI in the list.
8361
8362            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8363            pkg.applicationInfo.secondaryCpuAbi = null;
8364        } else if (has32BitLibs && !has64BitLibs) {
8365            // The package has 32 bit libs but not 64 bit libs. Its primary
8366            // ABI should be 32 bit.
8367
8368            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8369            pkg.applicationInfo.secondaryCpuAbi = null;
8370        } else if (has32BitLibs && has64BitLibs) {
8371            // The application has both 64 and 32 bit bundled libraries. We check
8372            // here that the app declares multiArch support, and warn if it doesn't.
8373            //
8374            // We will be lenient here and record both ABIs. The primary will be the
8375            // ABI that's higher on the list, i.e, a device that's configured to prefer
8376            // 64 bit apps will see a 64 bit primary ABI,
8377
8378            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8379                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8380            }
8381
8382            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8383                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8384                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8385            } else {
8386                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8387                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8388            }
8389        } else {
8390            pkg.applicationInfo.primaryCpuAbi = null;
8391            pkg.applicationInfo.secondaryCpuAbi = null;
8392        }
8393    }
8394
8395    private void killApplication(String pkgName, int appId, String reason) {
8396        // Request the ActivityManager to kill the process(only for existing packages)
8397        // so that we do not end up in a confused state while the user is still using the older
8398        // version of the application while the new one gets installed.
8399        IActivityManager am = ActivityManagerNative.getDefault();
8400        if (am != null) {
8401            try {
8402                am.killApplicationWithAppId(pkgName, appId, reason);
8403            } catch (RemoteException e) {
8404            }
8405        }
8406    }
8407
8408    void removePackageLI(PackageSetting ps, boolean chatty) {
8409        if (DEBUG_INSTALL) {
8410            if (chatty)
8411                Log.d(TAG, "Removing package " + ps.name);
8412        }
8413
8414        // writer
8415        synchronized (mPackages) {
8416            mPackages.remove(ps.name);
8417            final PackageParser.Package pkg = ps.pkg;
8418            if (pkg != null) {
8419                cleanPackageDataStructuresLILPw(pkg, chatty);
8420            }
8421        }
8422    }
8423
8424    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8425        if (DEBUG_INSTALL) {
8426            if (chatty)
8427                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8428        }
8429
8430        // writer
8431        synchronized (mPackages) {
8432            mPackages.remove(pkg.applicationInfo.packageName);
8433            cleanPackageDataStructuresLILPw(pkg, chatty);
8434        }
8435    }
8436
8437    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8438        int N = pkg.providers.size();
8439        StringBuilder r = null;
8440        int i;
8441        for (i=0; i<N; i++) {
8442            PackageParser.Provider p = pkg.providers.get(i);
8443            mProviders.removeProvider(p);
8444            if (p.info.authority == null) {
8445
8446                /* There was another ContentProvider with this authority when
8447                 * this app was installed so this authority is null,
8448                 * Ignore it as we don't have to unregister the provider.
8449                 */
8450                continue;
8451            }
8452            String names[] = p.info.authority.split(";");
8453            for (int j = 0; j < names.length; j++) {
8454                if (mProvidersByAuthority.get(names[j]) == p) {
8455                    mProvidersByAuthority.remove(names[j]);
8456                    if (DEBUG_REMOVE) {
8457                        if (chatty)
8458                            Log.d(TAG, "Unregistered content provider: " + names[j]
8459                                    + ", className = " + p.info.name + ", isSyncable = "
8460                                    + p.info.isSyncable);
8461                    }
8462                }
8463            }
8464            if (DEBUG_REMOVE && chatty) {
8465                if (r == null) {
8466                    r = new StringBuilder(256);
8467                } else {
8468                    r.append(' ');
8469                }
8470                r.append(p.info.name);
8471            }
8472        }
8473        if (r != null) {
8474            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8475        }
8476
8477        N = pkg.services.size();
8478        r = null;
8479        for (i=0; i<N; i++) {
8480            PackageParser.Service s = pkg.services.get(i);
8481            mServices.removeService(s);
8482            if (chatty) {
8483                if (r == null) {
8484                    r = new StringBuilder(256);
8485                } else {
8486                    r.append(' ');
8487                }
8488                r.append(s.info.name);
8489            }
8490        }
8491        if (r != null) {
8492            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8493        }
8494
8495        N = pkg.receivers.size();
8496        r = null;
8497        for (i=0; i<N; i++) {
8498            PackageParser.Activity a = pkg.receivers.get(i);
8499            mReceivers.removeActivity(a, "receiver");
8500            if (DEBUG_REMOVE && chatty) {
8501                if (r == null) {
8502                    r = new StringBuilder(256);
8503                } else {
8504                    r.append(' ');
8505                }
8506                r.append(a.info.name);
8507            }
8508        }
8509        if (r != null) {
8510            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8511        }
8512
8513        N = pkg.activities.size();
8514        r = null;
8515        for (i=0; i<N; i++) {
8516            PackageParser.Activity a = pkg.activities.get(i);
8517            mActivities.removeActivity(a, "activity");
8518            if (DEBUG_REMOVE && chatty) {
8519                if (r == null) {
8520                    r = new StringBuilder(256);
8521                } else {
8522                    r.append(' ');
8523                }
8524                r.append(a.info.name);
8525            }
8526        }
8527        if (r != null) {
8528            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8529        }
8530
8531        N = pkg.permissions.size();
8532        r = null;
8533        for (i=0; i<N; i++) {
8534            PackageParser.Permission p = pkg.permissions.get(i);
8535            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8536            if (bp == null) {
8537                bp = mSettings.mPermissionTrees.get(p.info.name);
8538            }
8539            if (bp != null && bp.perm == p) {
8540                bp.perm = null;
8541                if (DEBUG_REMOVE && chatty) {
8542                    if (r == null) {
8543                        r = new StringBuilder(256);
8544                    } else {
8545                        r.append(' ');
8546                    }
8547                    r.append(p.info.name);
8548                }
8549            }
8550            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8551                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8552                if (appOpPkgs != null) {
8553                    appOpPkgs.remove(pkg.packageName);
8554                }
8555            }
8556        }
8557        if (r != null) {
8558            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8559        }
8560
8561        N = pkg.requestedPermissions.size();
8562        r = null;
8563        for (i=0; i<N; i++) {
8564            String perm = pkg.requestedPermissions.get(i);
8565            BasePermission bp = mSettings.mPermissions.get(perm);
8566            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8567                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8568                if (appOpPkgs != null) {
8569                    appOpPkgs.remove(pkg.packageName);
8570                    if (appOpPkgs.isEmpty()) {
8571                        mAppOpPermissionPackages.remove(perm);
8572                    }
8573                }
8574            }
8575        }
8576        if (r != null) {
8577            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8578        }
8579
8580        N = pkg.instrumentation.size();
8581        r = null;
8582        for (i=0; i<N; i++) {
8583            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8584            mInstrumentation.remove(a.getComponentName());
8585            if (DEBUG_REMOVE && chatty) {
8586                if (r == null) {
8587                    r = new StringBuilder(256);
8588                } else {
8589                    r.append(' ');
8590                }
8591                r.append(a.info.name);
8592            }
8593        }
8594        if (r != null) {
8595            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8596        }
8597
8598        r = null;
8599        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8600            // Only system apps can hold shared libraries.
8601            if (pkg.libraryNames != null) {
8602                for (i=0; i<pkg.libraryNames.size(); i++) {
8603                    String name = pkg.libraryNames.get(i);
8604                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8605                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8606                        mSharedLibraries.remove(name);
8607                        if (DEBUG_REMOVE && chatty) {
8608                            if (r == null) {
8609                                r = new StringBuilder(256);
8610                            } else {
8611                                r.append(' ');
8612                            }
8613                            r.append(name);
8614                        }
8615                    }
8616                }
8617            }
8618        }
8619        if (r != null) {
8620            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8621        }
8622    }
8623
8624    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8625        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8626            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8627                return true;
8628            }
8629        }
8630        return false;
8631    }
8632
8633    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8634    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8635    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8636
8637    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8638            int flags) {
8639        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8640        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8641    }
8642
8643    private void updatePermissionsLPw(String changingPkg,
8644            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8645        // Make sure there are no dangling permission trees.
8646        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8647        while (it.hasNext()) {
8648            final BasePermission bp = it.next();
8649            if (bp.packageSetting == null) {
8650                // We may not yet have parsed the package, so just see if
8651                // we still know about its settings.
8652                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8653            }
8654            if (bp.packageSetting == null) {
8655                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8656                        + " from package " + bp.sourcePackage);
8657                it.remove();
8658            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8659                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8660                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8661                            + " from package " + bp.sourcePackage);
8662                    flags |= UPDATE_PERMISSIONS_ALL;
8663                    it.remove();
8664                }
8665            }
8666        }
8667
8668        // Make sure all dynamic permissions have been assigned to a package,
8669        // and make sure there are no dangling permissions.
8670        it = mSettings.mPermissions.values().iterator();
8671        while (it.hasNext()) {
8672            final BasePermission bp = it.next();
8673            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8674                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8675                        + bp.name + " pkg=" + bp.sourcePackage
8676                        + " info=" + bp.pendingInfo);
8677                if (bp.packageSetting == null && bp.pendingInfo != null) {
8678                    final BasePermission tree = findPermissionTreeLP(bp.name);
8679                    if (tree != null && tree.perm != null) {
8680                        bp.packageSetting = tree.packageSetting;
8681                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8682                                new PermissionInfo(bp.pendingInfo));
8683                        bp.perm.info.packageName = tree.perm.info.packageName;
8684                        bp.perm.info.name = bp.name;
8685                        bp.uid = tree.uid;
8686                    }
8687                }
8688            }
8689            if (bp.packageSetting == null) {
8690                // We may not yet have parsed the package, so just see if
8691                // we still know about its settings.
8692                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8693            }
8694            if (bp.packageSetting == null) {
8695                Slog.w(TAG, "Removing dangling permission: " + bp.name
8696                        + " from package " + bp.sourcePackage);
8697                it.remove();
8698            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8699                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8700                    Slog.i(TAG, "Removing old permission: " + bp.name
8701                            + " from package " + bp.sourcePackage);
8702                    flags |= UPDATE_PERMISSIONS_ALL;
8703                    it.remove();
8704                }
8705            }
8706        }
8707
8708        // Now update the permissions for all packages, in particular
8709        // replace the granted permissions of the system packages.
8710        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8711            for (PackageParser.Package pkg : mPackages.values()) {
8712                if (pkg != pkgInfo) {
8713                    // Only replace for packages on requested volume
8714                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8715                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8716                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8717                    grantPermissionsLPw(pkg, replace, changingPkg);
8718                }
8719            }
8720        }
8721
8722        if (pkgInfo != null) {
8723            // Only replace for packages on requested volume
8724            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8725            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8726                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8727            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8728        }
8729    }
8730
8731    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8732            String packageOfInterest) {
8733        // IMPORTANT: There are two types of permissions: install and runtime.
8734        // Install time permissions are granted when the app is installed to
8735        // all device users and users added in the future. Runtime permissions
8736        // are granted at runtime explicitly to specific users. Normal and signature
8737        // protected permissions are install time permissions. Dangerous permissions
8738        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8739        // otherwise they are runtime permissions. This function does not manage
8740        // runtime permissions except for the case an app targeting Lollipop MR1
8741        // being upgraded to target a newer SDK, in which case dangerous permissions
8742        // are transformed from install time to runtime ones.
8743
8744        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8745        if (ps == null) {
8746            return;
8747        }
8748
8749        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8750
8751        PermissionsState permissionsState = ps.getPermissionsState();
8752        PermissionsState origPermissions = permissionsState;
8753
8754        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8755
8756        boolean runtimePermissionsRevoked = false;
8757        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8758
8759        boolean changedInstallPermission = false;
8760
8761        if (replace) {
8762            ps.installPermissionsFixed = false;
8763            if (!ps.isSharedUser()) {
8764                origPermissions = new PermissionsState(permissionsState);
8765                permissionsState.reset();
8766            } else {
8767                // We need to know only about runtime permission changes since the
8768                // calling code always writes the install permissions state but
8769                // the runtime ones are written only if changed. The only cases of
8770                // changed runtime permissions here are promotion of an install to
8771                // runtime and revocation of a runtime from a shared user.
8772                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8773                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8774                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8775                    runtimePermissionsRevoked = true;
8776                }
8777            }
8778        }
8779
8780        permissionsState.setGlobalGids(mGlobalGids);
8781
8782        final int N = pkg.requestedPermissions.size();
8783        for (int i=0; i<N; i++) {
8784            final String name = pkg.requestedPermissions.get(i);
8785            final BasePermission bp = mSettings.mPermissions.get(name);
8786
8787            if (DEBUG_INSTALL) {
8788                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8789            }
8790
8791            if (bp == null || bp.packageSetting == null) {
8792                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8793                    Slog.w(TAG, "Unknown permission " + name
8794                            + " in package " + pkg.packageName);
8795                }
8796                continue;
8797            }
8798
8799            final String perm = bp.name;
8800            boolean allowedSig = false;
8801            int grant = GRANT_DENIED;
8802
8803            // Keep track of app op permissions.
8804            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8805                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8806                if (pkgs == null) {
8807                    pkgs = new ArraySet<>();
8808                    mAppOpPermissionPackages.put(bp.name, pkgs);
8809                }
8810                pkgs.add(pkg.packageName);
8811            }
8812
8813            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8814            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8815                    >= Build.VERSION_CODES.M;
8816            switch (level) {
8817                case PermissionInfo.PROTECTION_NORMAL: {
8818                    // For all apps normal permissions are install time ones.
8819                    grant = GRANT_INSTALL;
8820                } break;
8821
8822                case PermissionInfo.PROTECTION_DANGEROUS: {
8823                    // If a permission review is required for legacy apps we represent
8824                    // their permissions as always granted runtime ones since we need
8825                    // to keep the review required permission flag per user while an
8826                    // install permission's state is shared across all users.
8827                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8828                        // For legacy apps dangerous permissions are install time ones.
8829                        grant = GRANT_INSTALL;
8830                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8831                        // For legacy apps that became modern, install becomes runtime.
8832                        grant = GRANT_UPGRADE;
8833                    } else if (mPromoteSystemApps
8834                            && isSystemApp(ps)
8835                            && mExistingSystemPackages.contains(ps.name)) {
8836                        // For legacy system apps, install becomes runtime.
8837                        // We cannot check hasInstallPermission() for system apps since those
8838                        // permissions were granted implicitly and not persisted pre-M.
8839                        grant = GRANT_UPGRADE;
8840                    } else {
8841                        // For modern apps keep runtime permissions unchanged.
8842                        grant = GRANT_RUNTIME;
8843                    }
8844                } break;
8845
8846                case PermissionInfo.PROTECTION_SIGNATURE: {
8847                    // For all apps signature permissions are install time ones.
8848                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8849                    if (allowedSig) {
8850                        grant = GRANT_INSTALL;
8851                    }
8852                } break;
8853            }
8854
8855            if (DEBUG_INSTALL) {
8856                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8857            }
8858
8859            if (grant != GRANT_DENIED) {
8860                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8861                    // If this is an existing, non-system package, then
8862                    // we can't add any new permissions to it.
8863                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8864                        // Except...  if this is a permission that was added
8865                        // to the platform (note: need to only do this when
8866                        // updating the platform).
8867                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8868                            grant = GRANT_DENIED;
8869                        }
8870                    }
8871                }
8872
8873                switch (grant) {
8874                    case GRANT_INSTALL: {
8875                        // Revoke this as runtime permission to handle the case of
8876                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8877                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8878                            if (origPermissions.getRuntimePermissionState(
8879                                    bp.name, userId) != null) {
8880                                // Revoke the runtime permission and clear the flags.
8881                                origPermissions.revokeRuntimePermission(bp, userId);
8882                                origPermissions.updatePermissionFlags(bp, userId,
8883                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8884                                // If we revoked a permission permission, we have to write.
8885                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8886                                        changedRuntimePermissionUserIds, userId);
8887                            }
8888                        }
8889                        // Grant an install permission.
8890                        if (permissionsState.grantInstallPermission(bp) !=
8891                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8892                            changedInstallPermission = true;
8893                        }
8894                    } break;
8895
8896                    case GRANT_RUNTIME: {
8897                        // Grant previously granted runtime permissions.
8898                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8899                            PermissionState permissionState = origPermissions
8900                                    .getRuntimePermissionState(bp.name, userId);
8901                            int flags = permissionState != null
8902                                    ? permissionState.getFlags() : 0;
8903                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8904                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8905                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8906                                    // If we cannot put the permission as it was, we have to write.
8907                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8908                                            changedRuntimePermissionUserIds, userId);
8909                                }
8910                                // If the app supports runtime permissions no need for a review.
8911                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8912                                        && appSupportsRuntimePermissions
8913                                        && (flags & PackageManager
8914                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8915                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8916                                    // Since we changed the flags, we have to write.
8917                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8918                                            changedRuntimePermissionUserIds, userId);
8919                                }
8920                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8921                                    && !appSupportsRuntimePermissions) {
8922                                // For legacy apps that need a permission review, every new
8923                                // runtime permission is granted but it is pending a review.
8924                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8925                                    permissionsState.grantRuntimePermission(bp, userId);
8926                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8927                                    // We changed the permission and flags, hence have to write.
8928                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8929                                            changedRuntimePermissionUserIds, userId);
8930                                }
8931                            }
8932                            // Propagate the permission flags.
8933                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8934                        }
8935                    } break;
8936
8937                    case GRANT_UPGRADE: {
8938                        // Grant runtime permissions for a previously held install permission.
8939                        PermissionState permissionState = origPermissions
8940                                .getInstallPermissionState(bp.name);
8941                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8942
8943                        if (origPermissions.revokeInstallPermission(bp)
8944                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8945                            // We will be transferring the permission flags, so clear them.
8946                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8947                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8948                            changedInstallPermission = true;
8949                        }
8950
8951                        // If the permission is not to be promoted to runtime we ignore it and
8952                        // also its other flags as they are not applicable to install permissions.
8953                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8954                            for (int userId : currentUserIds) {
8955                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8956                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8957                                    // Transfer the permission flags.
8958                                    permissionsState.updatePermissionFlags(bp, userId,
8959                                            flags, flags);
8960                                    // If we granted the permission, we have to write.
8961                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8962                                            changedRuntimePermissionUserIds, userId);
8963                                }
8964                            }
8965                        }
8966                    } break;
8967
8968                    default: {
8969                        if (packageOfInterest == null
8970                                || packageOfInterest.equals(pkg.packageName)) {
8971                            Slog.w(TAG, "Not granting permission " + perm
8972                                    + " to package " + pkg.packageName
8973                                    + " because it was previously installed without");
8974                        }
8975                    } break;
8976                }
8977            } else {
8978                if (permissionsState.revokeInstallPermission(bp) !=
8979                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8980                    // Also drop the permission flags.
8981                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8982                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8983                    changedInstallPermission = true;
8984                    Slog.i(TAG, "Un-granting permission " + perm
8985                            + " from package " + pkg.packageName
8986                            + " (protectionLevel=" + bp.protectionLevel
8987                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8988                            + ")");
8989                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8990                    // Don't print warning for app op permissions, since it is fine for them
8991                    // not to be granted, there is a UI for the user to decide.
8992                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8993                        Slog.w(TAG, "Not granting permission " + perm
8994                                + " to package " + pkg.packageName
8995                                + " (protectionLevel=" + bp.protectionLevel
8996                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8997                                + ")");
8998                    }
8999                }
9000            }
9001        }
9002
9003        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9004                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9005            // This is the first that we have heard about this package, so the
9006            // permissions we have now selected are fixed until explicitly
9007            // changed.
9008            ps.installPermissionsFixed = true;
9009        }
9010
9011        // Persist the runtime permissions state for users with changes. If permissions
9012        // were revoked because no app in the shared user declares them we have to
9013        // write synchronously to avoid losing runtime permissions state.
9014        for (int userId : changedRuntimePermissionUserIds) {
9015            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9016        }
9017
9018        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9019    }
9020
9021    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9022        boolean allowed = false;
9023        final int NP = PackageParser.NEW_PERMISSIONS.length;
9024        for (int ip=0; ip<NP; ip++) {
9025            final PackageParser.NewPermissionInfo npi
9026                    = PackageParser.NEW_PERMISSIONS[ip];
9027            if (npi.name.equals(perm)
9028                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9029                allowed = true;
9030                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9031                        + pkg.packageName);
9032                break;
9033            }
9034        }
9035        return allowed;
9036    }
9037
9038    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9039            BasePermission bp, PermissionsState origPermissions) {
9040        boolean allowed;
9041        allowed = (compareSignatures(
9042                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9043                        == PackageManager.SIGNATURE_MATCH)
9044                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9045                        == PackageManager.SIGNATURE_MATCH);
9046        if (!allowed && (bp.protectionLevel
9047                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9048            if (isSystemApp(pkg)) {
9049                // For updated system applications, a system permission
9050                // is granted only if it had been defined by the original application.
9051                if (pkg.isUpdatedSystemApp()) {
9052                    final PackageSetting sysPs = mSettings
9053                            .getDisabledSystemPkgLPr(pkg.packageName);
9054                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9055                        // If the original was granted this permission, we take
9056                        // that grant decision as read and propagate it to the
9057                        // update.
9058                        if (sysPs.isPrivileged()) {
9059                            allowed = true;
9060                        }
9061                    } else {
9062                        // The system apk may have been updated with an older
9063                        // version of the one on the data partition, but which
9064                        // granted a new system permission that it didn't have
9065                        // before.  In this case we do want to allow the app to
9066                        // now get the new permission if the ancestral apk is
9067                        // privileged to get it.
9068                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9069                            for (int j=0;
9070                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9071                                if (perm.equals(
9072                                        sysPs.pkg.requestedPermissions.get(j))) {
9073                                    allowed = true;
9074                                    break;
9075                                }
9076                            }
9077                        }
9078                    }
9079                } else {
9080                    allowed = isPrivilegedApp(pkg);
9081                }
9082            }
9083        }
9084        if (!allowed) {
9085            if (!allowed && (bp.protectionLevel
9086                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9087                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9088                // If this was a previously normal/dangerous permission that got moved
9089                // to a system permission as part of the runtime permission redesign, then
9090                // we still want to blindly grant it to old apps.
9091                allowed = true;
9092            }
9093            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9094                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9095                // If this permission is to be granted to the system installer and
9096                // this app is an installer, then it gets the permission.
9097                allowed = true;
9098            }
9099            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9100                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9101                // If this permission is to be granted to the system verifier and
9102                // this app is a verifier, then it gets the permission.
9103                allowed = true;
9104            }
9105            if (!allowed && (bp.protectionLevel
9106                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9107                    && isSystemApp(pkg)) {
9108                // Any pre-installed system app is allowed to get this permission.
9109                allowed = true;
9110            }
9111            if (!allowed && (bp.protectionLevel
9112                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9113                // For development permissions, a development permission
9114                // is granted only if it was already granted.
9115                allowed = origPermissions.hasInstallPermission(perm);
9116            }
9117        }
9118        return allowed;
9119    }
9120
9121    final class ActivityIntentResolver
9122            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9123        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9124                boolean defaultOnly, int userId) {
9125            if (!sUserManager.exists(userId)) return null;
9126            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9127            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9128        }
9129
9130        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9131                int userId) {
9132            if (!sUserManager.exists(userId)) return null;
9133            mFlags = flags;
9134            return super.queryIntent(intent, resolvedType,
9135                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9136        }
9137
9138        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9139                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9140            if (!sUserManager.exists(userId)) return null;
9141            if (packageActivities == null) {
9142                return null;
9143            }
9144            mFlags = flags;
9145            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9146            final int N = packageActivities.size();
9147            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9148                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9149
9150            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9151            for (int i = 0; i < N; ++i) {
9152                intentFilters = packageActivities.get(i).intents;
9153                if (intentFilters != null && intentFilters.size() > 0) {
9154                    PackageParser.ActivityIntentInfo[] array =
9155                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9156                    intentFilters.toArray(array);
9157                    listCut.add(array);
9158                }
9159            }
9160            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9161        }
9162
9163        public final void addActivity(PackageParser.Activity a, String type) {
9164            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9165            mActivities.put(a.getComponentName(), a);
9166            if (DEBUG_SHOW_INFO)
9167                Log.v(
9168                TAG, "  " + type + " " +
9169                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9170            if (DEBUG_SHOW_INFO)
9171                Log.v(TAG, "    Class=" + a.info.name);
9172            final int NI = a.intents.size();
9173            for (int j=0; j<NI; j++) {
9174                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9175                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9176                    intent.setPriority(0);
9177                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9178                            + a.className + " with priority > 0, forcing to 0");
9179                }
9180                if (DEBUG_SHOW_INFO) {
9181                    Log.v(TAG, "    IntentFilter:");
9182                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9183                }
9184                if (!intent.debugCheck()) {
9185                    Log.w(TAG, "==> For Activity " + a.info.name);
9186                }
9187                addFilter(intent);
9188            }
9189        }
9190
9191        public final void removeActivity(PackageParser.Activity a, String type) {
9192            mActivities.remove(a.getComponentName());
9193            if (DEBUG_SHOW_INFO) {
9194                Log.v(TAG, "  " + type + " "
9195                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9196                                : a.info.name) + ":");
9197                Log.v(TAG, "    Class=" + a.info.name);
9198            }
9199            final int NI = a.intents.size();
9200            for (int j=0; j<NI; j++) {
9201                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9202                if (DEBUG_SHOW_INFO) {
9203                    Log.v(TAG, "    IntentFilter:");
9204                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9205                }
9206                removeFilter(intent);
9207            }
9208        }
9209
9210        @Override
9211        protected boolean allowFilterResult(
9212                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9213            ActivityInfo filterAi = filter.activity.info;
9214            for (int i=dest.size()-1; i>=0; i--) {
9215                ActivityInfo destAi = dest.get(i).activityInfo;
9216                if (destAi.name == filterAi.name
9217                        && destAi.packageName == filterAi.packageName) {
9218                    return false;
9219                }
9220            }
9221            return true;
9222        }
9223
9224        @Override
9225        protected ActivityIntentInfo[] newArray(int size) {
9226            return new ActivityIntentInfo[size];
9227        }
9228
9229        @Override
9230        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9231            if (!sUserManager.exists(userId)) return true;
9232            PackageParser.Package p = filter.activity.owner;
9233            if (p != null) {
9234                PackageSetting ps = (PackageSetting)p.mExtras;
9235                if (ps != null) {
9236                    // System apps are never considered stopped for purposes of
9237                    // filtering, because there may be no way for the user to
9238                    // actually re-launch them.
9239                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9240                            && ps.getStopped(userId);
9241                }
9242            }
9243            return false;
9244        }
9245
9246        @Override
9247        protected boolean isPackageForFilter(String packageName,
9248                PackageParser.ActivityIntentInfo info) {
9249            return packageName.equals(info.activity.owner.packageName);
9250        }
9251
9252        @Override
9253        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9254                int match, int userId) {
9255            if (!sUserManager.exists(userId)) return null;
9256            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9257                return null;
9258            }
9259            final PackageParser.Activity activity = info.activity;
9260            if (mSafeMode && (activity.info.applicationInfo.flags
9261                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9262                return null;
9263            }
9264            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9265            if (ps == null) {
9266                return null;
9267            }
9268            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9269                    ps.readUserState(userId), userId);
9270            if (ai == null) {
9271                return null;
9272            }
9273            final ResolveInfo res = new ResolveInfo();
9274            res.activityInfo = ai;
9275            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9276                res.filter = info;
9277            }
9278            if (info != null) {
9279                res.handleAllWebDataURI = info.handleAllWebDataURI();
9280            }
9281            res.priority = info.getPriority();
9282            res.preferredOrder = activity.owner.mPreferredOrder;
9283            //System.out.println("Result: " + res.activityInfo.className +
9284            //                   " = " + res.priority);
9285            res.match = match;
9286            res.isDefault = info.hasDefault;
9287            res.labelRes = info.labelRes;
9288            res.nonLocalizedLabel = info.nonLocalizedLabel;
9289            if (userNeedsBadging(userId)) {
9290                res.noResourceId = true;
9291            } else {
9292                res.icon = info.icon;
9293            }
9294            res.iconResourceId = info.icon;
9295            res.system = res.activityInfo.applicationInfo.isSystemApp();
9296            return res;
9297        }
9298
9299        @Override
9300        protected void sortResults(List<ResolveInfo> results) {
9301            Collections.sort(results, mResolvePrioritySorter);
9302        }
9303
9304        @Override
9305        protected void dumpFilter(PrintWriter out, String prefix,
9306                PackageParser.ActivityIntentInfo filter) {
9307            out.print(prefix); out.print(
9308                    Integer.toHexString(System.identityHashCode(filter.activity)));
9309                    out.print(' ');
9310                    filter.activity.printComponentShortName(out);
9311                    out.print(" filter ");
9312                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9313        }
9314
9315        @Override
9316        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9317            return filter.activity;
9318        }
9319
9320        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9321            PackageParser.Activity activity = (PackageParser.Activity)label;
9322            out.print(prefix); out.print(
9323                    Integer.toHexString(System.identityHashCode(activity)));
9324                    out.print(' ');
9325                    activity.printComponentShortName(out);
9326            if (count > 1) {
9327                out.print(" ("); out.print(count); out.print(" filters)");
9328            }
9329            out.println();
9330        }
9331
9332//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9333//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9334//            final List<ResolveInfo> retList = Lists.newArrayList();
9335//            while (i.hasNext()) {
9336//                final ResolveInfo resolveInfo = i.next();
9337//                if (isEnabledLP(resolveInfo.activityInfo)) {
9338//                    retList.add(resolveInfo);
9339//                }
9340//            }
9341//            return retList;
9342//        }
9343
9344        // Keys are String (activity class name), values are Activity.
9345        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9346                = new ArrayMap<ComponentName, PackageParser.Activity>();
9347        private int mFlags;
9348    }
9349
9350    private final class ServiceIntentResolver
9351            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9352        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9353                boolean defaultOnly, int userId) {
9354            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9355            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9356        }
9357
9358        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9359                int userId) {
9360            if (!sUserManager.exists(userId)) return null;
9361            mFlags = flags;
9362            return super.queryIntent(intent, resolvedType,
9363                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9364        }
9365
9366        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9367                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9368            if (!sUserManager.exists(userId)) return null;
9369            if (packageServices == null) {
9370                return null;
9371            }
9372            mFlags = flags;
9373            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9374            final int N = packageServices.size();
9375            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9376                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9377
9378            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9379            for (int i = 0; i < N; ++i) {
9380                intentFilters = packageServices.get(i).intents;
9381                if (intentFilters != null && intentFilters.size() > 0) {
9382                    PackageParser.ServiceIntentInfo[] array =
9383                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9384                    intentFilters.toArray(array);
9385                    listCut.add(array);
9386                }
9387            }
9388            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9389        }
9390
9391        public final void addService(PackageParser.Service s) {
9392            mServices.put(s.getComponentName(), s);
9393            if (DEBUG_SHOW_INFO) {
9394                Log.v(TAG, "  "
9395                        + (s.info.nonLocalizedLabel != null
9396                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9397                Log.v(TAG, "    Class=" + s.info.name);
9398            }
9399            final int NI = s.intents.size();
9400            int j;
9401            for (j=0; j<NI; j++) {
9402                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9403                if (DEBUG_SHOW_INFO) {
9404                    Log.v(TAG, "    IntentFilter:");
9405                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9406                }
9407                if (!intent.debugCheck()) {
9408                    Log.w(TAG, "==> For Service " + s.info.name);
9409                }
9410                addFilter(intent);
9411            }
9412        }
9413
9414        public final void removeService(PackageParser.Service s) {
9415            mServices.remove(s.getComponentName());
9416            if (DEBUG_SHOW_INFO) {
9417                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9418                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9419                Log.v(TAG, "    Class=" + s.info.name);
9420            }
9421            final int NI = s.intents.size();
9422            int j;
9423            for (j=0; j<NI; j++) {
9424                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9425                if (DEBUG_SHOW_INFO) {
9426                    Log.v(TAG, "    IntentFilter:");
9427                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9428                }
9429                removeFilter(intent);
9430            }
9431        }
9432
9433        @Override
9434        protected boolean allowFilterResult(
9435                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9436            ServiceInfo filterSi = filter.service.info;
9437            for (int i=dest.size()-1; i>=0; i--) {
9438                ServiceInfo destAi = dest.get(i).serviceInfo;
9439                if (destAi.name == filterSi.name
9440                        && destAi.packageName == filterSi.packageName) {
9441                    return false;
9442                }
9443            }
9444            return true;
9445        }
9446
9447        @Override
9448        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9449            return new PackageParser.ServiceIntentInfo[size];
9450        }
9451
9452        @Override
9453        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9454            if (!sUserManager.exists(userId)) return true;
9455            PackageParser.Package p = filter.service.owner;
9456            if (p != null) {
9457                PackageSetting ps = (PackageSetting)p.mExtras;
9458                if (ps != null) {
9459                    // System apps are never considered stopped for purposes of
9460                    // filtering, because there may be no way for the user to
9461                    // actually re-launch them.
9462                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9463                            && ps.getStopped(userId);
9464                }
9465            }
9466            return false;
9467        }
9468
9469        @Override
9470        protected boolean isPackageForFilter(String packageName,
9471                PackageParser.ServiceIntentInfo info) {
9472            return packageName.equals(info.service.owner.packageName);
9473        }
9474
9475        @Override
9476        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9477                int match, int userId) {
9478            if (!sUserManager.exists(userId)) return null;
9479            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9480            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9481                return null;
9482            }
9483            final PackageParser.Service service = info.service;
9484            if (mSafeMode && (service.info.applicationInfo.flags
9485                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9486                return null;
9487            }
9488            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9489            if (ps == null) {
9490                return null;
9491            }
9492            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9493                    ps.readUserState(userId), userId);
9494            if (si == null) {
9495                return null;
9496            }
9497            final ResolveInfo res = new ResolveInfo();
9498            res.serviceInfo = si;
9499            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9500                res.filter = filter;
9501            }
9502            res.priority = info.getPriority();
9503            res.preferredOrder = service.owner.mPreferredOrder;
9504            res.match = match;
9505            res.isDefault = info.hasDefault;
9506            res.labelRes = info.labelRes;
9507            res.nonLocalizedLabel = info.nonLocalizedLabel;
9508            res.icon = info.icon;
9509            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9510            return res;
9511        }
9512
9513        @Override
9514        protected void sortResults(List<ResolveInfo> results) {
9515            Collections.sort(results, mResolvePrioritySorter);
9516        }
9517
9518        @Override
9519        protected void dumpFilter(PrintWriter out, String prefix,
9520                PackageParser.ServiceIntentInfo filter) {
9521            out.print(prefix); out.print(
9522                    Integer.toHexString(System.identityHashCode(filter.service)));
9523                    out.print(' ');
9524                    filter.service.printComponentShortName(out);
9525                    out.print(" filter ");
9526                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9527        }
9528
9529        @Override
9530        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9531            return filter.service;
9532        }
9533
9534        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9535            PackageParser.Service service = (PackageParser.Service)label;
9536            out.print(prefix); out.print(
9537                    Integer.toHexString(System.identityHashCode(service)));
9538                    out.print(' ');
9539                    service.printComponentShortName(out);
9540            if (count > 1) {
9541                out.print(" ("); out.print(count); out.print(" filters)");
9542            }
9543            out.println();
9544        }
9545
9546//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9547//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9548//            final List<ResolveInfo> retList = Lists.newArrayList();
9549//            while (i.hasNext()) {
9550//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9551//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9552//                    retList.add(resolveInfo);
9553//                }
9554//            }
9555//            return retList;
9556//        }
9557
9558        // Keys are String (activity class name), values are Activity.
9559        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9560                = new ArrayMap<ComponentName, PackageParser.Service>();
9561        private int mFlags;
9562    };
9563
9564    private final class ProviderIntentResolver
9565            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9566        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9567                boolean defaultOnly, int userId) {
9568            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9569            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9570        }
9571
9572        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9573                int userId) {
9574            if (!sUserManager.exists(userId))
9575                return null;
9576            mFlags = flags;
9577            return super.queryIntent(intent, resolvedType,
9578                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9579        }
9580
9581        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9582                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9583            if (!sUserManager.exists(userId))
9584                return null;
9585            if (packageProviders == null) {
9586                return null;
9587            }
9588            mFlags = flags;
9589            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9590            final int N = packageProviders.size();
9591            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9592                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9593
9594            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9595            for (int i = 0; i < N; ++i) {
9596                intentFilters = packageProviders.get(i).intents;
9597                if (intentFilters != null && intentFilters.size() > 0) {
9598                    PackageParser.ProviderIntentInfo[] array =
9599                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9600                    intentFilters.toArray(array);
9601                    listCut.add(array);
9602                }
9603            }
9604            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9605        }
9606
9607        public final void addProvider(PackageParser.Provider p) {
9608            if (mProviders.containsKey(p.getComponentName())) {
9609                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9610                return;
9611            }
9612
9613            mProviders.put(p.getComponentName(), p);
9614            if (DEBUG_SHOW_INFO) {
9615                Log.v(TAG, "  "
9616                        + (p.info.nonLocalizedLabel != null
9617                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9618                Log.v(TAG, "    Class=" + p.info.name);
9619            }
9620            final int NI = p.intents.size();
9621            int j;
9622            for (j = 0; j < NI; j++) {
9623                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9624                if (DEBUG_SHOW_INFO) {
9625                    Log.v(TAG, "    IntentFilter:");
9626                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9627                }
9628                if (!intent.debugCheck()) {
9629                    Log.w(TAG, "==> For Provider " + p.info.name);
9630                }
9631                addFilter(intent);
9632            }
9633        }
9634
9635        public final void removeProvider(PackageParser.Provider p) {
9636            mProviders.remove(p.getComponentName());
9637            if (DEBUG_SHOW_INFO) {
9638                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9639                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9640                Log.v(TAG, "    Class=" + p.info.name);
9641            }
9642            final int NI = p.intents.size();
9643            int j;
9644            for (j = 0; j < NI; j++) {
9645                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9646                if (DEBUG_SHOW_INFO) {
9647                    Log.v(TAG, "    IntentFilter:");
9648                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9649                }
9650                removeFilter(intent);
9651            }
9652        }
9653
9654        @Override
9655        protected boolean allowFilterResult(
9656                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9657            ProviderInfo filterPi = filter.provider.info;
9658            for (int i = dest.size() - 1; i >= 0; i--) {
9659                ProviderInfo destPi = dest.get(i).providerInfo;
9660                if (destPi.name == filterPi.name
9661                        && destPi.packageName == filterPi.packageName) {
9662                    return false;
9663                }
9664            }
9665            return true;
9666        }
9667
9668        @Override
9669        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9670            return new PackageParser.ProviderIntentInfo[size];
9671        }
9672
9673        @Override
9674        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9675            if (!sUserManager.exists(userId))
9676                return true;
9677            PackageParser.Package p = filter.provider.owner;
9678            if (p != null) {
9679                PackageSetting ps = (PackageSetting) p.mExtras;
9680                if (ps != null) {
9681                    // System apps are never considered stopped for purposes of
9682                    // filtering, because there may be no way for the user to
9683                    // actually re-launch them.
9684                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9685                            && ps.getStopped(userId);
9686                }
9687            }
9688            return false;
9689        }
9690
9691        @Override
9692        protected boolean isPackageForFilter(String packageName,
9693                PackageParser.ProviderIntentInfo info) {
9694            return packageName.equals(info.provider.owner.packageName);
9695        }
9696
9697        @Override
9698        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9699                int match, int userId) {
9700            if (!sUserManager.exists(userId))
9701                return null;
9702            final PackageParser.ProviderIntentInfo info = filter;
9703            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9704                return null;
9705            }
9706            final PackageParser.Provider provider = info.provider;
9707            if (mSafeMode && (provider.info.applicationInfo.flags
9708                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9709                return null;
9710            }
9711            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9712            if (ps == null) {
9713                return null;
9714            }
9715            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9716                    ps.readUserState(userId), userId);
9717            if (pi == null) {
9718                return null;
9719            }
9720            final ResolveInfo res = new ResolveInfo();
9721            res.providerInfo = pi;
9722            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9723                res.filter = filter;
9724            }
9725            res.priority = info.getPriority();
9726            res.preferredOrder = provider.owner.mPreferredOrder;
9727            res.match = match;
9728            res.isDefault = info.hasDefault;
9729            res.labelRes = info.labelRes;
9730            res.nonLocalizedLabel = info.nonLocalizedLabel;
9731            res.icon = info.icon;
9732            res.system = res.providerInfo.applicationInfo.isSystemApp();
9733            return res;
9734        }
9735
9736        @Override
9737        protected void sortResults(List<ResolveInfo> results) {
9738            Collections.sort(results, mResolvePrioritySorter);
9739        }
9740
9741        @Override
9742        protected void dumpFilter(PrintWriter out, String prefix,
9743                PackageParser.ProviderIntentInfo filter) {
9744            out.print(prefix);
9745            out.print(
9746                    Integer.toHexString(System.identityHashCode(filter.provider)));
9747            out.print(' ');
9748            filter.provider.printComponentShortName(out);
9749            out.print(" filter ");
9750            out.println(Integer.toHexString(System.identityHashCode(filter)));
9751        }
9752
9753        @Override
9754        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9755            return filter.provider;
9756        }
9757
9758        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9759            PackageParser.Provider provider = (PackageParser.Provider)label;
9760            out.print(prefix); out.print(
9761                    Integer.toHexString(System.identityHashCode(provider)));
9762                    out.print(' ');
9763                    provider.printComponentShortName(out);
9764            if (count > 1) {
9765                out.print(" ("); out.print(count); out.print(" filters)");
9766            }
9767            out.println();
9768        }
9769
9770        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9771                = new ArrayMap<ComponentName, PackageParser.Provider>();
9772        private int mFlags;
9773    }
9774
9775    private static final class EphemeralIntentResolver
9776            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9777        @Override
9778        protected EphemeralResolveIntentInfo[] newArray(int size) {
9779            return new EphemeralResolveIntentInfo[size];
9780        }
9781
9782        @Override
9783        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9784            return true;
9785        }
9786
9787        @Override
9788        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9789                int userId) {
9790            if (!sUserManager.exists(userId)) {
9791                return null;
9792            }
9793            return info.getEphemeralResolveInfo();
9794        }
9795    }
9796
9797    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9798            new Comparator<ResolveInfo>() {
9799        public int compare(ResolveInfo r1, ResolveInfo r2) {
9800            int v1 = r1.priority;
9801            int v2 = r2.priority;
9802            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9803            if (v1 != v2) {
9804                return (v1 > v2) ? -1 : 1;
9805            }
9806            v1 = r1.preferredOrder;
9807            v2 = r2.preferredOrder;
9808            if (v1 != v2) {
9809                return (v1 > v2) ? -1 : 1;
9810            }
9811            if (r1.isDefault != r2.isDefault) {
9812                return r1.isDefault ? -1 : 1;
9813            }
9814            v1 = r1.match;
9815            v2 = r2.match;
9816            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9817            if (v1 != v2) {
9818                return (v1 > v2) ? -1 : 1;
9819            }
9820            if (r1.system != r2.system) {
9821                return r1.system ? -1 : 1;
9822            }
9823            if (r1.activityInfo != null) {
9824                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9825            }
9826            if (r1.serviceInfo != null) {
9827                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9828            }
9829            if (r1.providerInfo != null) {
9830                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9831            }
9832            return 0;
9833        }
9834    };
9835
9836    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9837            new Comparator<ProviderInfo>() {
9838        public int compare(ProviderInfo p1, ProviderInfo p2) {
9839            final int v1 = p1.initOrder;
9840            final int v2 = p2.initOrder;
9841            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9842        }
9843    };
9844
9845    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9846            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9847            final int[] userIds) {
9848        mHandler.post(new Runnable() {
9849            @Override
9850            public void run() {
9851                try {
9852                    final IActivityManager am = ActivityManagerNative.getDefault();
9853                    if (am == null) return;
9854                    final int[] resolvedUserIds;
9855                    if (userIds == null) {
9856                        resolvedUserIds = am.getRunningUserIds();
9857                    } else {
9858                        resolvedUserIds = userIds;
9859                    }
9860                    for (int id : resolvedUserIds) {
9861                        final Intent intent = new Intent(action,
9862                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9863                        if (extras != null) {
9864                            intent.putExtras(extras);
9865                        }
9866                        if (targetPkg != null) {
9867                            intent.setPackage(targetPkg);
9868                        }
9869                        // Modify the UID when posting to other users
9870                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9871                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9872                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9873                            intent.putExtra(Intent.EXTRA_UID, uid);
9874                        }
9875                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9876                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9877                        if (DEBUG_BROADCASTS) {
9878                            RuntimeException here = new RuntimeException("here");
9879                            here.fillInStackTrace();
9880                            Slog.d(TAG, "Sending to user " + id + ": "
9881                                    + intent.toShortString(false, true, false, false)
9882                                    + " " + intent.getExtras(), here);
9883                        }
9884                        am.broadcastIntent(null, intent, null, finishedReceiver,
9885                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9886                                null, finishedReceiver != null, false, id);
9887                    }
9888                } catch (RemoteException ex) {
9889                }
9890            }
9891        });
9892    }
9893
9894    /**
9895     * Check if the external storage media is available. This is true if there
9896     * is a mounted external storage medium or if the external storage is
9897     * emulated.
9898     */
9899    private boolean isExternalMediaAvailable() {
9900        return mMediaMounted || Environment.isExternalStorageEmulated();
9901    }
9902
9903    @Override
9904    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9905        // writer
9906        synchronized (mPackages) {
9907            if (!isExternalMediaAvailable()) {
9908                // If the external storage is no longer mounted at this point,
9909                // the caller may not have been able to delete all of this
9910                // packages files and can not delete any more.  Bail.
9911                return null;
9912            }
9913            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9914            if (lastPackage != null) {
9915                pkgs.remove(lastPackage);
9916            }
9917            if (pkgs.size() > 0) {
9918                return pkgs.get(0);
9919            }
9920        }
9921        return null;
9922    }
9923
9924    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9925        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9926                userId, andCode ? 1 : 0, packageName);
9927        if (mSystemReady) {
9928            msg.sendToTarget();
9929        } else {
9930            if (mPostSystemReadyMessages == null) {
9931                mPostSystemReadyMessages = new ArrayList<>();
9932            }
9933            mPostSystemReadyMessages.add(msg);
9934        }
9935    }
9936
9937    void startCleaningPackages() {
9938        // reader
9939        synchronized (mPackages) {
9940            if (!isExternalMediaAvailable()) {
9941                return;
9942            }
9943            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9944                return;
9945            }
9946        }
9947        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9948        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9949        IActivityManager am = ActivityManagerNative.getDefault();
9950        if (am != null) {
9951            try {
9952                am.startService(null, intent, null, mContext.getOpPackageName(),
9953                        UserHandle.USER_SYSTEM);
9954            } catch (RemoteException e) {
9955            }
9956        }
9957    }
9958
9959    @Override
9960    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9961            int installFlags, String installerPackageName, VerificationParams verificationParams,
9962            String packageAbiOverride) {
9963        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9964                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9965    }
9966
9967    @Override
9968    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9969            int installFlags, String installerPackageName, VerificationParams verificationParams,
9970            String packageAbiOverride, int userId) {
9971        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9972
9973        final int callingUid = Binder.getCallingUid();
9974        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9975
9976        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9977            try {
9978                if (observer != null) {
9979                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9980                }
9981            } catch (RemoteException re) {
9982            }
9983            return;
9984        }
9985
9986        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9987            installFlags |= PackageManager.INSTALL_FROM_ADB;
9988
9989        } else {
9990            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9991            // about installerPackageName.
9992
9993            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9994            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9995        }
9996
9997        UserHandle user;
9998        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9999            user = UserHandle.ALL;
10000        } else {
10001            user = new UserHandle(userId);
10002        }
10003
10004        // Only system components can circumvent runtime permissions when installing.
10005        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10006                && mContext.checkCallingOrSelfPermission(Manifest.permission
10007                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10008            throw new SecurityException("You need the "
10009                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10010                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10011        }
10012
10013        verificationParams.setInstallerUid(callingUid);
10014
10015        final File originFile = new File(originPath);
10016        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10017
10018        final Message msg = mHandler.obtainMessage(INIT_COPY);
10019        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10020                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10021        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10022        msg.obj = params;
10023
10024        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10025                System.identityHashCode(msg.obj));
10026        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10027                System.identityHashCode(msg.obj));
10028
10029        mHandler.sendMessage(msg);
10030    }
10031
10032    void installStage(String packageName, File stagedDir, String stagedCid,
10033            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10034            String installerPackageName, int installerUid, UserHandle user) {
10035        if (DEBUG_EPHEMERAL) {
10036            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10037                Slog.d(TAG, "Ephemeral install of " + packageName);
10038            }
10039        }
10040        final VerificationParams verifParams = new VerificationParams(
10041                null, sessionParams.originatingUri, sessionParams.referrerUri,
10042                sessionParams.originatingUid, null);
10043        verifParams.setInstallerUid(installerUid);
10044
10045        final OriginInfo origin;
10046        if (stagedDir != null) {
10047            origin = OriginInfo.fromStagedFile(stagedDir);
10048        } else {
10049            origin = OriginInfo.fromStagedContainer(stagedCid);
10050        }
10051
10052        final Message msg = mHandler.obtainMessage(INIT_COPY);
10053        final InstallParams params = new InstallParams(origin, null, observer,
10054                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10055                verifParams, user, sessionParams.abiOverride,
10056                sessionParams.grantedRuntimePermissions);
10057        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10058        msg.obj = params;
10059
10060        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10061                System.identityHashCode(msg.obj));
10062        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10063                System.identityHashCode(msg.obj));
10064
10065        mHandler.sendMessage(msg);
10066    }
10067
10068    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10069        Bundle extras = new Bundle(1);
10070        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10071
10072        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10073                packageName, extras, 0, null, null, new int[] {userId});
10074        try {
10075            IActivityManager am = ActivityManagerNative.getDefault();
10076            final boolean isSystem =
10077                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10078            if (isSystem && am.isUserRunning(userId, 0)) {
10079                // The just-installed/enabled app is bundled on the system, so presumed
10080                // to be able to run automatically without needing an explicit launch.
10081                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10082                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10083                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10084                        .setPackage(packageName);
10085                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10086                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10087            }
10088        } catch (RemoteException e) {
10089            // shouldn't happen
10090            Slog.w(TAG, "Unable to bootstrap installed package", e);
10091        }
10092    }
10093
10094    @Override
10095    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10096            int userId) {
10097        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10098        PackageSetting pkgSetting;
10099        final int uid = Binder.getCallingUid();
10100        enforceCrossUserPermission(uid, userId, true, true,
10101                "setApplicationHiddenSetting for user " + userId);
10102
10103        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10104            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10105            return false;
10106        }
10107
10108        long callingId = Binder.clearCallingIdentity();
10109        try {
10110            boolean sendAdded = false;
10111            boolean sendRemoved = false;
10112            // writer
10113            synchronized (mPackages) {
10114                pkgSetting = mSettings.mPackages.get(packageName);
10115                if (pkgSetting == null) {
10116                    return false;
10117                }
10118                if (pkgSetting.getHidden(userId) != hidden) {
10119                    pkgSetting.setHidden(hidden, userId);
10120                    mSettings.writePackageRestrictionsLPr(userId);
10121                    if (hidden) {
10122                        sendRemoved = true;
10123                    } else {
10124                        sendAdded = true;
10125                    }
10126                }
10127            }
10128            if (sendAdded) {
10129                sendPackageAddedForUser(packageName, pkgSetting, userId);
10130                return true;
10131            }
10132            if (sendRemoved) {
10133                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10134                        "hiding pkg");
10135                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10136                return true;
10137            }
10138        } finally {
10139            Binder.restoreCallingIdentity(callingId);
10140        }
10141        return false;
10142    }
10143
10144    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10145            int userId) {
10146        final PackageRemovedInfo info = new PackageRemovedInfo();
10147        info.removedPackage = packageName;
10148        info.removedUsers = new int[] {userId};
10149        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10150        info.sendBroadcast(false, false, false);
10151    }
10152
10153    /**
10154     * Returns true if application is not found or there was an error. Otherwise it returns
10155     * the hidden state of the package for the given user.
10156     */
10157    @Override
10158    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10159        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10160        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10161                false, "getApplicationHidden for user " + userId);
10162        PackageSetting pkgSetting;
10163        long callingId = Binder.clearCallingIdentity();
10164        try {
10165            // writer
10166            synchronized (mPackages) {
10167                pkgSetting = mSettings.mPackages.get(packageName);
10168                if (pkgSetting == null) {
10169                    return true;
10170                }
10171                return pkgSetting.getHidden(userId);
10172            }
10173        } finally {
10174            Binder.restoreCallingIdentity(callingId);
10175        }
10176    }
10177
10178    /**
10179     * @hide
10180     */
10181    @Override
10182    public int installExistingPackageAsUser(String packageName, int userId) {
10183        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10184                null);
10185        PackageSetting pkgSetting;
10186        final int uid = Binder.getCallingUid();
10187        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10188                + userId);
10189        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10190            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10191        }
10192
10193        long callingId = Binder.clearCallingIdentity();
10194        try {
10195            boolean sendAdded = false;
10196
10197            // writer
10198            synchronized (mPackages) {
10199                pkgSetting = mSettings.mPackages.get(packageName);
10200                if (pkgSetting == null) {
10201                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10202                }
10203                if (!pkgSetting.getInstalled(userId)) {
10204                    pkgSetting.setInstalled(true, userId);
10205                    pkgSetting.setHidden(false, userId);
10206                    mSettings.writePackageRestrictionsLPr(userId);
10207                    sendAdded = true;
10208                }
10209            }
10210
10211            if (sendAdded) {
10212                sendPackageAddedForUser(packageName, pkgSetting, userId);
10213            }
10214        } finally {
10215            Binder.restoreCallingIdentity(callingId);
10216        }
10217
10218        return PackageManager.INSTALL_SUCCEEDED;
10219    }
10220
10221    boolean isUserRestricted(int userId, String restrictionKey) {
10222        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10223        if (restrictions.getBoolean(restrictionKey, false)) {
10224            Log.w(TAG, "User is restricted: " + restrictionKey);
10225            return true;
10226        }
10227        return false;
10228    }
10229
10230    @Override
10231    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10232        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10233        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10234                "setPackageSuspended for user " + userId);
10235
10236        long callingId = Binder.clearCallingIdentity();
10237        try {
10238            synchronized (mPackages) {
10239                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10240                if (pkgSetting != null) {
10241                    if (pkgSetting.getSuspended(userId) != suspended) {
10242                        pkgSetting.setSuspended(suspended, userId);
10243                        mSettings.writePackageRestrictionsLPr(userId);
10244                    }
10245
10246                    // TODO:
10247                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10248                    // * remove app from recents (kill app it if it is running)
10249                    // * erase existing notifications for this app
10250                    return true;
10251                }
10252
10253                return false;
10254            }
10255        } finally {
10256            Binder.restoreCallingIdentity(callingId);
10257        }
10258    }
10259
10260    @Override
10261    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10262        mContext.enforceCallingOrSelfPermission(
10263                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10264                "Only package verification agents can verify applications");
10265
10266        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10267        final PackageVerificationResponse response = new PackageVerificationResponse(
10268                verificationCode, Binder.getCallingUid());
10269        msg.arg1 = id;
10270        msg.obj = response;
10271        mHandler.sendMessage(msg);
10272    }
10273
10274    @Override
10275    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10276            long millisecondsToDelay) {
10277        mContext.enforceCallingOrSelfPermission(
10278                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10279                "Only package verification agents can extend verification timeouts");
10280
10281        final PackageVerificationState state = mPendingVerification.get(id);
10282        final PackageVerificationResponse response = new PackageVerificationResponse(
10283                verificationCodeAtTimeout, Binder.getCallingUid());
10284
10285        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10286            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10287        }
10288        if (millisecondsToDelay < 0) {
10289            millisecondsToDelay = 0;
10290        }
10291        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10292                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10293            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10294        }
10295
10296        if ((state != null) && !state.timeoutExtended()) {
10297            state.extendTimeout();
10298
10299            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10300            msg.arg1 = id;
10301            msg.obj = response;
10302            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10303        }
10304    }
10305
10306    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10307            int verificationCode, UserHandle user) {
10308        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10309        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10310        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10311        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10312        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10313
10314        mContext.sendBroadcastAsUser(intent, user,
10315                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10316    }
10317
10318    private ComponentName matchComponentForVerifier(String packageName,
10319            List<ResolveInfo> receivers) {
10320        ActivityInfo targetReceiver = null;
10321
10322        final int NR = receivers.size();
10323        for (int i = 0; i < NR; i++) {
10324            final ResolveInfo info = receivers.get(i);
10325            if (info.activityInfo == null) {
10326                continue;
10327            }
10328
10329            if (packageName.equals(info.activityInfo.packageName)) {
10330                targetReceiver = info.activityInfo;
10331                break;
10332            }
10333        }
10334
10335        if (targetReceiver == null) {
10336            return null;
10337        }
10338
10339        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10340    }
10341
10342    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10343            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10344        if (pkgInfo.verifiers.length == 0) {
10345            return null;
10346        }
10347
10348        final int N = pkgInfo.verifiers.length;
10349        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10350        for (int i = 0; i < N; i++) {
10351            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10352
10353            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10354                    receivers);
10355            if (comp == null) {
10356                continue;
10357            }
10358
10359            final int verifierUid = getUidForVerifier(verifierInfo);
10360            if (verifierUid == -1) {
10361                continue;
10362            }
10363
10364            if (DEBUG_VERIFY) {
10365                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10366                        + " with the correct signature");
10367            }
10368            sufficientVerifiers.add(comp);
10369            verificationState.addSufficientVerifier(verifierUid);
10370        }
10371
10372        return sufficientVerifiers;
10373    }
10374
10375    private int getUidForVerifier(VerifierInfo verifierInfo) {
10376        synchronized (mPackages) {
10377            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10378            if (pkg == null) {
10379                return -1;
10380            } else if (pkg.mSignatures.length != 1) {
10381                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10382                        + " has more than one signature; ignoring");
10383                return -1;
10384            }
10385
10386            /*
10387             * If the public key of the package's signature does not match
10388             * our expected public key, then this is a different package and
10389             * we should skip.
10390             */
10391
10392            final byte[] expectedPublicKey;
10393            try {
10394                final Signature verifierSig = pkg.mSignatures[0];
10395                final PublicKey publicKey = verifierSig.getPublicKey();
10396                expectedPublicKey = publicKey.getEncoded();
10397            } catch (CertificateException e) {
10398                return -1;
10399            }
10400
10401            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10402
10403            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10404                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10405                        + " does not have the expected public key; ignoring");
10406                return -1;
10407            }
10408
10409            return pkg.applicationInfo.uid;
10410        }
10411    }
10412
10413    @Override
10414    public void finishPackageInstall(int token) {
10415        enforceSystemOrRoot("Only the system is allowed to finish installs");
10416
10417        if (DEBUG_INSTALL) {
10418            Slog.v(TAG, "BM finishing package install for " + token);
10419        }
10420        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10421
10422        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10423        mHandler.sendMessage(msg);
10424    }
10425
10426    /**
10427     * Get the verification agent timeout.
10428     *
10429     * @return verification timeout in milliseconds
10430     */
10431    private long getVerificationTimeout() {
10432        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10433                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10434                DEFAULT_VERIFICATION_TIMEOUT);
10435    }
10436
10437    /**
10438     * Get the default verification agent response code.
10439     *
10440     * @return default verification response code
10441     */
10442    private int getDefaultVerificationResponse() {
10443        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10444                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10445                DEFAULT_VERIFICATION_RESPONSE);
10446    }
10447
10448    /**
10449     * Check whether or not package verification has been enabled.
10450     *
10451     * @return true if verification should be performed
10452     */
10453    private boolean isVerificationEnabled(int userId, int installFlags) {
10454        if (!DEFAULT_VERIFY_ENABLE) {
10455            return false;
10456        }
10457        // Ephemeral apps don't get the full verification treatment
10458        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10459            if (DEBUG_EPHEMERAL) {
10460                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10461            }
10462            return false;
10463        }
10464
10465        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10466
10467        // Check if installing from ADB
10468        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10469            // Do not run verification in a test harness environment
10470            if (ActivityManager.isRunningInTestHarness()) {
10471                return false;
10472            }
10473            if (ensureVerifyAppsEnabled) {
10474                return true;
10475            }
10476            // Check if the developer does not want package verification for ADB installs
10477            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10478                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10479                return false;
10480            }
10481        }
10482
10483        if (ensureVerifyAppsEnabled) {
10484            return true;
10485        }
10486
10487        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10488                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10489    }
10490
10491    @Override
10492    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10493            throws RemoteException {
10494        mContext.enforceCallingOrSelfPermission(
10495                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10496                "Only intentfilter verification agents can verify applications");
10497
10498        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10499        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10500                Binder.getCallingUid(), verificationCode, failedDomains);
10501        msg.arg1 = id;
10502        msg.obj = response;
10503        mHandler.sendMessage(msg);
10504    }
10505
10506    @Override
10507    public int getIntentVerificationStatus(String packageName, int userId) {
10508        synchronized (mPackages) {
10509            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10510        }
10511    }
10512
10513    @Override
10514    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10515        mContext.enforceCallingOrSelfPermission(
10516                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10517
10518        boolean result = false;
10519        synchronized (mPackages) {
10520            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10521        }
10522        if (result) {
10523            scheduleWritePackageRestrictionsLocked(userId);
10524        }
10525        return result;
10526    }
10527
10528    @Override
10529    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10530        synchronized (mPackages) {
10531            return mSettings.getIntentFilterVerificationsLPr(packageName);
10532        }
10533    }
10534
10535    @Override
10536    public List<IntentFilter> getAllIntentFilters(String packageName) {
10537        if (TextUtils.isEmpty(packageName)) {
10538            return Collections.<IntentFilter>emptyList();
10539        }
10540        synchronized (mPackages) {
10541            PackageParser.Package pkg = mPackages.get(packageName);
10542            if (pkg == null || pkg.activities == null) {
10543                return Collections.<IntentFilter>emptyList();
10544            }
10545            final int count = pkg.activities.size();
10546            ArrayList<IntentFilter> result = new ArrayList<>();
10547            for (int n=0; n<count; n++) {
10548                PackageParser.Activity activity = pkg.activities.get(n);
10549                if (activity.intents != null && activity.intents.size() > 0) {
10550                    result.addAll(activity.intents);
10551                }
10552            }
10553            return result;
10554        }
10555    }
10556
10557    @Override
10558    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10559        mContext.enforceCallingOrSelfPermission(
10560                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10561
10562        synchronized (mPackages) {
10563            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10564            if (packageName != null) {
10565                result |= updateIntentVerificationStatus(packageName,
10566                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10567                        userId);
10568                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10569                        packageName, userId);
10570            }
10571            return result;
10572        }
10573    }
10574
10575    @Override
10576    public String getDefaultBrowserPackageName(int userId) {
10577        synchronized (mPackages) {
10578            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10579        }
10580    }
10581
10582    /**
10583     * Get the "allow unknown sources" setting.
10584     *
10585     * @return the current "allow unknown sources" setting
10586     */
10587    private int getUnknownSourcesSettings() {
10588        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10589                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10590                -1);
10591    }
10592
10593    @Override
10594    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10595        final int uid = Binder.getCallingUid();
10596        // writer
10597        synchronized (mPackages) {
10598            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10599            if (targetPackageSetting == null) {
10600                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10601            }
10602
10603            PackageSetting installerPackageSetting;
10604            if (installerPackageName != null) {
10605                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10606                if (installerPackageSetting == null) {
10607                    throw new IllegalArgumentException("Unknown installer package: "
10608                            + installerPackageName);
10609                }
10610            } else {
10611                installerPackageSetting = null;
10612            }
10613
10614            Signature[] callerSignature;
10615            Object obj = mSettings.getUserIdLPr(uid);
10616            if (obj != null) {
10617                if (obj instanceof SharedUserSetting) {
10618                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10619                } else if (obj instanceof PackageSetting) {
10620                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10621                } else {
10622                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10623                }
10624            } else {
10625                throw new SecurityException("Unknown calling uid " + uid);
10626            }
10627
10628            // Verify: can't set installerPackageName to a package that is
10629            // not signed with the same cert as the caller.
10630            if (installerPackageSetting != null) {
10631                if (compareSignatures(callerSignature,
10632                        installerPackageSetting.signatures.mSignatures)
10633                        != PackageManager.SIGNATURE_MATCH) {
10634                    throw new SecurityException(
10635                            "Caller does not have same cert as new installer package "
10636                            + installerPackageName);
10637                }
10638            }
10639
10640            // Verify: if target already has an installer package, it must
10641            // be signed with the same cert as the caller.
10642            if (targetPackageSetting.installerPackageName != null) {
10643                PackageSetting setting = mSettings.mPackages.get(
10644                        targetPackageSetting.installerPackageName);
10645                // If the currently set package isn't valid, then it's always
10646                // okay to change it.
10647                if (setting != null) {
10648                    if (compareSignatures(callerSignature,
10649                            setting.signatures.mSignatures)
10650                            != PackageManager.SIGNATURE_MATCH) {
10651                        throw new SecurityException(
10652                                "Caller does not have same cert as old installer package "
10653                                + targetPackageSetting.installerPackageName);
10654                    }
10655                }
10656            }
10657
10658            // Okay!
10659            targetPackageSetting.installerPackageName = installerPackageName;
10660            scheduleWriteSettingsLocked();
10661        }
10662    }
10663
10664    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10665        // Queue up an async operation since the package installation may take a little while.
10666        mHandler.post(new Runnable() {
10667            public void run() {
10668                mHandler.removeCallbacks(this);
10669                 // Result object to be returned
10670                PackageInstalledInfo res = new PackageInstalledInfo();
10671                res.returnCode = currentStatus;
10672                res.uid = -1;
10673                res.pkg = null;
10674                res.removedInfo = new PackageRemovedInfo();
10675                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10676                    args.doPreInstall(res.returnCode);
10677                    synchronized (mInstallLock) {
10678                        installPackageTracedLI(args, res);
10679                    }
10680                    args.doPostInstall(res.returnCode, res.uid);
10681                }
10682
10683                // A restore should be performed at this point if (a) the install
10684                // succeeded, (b) the operation is not an update, and (c) the new
10685                // package has not opted out of backup participation.
10686                final boolean update = res.removedInfo.removedPackage != null;
10687                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10688                boolean doRestore = !update
10689                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10690
10691                // Set up the post-install work request bookkeeping.  This will be used
10692                // and cleaned up by the post-install event handling regardless of whether
10693                // there's a restore pass performed.  Token values are >= 1.
10694                int token;
10695                if (mNextInstallToken < 0) mNextInstallToken = 1;
10696                token = mNextInstallToken++;
10697
10698                PostInstallData data = new PostInstallData(args, res);
10699                mRunningInstalls.put(token, data);
10700                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10701
10702                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10703                    // Pass responsibility to the Backup Manager.  It will perform a
10704                    // restore if appropriate, then pass responsibility back to the
10705                    // Package Manager to run the post-install observer callbacks
10706                    // and broadcasts.
10707                    IBackupManager bm = IBackupManager.Stub.asInterface(
10708                            ServiceManager.getService(Context.BACKUP_SERVICE));
10709                    if (bm != null) {
10710                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10711                                + " to BM for possible restore");
10712                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10713                        try {
10714                            // TODO: http://b/22388012
10715                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10716                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10717                            } else {
10718                                doRestore = false;
10719                            }
10720                        } catch (RemoteException e) {
10721                            // can't happen; the backup manager is local
10722                        } catch (Exception e) {
10723                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10724                            doRestore = false;
10725                        }
10726                    } else {
10727                        Slog.e(TAG, "Backup Manager not found!");
10728                        doRestore = false;
10729                    }
10730                }
10731
10732                if (!doRestore) {
10733                    // No restore possible, or the Backup Manager was mysteriously not
10734                    // available -- just fire the post-install work request directly.
10735                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10736
10737                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10738
10739                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10740                    mHandler.sendMessage(msg);
10741                }
10742            }
10743        });
10744    }
10745
10746    private abstract class HandlerParams {
10747        private static final int MAX_RETRIES = 4;
10748
10749        /**
10750         * Number of times startCopy() has been attempted and had a non-fatal
10751         * error.
10752         */
10753        private int mRetries = 0;
10754
10755        /** User handle for the user requesting the information or installation. */
10756        private final UserHandle mUser;
10757        String traceMethod;
10758        int traceCookie;
10759
10760        HandlerParams(UserHandle user) {
10761            mUser = user;
10762        }
10763
10764        UserHandle getUser() {
10765            return mUser;
10766        }
10767
10768        HandlerParams setTraceMethod(String traceMethod) {
10769            this.traceMethod = traceMethod;
10770            return this;
10771        }
10772
10773        HandlerParams setTraceCookie(int traceCookie) {
10774            this.traceCookie = traceCookie;
10775            return this;
10776        }
10777
10778        final boolean startCopy() {
10779            boolean res;
10780            try {
10781                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10782
10783                if (++mRetries > MAX_RETRIES) {
10784                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10785                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10786                    handleServiceError();
10787                    return false;
10788                } else {
10789                    handleStartCopy();
10790                    res = true;
10791                }
10792            } catch (RemoteException e) {
10793                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10794                mHandler.sendEmptyMessage(MCS_RECONNECT);
10795                res = false;
10796            }
10797            handleReturnCode();
10798            return res;
10799        }
10800
10801        final void serviceError() {
10802            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10803            handleServiceError();
10804            handleReturnCode();
10805        }
10806
10807        abstract void handleStartCopy() throws RemoteException;
10808        abstract void handleServiceError();
10809        abstract void handleReturnCode();
10810    }
10811
10812    class MeasureParams extends HandlerParams {
10813        private final PackageStats mStats;
10814        private boolean mSuccess;
10815
10816        private final IPackageStatsObserver mObserver;
10817
10818        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10819            super(new UserHandle(stats.userHandle));
10820            mObserver = observer;
10821            mStats = stats;
10822        }
10823
10824        @Override
10825        public String toString() {
10826            return "MeasureParams{"
10827                + Integer.toHexString(System.identityHashCode(this))
10828                + " " + mStats.packageName + "}";
10829        }
10830
10831        @Override
10832        void handleStartCopy() throws RemoteException {
10833            synchronized (mInstallLock) {
10834                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10835            }
10836
10837            if (mSuccess) {
10838                final boolean mounted;
10839                if (Environment.isExternalStorageEmulated()) {
10840                    mounted = true;
10841                } else {
10842                    final String status = Environment.getExternalStorageState();
10843                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10844                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10845                }
10846
10847                if (mounted) {
10848                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10849
10850                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10851                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10852
10853                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10854                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10855
10856                    // Always subtract cache size, since it's a subdirectory
10857                    mStats.externalDataSize -= mStats.externalCacheSize;
10858
10859                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10860                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10861
10862                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10863                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10864                }
10865            }
10866        }
10867
10868        @Override
10869        void handleReturnCode() {
10870            if (mObserver != null) {
10871                try {
10872                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10873                } catch (RemoteException e) {
10874                    Slog.i(TAG, "Observer no longer exists.");
10875                }
10876            }
10877        }
10878
10879        @Override
10880        void handleServiceError() {
10881            Slog.e(TAG, "Could not measure application " + mStats.packageName
10882                            + " external storage");
10883        }
10884    }
10885
10886    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10887            throws RemoteException {
10888        long result = 0;
10889        for (File path : paths) {
10890            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10891        }
10892        return result;
10893    }
10894
10895    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10896        for (File path : paths) {
10897            try {
10898                mcs.clearDirectory(path.getAbsolutePath());
10899            } catch (RemoteException e) {
10900            }
10901        }
10902    }
10903
10904    static class OriginInfo {
10905        /**
10906         * Location where install is coming from, before it has been
10907         * copied/renamed into place. This could be a single monolithic APK
10908         * file, or a cluster directory. This location may be untrusted.
10909         */
10910        final File file;
10911        final String cid;
10912
10913        /**
10914         * Flag indicating that {@link #file} or {@link #cid} has already been
10915         * staged, meaning downstream users don't need to defensively copy the
10916         * contents.
10917         */
10918        final boolean staged;
10919
10920        /**
10921         * Flag indicating that {@link #file} or {@link #cid} is an already
10922         * installed app that is being moved.
10923         */
10924        final boolean existing;
10925
10926        final String resolvedPath;
10927        final File resolvedFile;
10928
10929        static OriginInfo fromNothing() {
10930            return new OriginInfo(null, null, false, false);
10931        }
10932
10933        static OriginInfo fromUntrustedFile(File file) {
10934            return new OriginInfo(file, null, false, false);
10935        }
10936
10937        static OriginInfo fromExistingFile(File file) {
10938            return new OriginInfo(file, null, false, true);
10939        }
10940
10941        static OriginInfo fromStagedFile(File file) {
10942            return new OriginInfo(file, null, true, false);
10943        }
10944
10945        static OriginInfo fromStagedContainer(String cid) {
10946            return new OriginInfo(null, cid, true, false);
10947        }
10948
10949        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10950            this.file = file;
10951            this.cid = cid;
10952            this.staged = staged;
10953            this.existing = existing;
10954
10955            if (cid != null) {
10956                resolvedPath = PackageHelper.getSdDir(cid);
10957                resolvedFile = new File(resolvedPath);
10958            } else if (file != null) {
10959                resolvedPath = file.getAbsolutePath();
10960                resolvedFile = file;
10961            } else {
10962                resolvedPath = null;
10963                resolvedFile = null;
10964            }
10965        }
10966    }
10967
10968    static class MoveInfo {
10969        final int moveId;
10970        final String fromUuid;
10971        final String toUuid;
10972        final String packageName;
10973        final String dataAppName;
10974        final int appId;
10975        final String seinfo;
10976
10977        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10978                String dataAppName, int appId, String seinfo) {
10979            this.moveId = moveId;
10980            this.fromUuid = fromUuid;
10981            this.toUuid = toUuid;
10982            this.packageName = packageName;
10983            this.dataAppName = dataAppName;
10984            this.appId = appId;
10985            this.seinfo = seinfo;
10986        }
10987    }
10988
10989    class InstallParams extends HandlerParams {
10990        final OriginInfo origin;
10991        final MoveInfo move;
10992        final IPackageInstallObserver2 observer;
10993        int installFlags;
10994        final String installerPackageName;
10995        final String volumeUuid;
10996        final VerificationParams verificationParams;
10997        private InstallArgs mArgs;
10998        private int mRet;
10999        final String packageAbiOverride;
11000        final String[] grantedRuntimePermissions;
11001
11002        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11003                int installFlags, String installerPackageName, String volumeUuid,
11004                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11005                String[] grantedPermissions) {
11006            super(user);
11007            this.origin = origin;
11008            this.move = move;
11009            this.observer = observer;
11010            this.installFlags = installFlags;
11011            this.installerPackageName = installerPackageName;
11012            this.volumeUuid = volumeUuid;
11013            this.verificationParams = verificationParams;
11014            this.packageAbiOverride = packageAbiOverride;
11015            this.grantedRuntimePermissions = grantedPermissions;
11016        }
11017
11018        @Override
11019        public String toString() {
11020            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11021                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11022        }
11023
11024        public ManifestDigest getManifestDigest() {
11025            if (verificationParams == null) {
11026                return null;
11027            }
11028            return verificationParams.getManifestDigest();
11029        }
11030
11031        private int installLocationPolicy(PackageInfoLite pkgLite) {
11032            String packageName = pkgLite.packageName;
11033            int installLocation = pkgLite.installLocation;
11034            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11035            // reader
11036            synchronized (mPackages) {
11037                PackageParser.Package pkg = mPackages.get(packageName);
11038                if (pkg != null) {
11039                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11040                        // Check for downgrading.
11041                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11042                            try {
11043                                checkDowngrade(pkg, pkgLite);
11044                            } catch (PackageManagerException e) {
11045                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11046                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11047                            }
11048                        }
11049                        // Check for updated system application.
11050                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11051                            if (onSd) {
11052                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11053                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11054                            }
11055                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11056                        } else {
11057                            if (onSd) {
11058                                // Install flag overrides everything.
11059                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11060                            }
11061                            // If current upgrade specifies particular preference
11062                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11063                                // Application explicitly specified internal.
11064                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11065                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11066                                // App explictly prefers external. Let policy decide
11067                            } else {
11068                                // Prefer previous location
11069                                if (isExternal(pkg)) {
11070                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11071                                }
11072                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11073                            }
11074                        }
11075                    } else {
11076                        // Invalid install. Return error code
11077                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11078                    }
11079                }
11080            }
11081            // All the special cases have been taken care of.
11082            // Return result based on recommended install location.
11083            if (onSd) {
11084                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11085            }
11086            return pkgLite.recommendedInstallLocation;
11087        }
11088
11089        /*
11090         * Invoke remote method to get package information and install
11091         * location values. Override install location based on default
11092         * policy if needed and then create install arguments based
11093         * on the install location.
11094         */
11095        public void handleStartCopy() throws RemoteException {
11096            int ret = PackageManager.INSTALL_SUCCEEDED;
11097
11098            // If we're already staged, we've firmly committed to an install location
11099            if (origin.staged) {
11100                if (origin.file != null) {
11101                    installFlags |= PackageManager.INSTALL_INTERNAL;
11102                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11103                } else if (origin.cid != null) {
11104                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11105                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11106                } else {
11107                    throw new IllegalStateException("Invalid stage location");
11108                }
11109            }
11110
11111            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11112            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11113            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11114            PackageInfoLite pkgLite = null;
11115
11116            if (onInt && onSd) {
11117                // Check if both bits are set.
11118                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11119                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11120            } else if (onSd && ephemeral) {
11121                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11122                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11123            } else {
11124                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11125                        packageAbiOverride);
11126
11127                if (DEBUG_EPHEMERAL && ephemeral) {
11128                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11129                }
11130
11131                /*
11132                 * If we have too little free space, try to free cache
11133                 * before giving up.
11134                 */
11135                if (!origin.staged && pkgLite.recommendedInstallLocation
11136                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11137                    // TODO: focus freeing disk space on the target device
11138                    final StorageManager storage = StorageManager.from(mContext);
11139                    final long lowThreshold = storage.getStorageLowBytes(
11140                            Environment.getDataDirectory());
11141
11142                    final long sizeBytes = mContainerService.calculateInstalledSize(
11143                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11144
11145                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11146                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11147                                installFlags, packageAbiOverride);
11148                    }
11149
11150                    /*
11151                     * The cache free must have deleted the file we
11152                     * downloaded to install.
11153                     *
11154                     * TODO: fix the "freeCache" call to not delete
11155                     *       the file we care about.
11156                     */
11157                    if (pkgLite.recommendedInstallLocation
11158                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11159                        pkgLite.recommendedInstallLocation
11160                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11161                    }
11162                }
11163            }
11164
11165            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11166                int loc = pkgLite.recommendedInstallLocation;
11167                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11168                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11169                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11170                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11171                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11172                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11173                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11174                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11175                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11176                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11177                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11178                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11179                } else {
11180                    // Override with defaults if needed.
11181                    loc = installLocationPolicy(pkgLite);
11182                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11183                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11184                    } else if (!onSd && !onInt) {
11185                        // Override install location with flags
11186                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11187                            // Set the flag to install on external media.
11188                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11189                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11190                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11191                            if (DEBUG_EPHEMERAL) {
11192                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11193                            }
11194                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11195                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11196                                    |PackageManager.INSTALL_INTERNAL);
11197                        } else {
11198                            // Make sure the flag for installing on external
11199                            // media is unset
11200                            installFlags |= PackageManager.INSTALL_INTERNAL;
11201                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11202                        }
11203                    }
11204                }
11205            }
11206
11207            final InstallArgs args = createInstallArgs(this);
11208            mArgs = args;
11209
11210            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11211                // TODO: http://b/22976637
11212                // Apps installed for "all" users use the device owner to verify the app
11213                UserHandle verifierUser = getUser();
11214                if (verifierUser == UserHandle.ALL) {
11215                    verifierUser = UserHandle.SYSTEM;
11216                }
11217
11218                /*
11219                 * Determine if we have any installed package verifiers. If we
11220                 * do, then we'll defer to them to verify the packages.
11221                 */
11222                final int requiredUid = mRequiredVerifierPackage == null ? -1
11223                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11224                if (!origin.existing && requiredUid != -1
11225                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11226                    final Intent verification = new Intent(
11227                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11228                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11229                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11230                            PACKAGE_MIME_TYPE);
11231                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11232
11233                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11234                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11235                            verifierUser.getIdentifier());
11236
11237                    if (DEBUG_VERIFY) {
11238                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11239                                + verification.toString() + " with " + pkgLite.verifiers.length
11240                                + " optional verifiers");
11241                    }
11242
11243                    final int verificationId = mPendingVerificationToken++;
11244
11245                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11246
11247                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11248                            installerPackageName);
11249
11250                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11251                            installFlags);
11252
11253                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11254                            pkgLite.packageName);
11255
11256                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11257                            pkgLite.versionCode);
11258
11259                    if (verificationParams != null) {
11260                        if (verificationParams.getVerificationURI() != null) {
11261                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11262                                 verificationParams.getVerificationURI());
11263                        }
11264                        if (verificationParams.getOriginatingURI() != null) {
11265                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11266                                  verificationParams.getOriginatingURI());
11267                        }
11268                        if (verificationParams.getReferrer() != null) {
11269                            verification.putExtra(Intent.EXTRA_REFERRER,
11270                                  verificationParams.getReferrer());
11271                        }
11272                        if (verificationParams.getOriginatingUid() >= 0) {
11273                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11274                                  verificationParams.getOriginatingUid());
11275                        }
11276                        if (verificationParams.getInstallerUid() >= 0) {
11277                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11278                                  verificationParams.getInstallerUid());
11279                        }
11280                    }
11281
11282                    final PackageVerificationState verificationState = new PackageVerificationState(
11283                            requiredUid, args);
11284
11285                    mPendingVerification.append(verificationId, verificationState);
11286
11287                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11288                            receivers, verificationState);
11289
11290                    /*
11291                     * If any sufficient verifiers were listed in the package
11292                     * manifest, attempt to ask them.
11293                     */
11294                    if (sufficientVerifiers != null) {
11295                        final int N = sufficientVerifiers.size();
11296                        if (N == 0) {
11297                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11298                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11299                        } else {
11300                            for (int i = 0; i < N; i++) {
11301                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11302
11303                                final Intent sufficientIntent = new Intent(verification);
11304                                sufficientIntent.setComponent(verifierComponent);
11305                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11306                            }
11307                        }
11308                    }
11309
11310                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11311                            mRequiredVerifierPackage, receivers);
11312                    if (ret == PackageManager.INSTALL_SUCCEEDED
11313                            && mRequiredVerifierPackage != null) {
11314                        Trace.asyncTraceBegin(
11315                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11316                        /*
11317                         * Send the intent to the required verification agent,
11318                         * but only start the verification timeout after the
11319                         * target BroadcastReceivers have run.
11320                         */
11321                        verification.setComponent(requiredVerifierComponent);
11322                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11323                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11324                                new BroadcastReceiver() {
11325                                    @Override
11326                                    public void onReceive(Context context, Intent intent) {
11327                                        final Message msg = mHandler
11328                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11329                                        msg.arg1 = verificationId;
11330                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11331                                    }
11332                                }, null, 0, null, null);
11333
11334                        /*
11335                         * We don't want the copy to proceed until verification
11336                         * succeeds, so null out this field.
11337                         */
11338                        mArgs = null;
11339                    }
11340                } else {
11341                    /*
11342                     * No package verification is enabled, so immediately start
11343                     * the remote call to initiate copy using temporary file.
11344                     */
11345                    ret = args.copyApk(mContainerService, true);
11346                }
11347            }
11348
11349            mRet = ret;
11350        }
11351
11352        @Override
11353        void handleReturnCode() {
11354            // If mArgs is null, then MCS couldn't be reached. When it
11355            // reconnects, it will try again to install. At that point, this
11356            // will succeed.
11357            if (mArgs != null) {
11358                processPendingInstall(mArgs, mRet);
11359            }
11360        }
11361
11362        @Override
11363        void handleServiceError() {
11364            mArgs = createInstallArgs(this);
11365            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11366        }
11367
11368        public boolean isForwardLocked() {
11369            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11370        }
11371    }
11372
11373    /**
11374     * Used during creation of InstallArgs
11375     *
11376     * @param installFlags package installation flags
11377     * @return true if should be installed on external storage
11378     */
11379    private static boolean installOnExternalAsec(int installFlags) {
11380        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11381            return false;
11382        }
11383        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11384            return true;
11385        }
11386        return false;
11387    }
11388
11389    /**
11390     * Used during creation of InstallArgs
11391     *
11392     * @param installFlags package installation flags
11393     * @return true if should be installed as forward locked
11394     */
11395    private static boolean installForwardLocked(int installFlags) {
11396        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11397    }
11398
11399    private InstallArgs createInstallArgs(InstallParams params) {
11400        if (params.move != null) {
11401            return new MoveInstallArgs(params);
11402        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11403            return new AsecInstallArgs(params);
11404        } else {
11405            return new FileInstallArgs(params);
11406        }
11407    }
11408
11409    /**
11410     * Create args that describe an existing installed package. Typically used
11411     * when cleaning up old installs, or used as a move source.
11412     */
11413    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11414            String resourcePath, String[] instructionSets) {
11415        final boolean isInAsec;
11416        if (installOnExternalAsec(installFlags)) {
11417            /* Apps on SD card are always in ASEC containers. */
11418            isInAsec = true;
11419        } else if (installForwardLocked(installFlags)
11420                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11421            /*
11422             * Forward-locked apps are only in ASEC containers if they're the
11423             * new style
11424             */
11425            isInAsec = true;
11426        } else {
11427            isInAsec = false;
11428        }
11429
11430        if (isInAsec) {
11431            return new AsecInstallArgs(codePath, instructionSets,
11432                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11433        } else {
11434            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11435        }
11436    }
11437
11438    static abstract class InstallArgs {
11439        /** @see InstallParams#origin */
11440        final OriginInfo origin;
11441        /** @see InstallParams#move */
11442        final MoveInfo move;
11443
11444        final IPackageInstallObserver2 observer;
11445        // Always refers to PackageManager flags only
11446        final int installFlags;
11447        final String installerPackageName;
11448        final String volumeUuid;
11449        final ManifestDigest manifestDigest;
11450        final UserHandle user;
11451        final String abiOverride;
11452        final String[] installGrantPermissions;
11453        /** If non-null, drop an async trace when the install completes */
11454        final String traceMethod;
11455        final int traceCookie;
11456
11457        // The list of instruction sets supported by this app. This is currently
11458        // only used during the rmdex() phase to clean up resources. We can get rid of this
11459        // if we move dex files under the common app path.
11460        /* nullable */ String[] instructionSets;
11461
11462        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11463                int installFlags, String installerPackageName, String volumeUuid,
11464                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11465                String abiOverride, String[] installGrantPermissions,
11466                String traceMethod, int traceCookie) {
11467            this.origin = origin;
11468            this.move = move;
11469            this.installFlags = installFlags;
11470            this.observer = observer;
11471            this.installerPackageName = installerPackageName;
11472            this.volumeUuid = volumeUuid;
11473            this.manifestDigest = manifestDigest;
11474            this.user = user;
11475            this.instructionSets = instructionSets;
11476            this.abiOverride = abiOverride;
11477            this.installGrantPermissions = installGrantPermissions;
11478            this.traceMethod = traceMethod;
11479            this.traceCookie = traceCookie;
11480        }
11481
11482        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11483        abstract int doPreInstall(int status);
11484
11485        /**
11486         * Rename package into final resting place. All paths on the given
11487         * scanned package should be updated to reflect the rename.
11488         */
11489        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11490        abstract int doPostInstall(int status, int uid);
11491
11492        /** @see PackageSettingBase#codePathString */
11493        abstract String getCodePath();
11494        /** @see PackageSettingBase#resourcePathString */
11495        abstract String getResourcePath();
11496
11497        // Need installer lock especially for dex file removal.
11498        abstract void cleanUpResourcesLI();
11499        abstract boolean doPostDeleteLI(boolean delete);
11500
11501        /**
11502         * Called before the source arguments are copied. This is used mostly
11503         * for MoveParams when it needs to read the source file to put it in the
11504         * destination.
11505         */
11506        int doPreCopy() {
11507            return PackageManager.INSTALL_SUCCEEDED;
11508        }
11509
11510        /**
11511         * Called after the source arguments are copied. This is used mostly for
11512         * MoveParams when it needs to read the source file to put it in the
11513         * destination.
11514         *
11515         * @return
11516         */
11517        int doPostCopy(int uid) {
11518            return PackageManager.INSTALL_SUCCEEDED;
11519        }
11520
11521        protected boolean isFwdLocked() {
11522            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11523        }
11524
11525        protected boolean isExternalAsec() {
11526            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11527        }
11528
11529        protected boolean isEphemeral() {
11530            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11531        }
11532
11533        UserHandle getUser() {
11534            return user;
11535        }
11536    }
11537
11538    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11539        if (!allCodePaths.isEmpty()) {
11540            if (instructionSets == null) {
11541                throw new IllegalStateException("instructionSet == null");
11542            }
11543            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11544            for (String codePath : allCodePaths) {
11545                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11546                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11547                    if (retCode < 0) {
11548                        Slog.w(TAG, "Couldn't remove dex file for package: "
11549                                + " at location " + codePath + ", retcode=" + retCode);
11550                        // we don't consider this to be a failure of the core package deletion
11551                    }
11552                }
11553            }
11554        }
11555    }
11556
11557    /**
11558     * Logic to handle installation of non-ASEC applications, including copying
11559     * and renaming logic.
11560     */
11561    class FileInstallArgs extends InstallArgs {
11562        private File codeFile;
11563        private File resourceFile;
11564
11565        // Example topology:
11566        // /data/app/com.example/base.apk
11567        // /data/app/com.example/split_foo.apk
11568        // /data/app/com.example/lib/arm/libfoo.so
11569        // /data/app/com.example/lib/arm64/libfoo.so
11570        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11571
11572        /** New install */
11573        FileInstallArgs(InstallParams params) {
11574            super(params.origin, params.move, params.observer, params.installFlags,
11575                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11576                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11577                    params.grantedRuntimePermissions,
11578                    params.traceMethod, params.traceCookie);
11579            if (isFwdLocked()) {
11580                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11581            }
11582        }
11583
11584        /** Existing install */
11585        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11586            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11587                    null, null, null, 0);
11588            this.codeFile = (codePath != null) ? new File(codePath) : null;
11589            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11590        }
11591
11592        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11593            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11594            try {
11595                return doCopyApk(imcs, temp);
11596            } finally {
11597                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11598            }
11599        }
11600
11601        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11602            if (origin.staged) {
11603                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11604                codeFile = origin.file;
11605                resourceFile = origin.file;
11606                return PackageManager.INSTALL_SUCCEEDED;
11607            }
11608
11609            try {
11610                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11611                final File tempDir =
11612                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11613                codeFile = tempDir;
11614                resourceFile = tempDir;
11615            } catch (IOException e) {
11616                Slog.w(TAG, "Failed to create copy file: " + e);
11617                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11618            }
11619
11620            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11621                @Override
11622                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11623                    if (!FileUtils.isValidExtFilename(name)) {
11624                        throw new IllegalArgumentException("Invalid filename: " + name);
11625                    }
11626                    try {
11627                        final File file = new File(codeFile, name);
11628                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11629                                O_RDWR | O_CREAT, 0644);
11630                        Os.chmod(file.getAbsolutePath(), 0644);
11631                        return new ParcelFileDescriptor(fd);
11632                    } catch (ErrnoException e) {
11633                        throw new RemoteException("Failed to open: " + e.getMessage());
11634                    }
11635                }
11636            };
11637
11638            int ret = PackageManager.INSTALL_SUCCEEDED;
11639            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11640            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11641                Slog.e(TAG, "Failed to copy package");
11642                return ret;
11643            }
11644
11645            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11646            NativeLibraryHelper.Handle handle = null;
11647            try {
11648                handle = NativeLibraryHelper.Handle.create(codeFile);
11649                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11650                        abiOverride);
11651            } catch (IOException e) {
11652                Slog.e(TAG, "Copying native libraries failed", e);
11653                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11654            } finally {
11655                IoUtils.closeQuietly(handle);
11656            }
11657
11658            return ret;
11659        }
11660
11661        int doPreInstall(int status) {
11662            if (status != PackageManager.INSTALL_SUCCEEDED) {
11663                cleanUp();
11664            }
11665            return status;
11666        }
11667
11668        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11669            if (status != PackageManager.INSTALL_SUCCEEDED) {
11670                cleanUp();
11671                return false;
11672            }
11673
11674            final File targetDir = codeFile.getParentFile();
11675            final File beforeCodeFile = codeFile;
11676            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11677
11678            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11679            try {
11680                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11681            } catch (ErrnoException e) {
11682                Slog.w(TAG, "Failed to rename", e);
11683                return false;
11684            }
11685
11686            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11687                Slog.w(TAG, "Failed to restorecon");
11688                return false;
11689            }
11690
11691            // Reflect the rename internally
11692            codeFile = afterCodeFile;
11693            resourceFile = afterCodeFile;
11694
11695            // Reflect the rename in scanned details
11696            pkg.codePath = afterCodeFile.getAbsolutePath();
11697            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11698                    pkg.baseCodePath);
11699            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11700                    pkg.splitCodePaths);
11701
11702            // Reflect the rename in app info
11703            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11704            pkg.applicationInfo.setCodePath(pkg.codePath);
11705            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11706            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11707            pkg.applicationInfo.setResourcePath(pkg.codePath);
11708            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11709            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11710
11711            return true;
11712        }
11713
11714        int doPostInstall(int status, int uid) {
11715            if (status != PackageManager.INSTALL_SUCCEEDED) {
11716                cleanUp();
11717            }
11718            return status;
11719        }
11720
11721        @Override
11722        String getCodePath() {
11723            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11724        }
11725
11726        @Override
11727        String getResourcePath() {
11728            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11729        }
11730
11731        private boolean cleanUp() {
11732            if (codeFile == null || !codeFile.exists()) {
11733                return false;
11734            }
11735
11736            if (codeFile.isDirectory()) {
11737                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11738            } else {
11739                codeFile.delete();
11740            }
11741
11742            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11743                resourceFile.delete();
11744            }
11745
11746            return true;
11747        }
11748
11749        void cleanUpResourcesLI() {
11750            // Try enumerating all code paths before deleting
11751            List<String> allCodePaths = Collections.EMPTY_LIST;
11752            if (codeFile != null && codeFile.exists()) {
11753                try {
11754                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11755                    allCodePaths = pkg.getAllCodePaths();
11756                } catch (PackageParserException e) {
11757                    // Ignored; we tried our best
11758                }
11759            }
11760
11761            cleanUp();
11762            removeDexFiles(allCodePaths, instructionSets);
11763        }
11764
11765        boolean doPostDeleteLI(boolean delete) {
11766            // XXX err, shouldn't we respect the delete flag?
11767            cleanUpResourcesLI();
11768            return true;
11769        }
11770    }
11771
11772    private boolean isAsecExternal(String cid) {
11773        final String asecPath = PackageHelper.getSdFilesystem(cid);
11774        return !asecPath.startsWith(mAsecInternalPath);
11775    }
11776
11777    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11778            PackageManagerException {
11779        if (copyRet < 0) {
11780            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11781                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11782                throw new PackageManagerException(copyRet, message);
11783            }
11784        }
11785    }
11786
11787    /**
11788     * Extract the MountService "container ID" from the full code path of an
11789     * .apk.
11790     */
11791    static String cidFromCodePath(String fullCodePath) {
11792        int eidx = fullCodePath.lastIndexOf("/");
11793        String subStr1 = fullCodePath.substring(0, eidx);
11794        int sidx = subStr1.lastIndexOf("/");
11795        return subStr1.substring(sidx+1, eidx);
11796    }
11797
11798    /**
11799     * Logic to handle installation of ASEC applications, including copying and
11800     * renaming logic.
11801     */
11802    class AsecInstallArgs extends InstallArgs {
11803        static final String RES_FILE_NAME = "pkg.apk";
11804        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11805
11806        String cid;
11807        String packagePath;
11808        String resourcePath;
11809
11810        /** New install */
11811        AsecInstallArgs(InstallParams params) {
11812            super(params.origin, params.move, params.observer, params.installFlags,
11813                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11814                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11815                    params.grantedRuntimePermissions,
11816                    params.traceMethod, params.traceCookie);
11817        }
11818
11819        /** Existing install */
11820        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11821                        boolean isExternal, boolean isForwardLocked) {
11822            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11823                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11824                    instructionSets, null, null, null, 0);
11825            // Hackily pretend we're still looking at a full code path
11826            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11827                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11828            }
11829
11830            // Extract cid from fullCodePath
11831            int eidx = fullCodePath.lastIndexOf("/");
11832            String subStr1 = fullCodePath.substring(0, eidx);
11833            int sidx = subStr1.lastIndexOf("/");
11834            cid = subStr1.substring(sidx+1, eidx);
11835            setMountPath(subStr1);
11836        }
11837
11838        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11839            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11840                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11841                    instructionSets, null, null, null, 0);
11842            this.cid = cid;
11843            setMountPath(PackageHelper.getSdDir(cid));
11844        }
11845
11846        void createCopyFile() {
11847            cid = mInstallerService.allocateExternalStageCidLegacy();
11848        }
11849
11850        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11851            if (origin.staged && origin.cid != null) {
11852                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11853                cid = origin.cid;
11854                setMountPath(PackageHelper.getSdDir(cid));
11855                return PackageManager.INSTALL_SUCCEEDED;
11856            }
11857
11858            if (temp) {
11859                createCopyFile();
11860            } else {
11861                /*
11862                 * Pre-emptively destroy the container since it's destroyed if
11863                 * copying fails due to it existing anyway.
11864                 */
11865                PackageHelper.destroySdDir(cid);
11866            }
11867
11868            final String newMountPath = imcs.copyPackageToContainer(
11869                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11870                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11871
11872            if (newMountPath != null) {
11873                setMountPath(newMountPath);
11874                return PackageManager.INSTALL_SUCCEEDED;
11875            } else {
11876                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11877            }
11878        }
11879
11880        @Override
11881        String getCodePath() {
11882            return packagePath;
11883        }
11884
11885        @Override
11886        String getResourcePath() {
11887            return resourcePath;
11888        }
11889
11890        int doPreInstall(int status) {
11891            if (status != PackageManager.INSTALL_SUCCEEDED) {
11892                // Destroy container
11893                PackageHelper.destroySdDir(cid);
11894            } else {
11895                boolean mounted = PackageHelper.isContainerMounted(cid);
11896                if (!mounted) {
11897                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11898                            Process.SYSTEM_UID);
11899                    if (newMountPath != null) {
11900                        setMountPath(newMountPath);
11901                    } else {
11902                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11903                    }
11904                }
11905            }
11906            return status;
11907        }
11908
11909        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11910            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11911            String newMountPath = null;
11912            if (PackageHelper.isContainerMounted(cid)) {
11913                // Unmount the container
11914                if (!PackageHelper.unMountSdDir(cid)) {
11915                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11916                    return false;
11917                }
11918            }
11919            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11920                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11921                        " which might be stale. Will try to clean up.");
11922                // Clean up the stale container and proceed to recreate.
11923                if (!PackageHelper.destroySdDir(newCacheId)) {
11924                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11925                    return false;
11926                }
11927                // Successfully cleaned up stale container. Try to rename again.
11928                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11929                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11930                            + " inspite of cleaning it up.");
11931                    return false;
11932                }
11933            }
11934            if (!PackageHelper.isContainerMounted(newCacheId)) {
11935                Slog.w(TAG, "Mounting container " + newCacheId);
11936                newMountPath = PackageHelper.mountSdDir(newCacheId,
11937                        getEncryptKey(), Process.SYSTEM_UID);
11938            } else {
11939                newMountPath = PackageHelper.getSdDir(newCacheId);
11940            }
11941            if (newMountPath == null) {
11942                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11943                return false;
11944            }
11945            Log.i(TAG, "Succesfully renamed " + cid +
11946                    " to " + newCacheId +
11947                    " at new path: " + newMountPath);
11948            cid = newCacheId;
11949
11950            final File beforeCodeFile = new File(packagePath);
11951            setMountPath(newMountPath);
11952            final File afterCodeFile = new File(packagePath);
11953
11954            // Reflect the rename in scanned details
11955            pkg.codePath = afterCodeFile.getAbsolutePath();
11956            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11957                    pkg.baseCodePath);
11958            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11959                    pkg.splitCodePaths);
11960
11961            // Reflect the rename in app info
11962            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11963            pkg.applicationInfo.setCodePath(pkg.codePath);
11964            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11965            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11966            pkg.applicationInfo.setResourcePath(pkg.codePath);
11967            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11968            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11969
11970            return true;
11971        }
11972
11973        private void setMountPath(String mountPath) {
11974            final File mountFile = new File(mountPath);
11975
11976            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11977            if (monolithicFile.exists()) {
11978                packagePath = monolithicFile.getAbsolutePath();
11979                if (isFwdLocked()) {
11980                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11981                } else {
11982                    resourcePath = packagePath;
11983                }
11984            } else {
11985                packagePath = mountFile.getAbsolutePath();
11986                resourcePath = packagePath;
11987            }
11988        }
11989
11990        int doPostInstall(int status, int uid) {
11991            if (status != PackageManager.INSTALL_SUCCEEDED) {
11992                cleanUp();
11993            } else {
11994                final int groupOwner;
11995                final String protectedFile;
11996                if (isFwdLocked()) {
11997                    groupOwner = UserHandle.getSharedAppGid(uid);
11998                    protectedFile = RES_FILE_NAME;
11999                } else {
12000                    groupOwner = -1;
12001                    protectedFile = null;
12002                }
12003
12004                if (uid < Process.FIRST_APPLICATION_UID
12005                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12006                    Slog.e(TAG, "Failed to finalize " + cid);
12007                    PackageHelper.destroySdDir(cid);
12008                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12009                }
12010
12011                boolean mounted = PackageHelper.isContainerMounted(cid);
12012                if (!mounted) {
12013                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12014                }
12015            }
12016            return status;
12017        }
12018
12019        private void cleanUp() {
12020            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12021
12022            // Destroy secure container
12023            PackageHelper.destroySdDir(cid);
12024        }
12025
12026        private List<String> getAllCodePaths() {
12027            final File codeFile = new File(getCodePath());
12028            if (codeFile != null && codeFile.exists()) {
12029                try {
12030                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12031                    return pkg.getAllCodePaths();
12032                } catch (PackageParserException e) {
12033                    // Ignored; we tried our best
12034                }
12035            }
12036            return Collections.EMPTY_LIST;
12037        }
12038
12039        void cleanUpResourcesLI() {
12040            // Enumerate all code paths before deleting
12041            cleanUpResourcesLI(getAllCodePaths());
12042        }
12043
12044        private void cleanUpResourcesLI(List<String> allCodePaths) {
12045            cleanUp();
12046            removeDexFiles(allCodePaths, instructionSets);
12047        }
12048
12049        String getPackageName() {
12050            return getAsecPackageName(cid);
12051        }
12052
12053        boolean doPostDeleteLI(boolean delete) {
12054            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12055            final List<String> allCodePaths = getAllCodePaths();
12056            boolean mounted = PackageHelper.isContainerMounted(cid);
12057            if (mounted) {
12058                // Unmount first
12059                if (PackageHelper.unMountSdDir(cid)) {
12060                    mounted = false;
12061                }
12062            }
12063            if (!mounted && delete) {
12064                cleanUpResourcesLI(allCodePaths);
12065            }
12066            return !mounted;
12067        }
12068
12069        @Override
12070        int doPreCopy() {
12071            if (isFwdLocked()) {
12072                if (!PackageHelper.fixSdPermissions(cid,
12073                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12074                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12075                }
12076            }
12077
12078            return PackageManager.INSTALL_SUCCEEDED;
12079        }
12080
12081        @Override
12082        int doPostCopy(int uid) {
12083            if (isFwdLocked()) {
12084                if (uid < Process.FIRST_APPLICATION_UID
12085                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12086                                RES_FILE_NAME)) {
12087                    Slog.e(TAG, "Failed to finalize " + cid);
12088                    PackageHelper.destroySdDir(cid);
12089                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12090                }
12091            }
12092
12093            return PackageManager.INSTALL_SUCCEEDED;
12094        }
12095    }
12096
12097    /**
12098     * Logic to handle movement of existing installed applications.
12099     */
12100    class MoveInstallArgs extends InstallArgs {
12101        private File codeFile;
12102        private File resourceFile;
12103
12104        /** New install */
12105        MoveInstallArgs(InstallParams params) {
12106            super(params.origin, params.move, params.observer, params.installFlags,
12107                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
12108                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12109                    params.grantedRuntimePermissions,
12110                    params.traceMethod, params.traceCookie);
12111        }
12112
12113        int copyApk(IMediaContainerService imcs, boolean temp) {
12114            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12115                    + move.fromUuid + " to " + move.toUuid);
12116            synchronized (mInstaller) {
12117                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12118                        move.dataAppName, move.appId, move.seinfo) != 0) {
12119                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12120                }
12121            }
12122
12123            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12124            resourceFile = codeFile;
12125            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12126
12127            return PackageManager.INSTALL_SUCCEEDED;
12128        }
12129
12130        int doPreInstall(int status) {
12131            if (status != PackageManager.INSTALL_SUCCEEDED) {
12132                cleanUp(move.toUuid);
12133            }
12134            return status;
12135        }
12136
12137        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12138            if (status != PackageManager.INSTALL_SUCCEEDED) {
12139                cleanUp(move.toUuid);
12140                return false;
12141            }
12142
12143            // Reflect the move in app info
12144            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12145            pkg.applicationInfo.setCodePath(pkg.codePath);
12146            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12147            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12148            pkg.applicationInfo.setResourcePath(pkg.codePath);
12149            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12150            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12151
12152            return true;
12153        }
12154
12155        int doPostInstall(int status, int uid) {
12156            if (status == PackageManager.INSTALL_SUCCEEDED) {
12157                cleanUp(move.fromUuid);
12158            } else {
12159                cleanUp(move.toUuid);
12160            }
12161            return status;
12162        }
12163
12164        @Override
12165        String getCodePath() {
12166            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12167        }
12168
12169        @Override
12170        String getResourcePath() {
12171            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12172        }
12173
12174        private boolean cleanUp(String volumeUuid) {
12175            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12176                    move.dataAppName);
12177            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12178            synchronized (mInstallLock) {
12179                // Clean up both app data and code
12180                removeDataDirsLI(volumeUuid, move.packageName);
12181                if (codeFile.isDirectory()) {
12182                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12183                } else {
12184                    codeFile.delete();
12185                }
12186            }
12187            return true;
12188        }
12189
12190        void cleanUpResourcesLI() {
12191            throw new UnsupportedOperationException();
12192        }
12193
12194        boolean doPostDeleteLI(boolean delete) {
12195            throw new UnsupportedOperationException();
12196        }
12197    }
12198
12199    static String getAsecPackageName(String packageCid) {
12200        int idx = packageCid.lastIndexOf("-");
12201        if (idx == -1) {
12202            return packageCid;
12203        }
12204        return packageCid.substring(0, idx);
12205    }
12206
12207    // Utility method used to create code paths based on package name and available index.
12208    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12209        String idxStr = "";
12210        int idx = 1;
12211        // Fall back to default value of idx=1 if prefix is not
12212        // part of oldCodePath
12213        if (oldCodePath != null) {
12214            String subStr = oldCodePath;
12215            // Drop the suffix right away
12216            if (suffix != null && subStr.endsWith(suffix)) {
12217                subStr = subStr.substring(0, subStr.length() - suffix.length());
12218            }
12219            // If oldCodePath already contains prefix find out the
12220            // ending index to either increment or decrement.
12221            int sidx = subStr.lastIndexOf(prefix);
12222            if (sidx != -1) {
12223                subStr = subStr.substring(sidx + prefix.length());
12224                if (subStr != null) {
12225                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12226                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12227                    }
12228                    try {
12229                        idx = Integer.parseInt(subStr);
12230                        if (idx <= 1) {
12231                            idx++;
12232                        } else {
12233                            idx--;
12234                        }
12235                    } catch(NumberFormatException e) {
12236                    }
12237                }
12238            }
12239        }
12240        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12241        return prefix + idxStr;
12242    }
12243
12244    private File getNextCodePath(File targetDir, String packageName) {
12245        int suffix = 1;
12246        File result;
12247        do {
12248            result = new File(targetDir, packageName + "-" + suffix);
12249            suffix++;
12250        } while (result.exists());
12251        return result;
12252    }
12253
12254    // Utility method that returns the relative package path with respect
12255    // to the installation directory. Like say for /data/data/com.test-1.apk
12256    // string com.test-1 is returned.
12257    static String deriveCodePathName(String codePath) {
12258        if (codePath == null) {
12259            return null;
12260        }
12261        final File codeFile = new File(codePath);
12262        final String name = codeFile.getName();
12263        if (codeFile.isDirectory()) {
12264            return name;
12265        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12266            final int lastDot = name.lastIndexOf('.');
12267            return name.substring(0, lastDot);
12268        } else {
12269            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12270            return null;
12271        }
12272    }
12273
12274    static class PackageInstalledInfo {
12275        String name;
12276        int uid;
12277        // The set of users that originally had this package installed.
12278        int[] origUsers;
12279        // The set of users that now have this package installed.
12280        int[] newUsers;
12281        PackageParser.Package pkg;
12282        int returnCode;
12283        String returnMsg;
12284        PackageRemovedInfo removedInfo;
12285
12286        public void setError(int code, String msg) {
12287            returnCode = code;
12288            returnMsg = msg;
12289            Slog.w(TAG, msg);
12290        }
12291
12292        public void setError(String msg, PackageParserException e) {
12293            returnCode = e.error;
12294            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12295            Slog.w(TAG, msg, e);
12296        }
12297
12298        public void setError(String msg, PackageManagerException e) {
12299            returnCode = e.error;
12300            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12301            Slog.w(TAG, msg, e);
12302        }
12303
12304        // In some error cases we want to convey more info back to the observer
12305        String origPackage;
12306        String origPermission;
12307    }
12308
12309    /*
12310     * Install a non-existing package.
12311     */
12312    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12313            UserHandle user, String installerPackageName, String volumeUuid,
12314            PackageInstalledInfo res) {
12315        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12316
12317        // Remember this for later, in case we need to rollback this install
12318        String pkgName = pkg.packageName;
12319
12320        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12321        // TODO: b/23350563
12322        final boolean dataDirExists = Environment
12323                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12324
12325        synchronized(mPackages) {
12326            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12327                // A package with the same name is already installed, though
12328                // it has been renamed to an older name.  The package we
12329                // are trying to install should be installed as an update to
12330                // the existing one, but that has not been requested, so bail.
12331                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12332                        + " without first uninstalling package running as "
12333                        + mSettings.mRenamedPackages.get(pkgName));
12334                return;
12335            }
12336            if (mPackages.containsKey(pkgName)) {
12337                // Don't allow installation over an existing package with the same name.
12338                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12339                        + " without first uninstalling.");
12340                return;
12341            }
12342        }
12343
12344        try {
12345            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12346                    System.currentTimeMillis(), user);
12347
12348            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12349            // delete the partially installed application. the data directory will have to be
12350            // restored if it was already existing
12351            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12352                // remove package from internal structures.  Note that we want deletePackageX to
12353                // delete the package data and cache directories that it created in
12354                // scanPackageLocked, unless those directories existed before we even tried to
12355                // install.
12356                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12357                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12358                                res.removedInfo, true);
12359            }
12360
12361        } catch (PackageManagerException e) {
12362            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12363        }
12364
12365        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12366    }
12367
12368    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12369        // Can't rotate keys during boot or if sharedUser.
12370        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12371                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12372            return false;
12373        }
12374        // app is using upgradeKeySets; make sure all are valid
12375        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12376        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12377        for (int i = 0; i < upgradeKeySets.length; i++) {
12378            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12379                Slog.wtf(TAG, "Package "
12380                         + (oldPs.name != null ? oldPs.name : "<null>")
12381                         + " contains upgrade-key-set reference to unknown key-set: "
12382                         + upgradeKeySets[i]
12383                         + " reverting to signatures check.");
12384                return false;
12385            }
12386        }
12387        return true;
12388    }
12389
12390    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12391        // Upgrade keysets are being used.  Determine if new package has a superset of the
12392        // required keys.
12393        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12394        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12395        for (int i = 0; i < upgradeKeySets.length; i++) {
12396            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12397            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12398                return true;
12399            }
12400        }
12401        return false;
12402    }
12403
12404    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12405            UserHandle user, String installerPackageName, String volumeUuid,
12406            PackageInstalledInfo res) {
12407        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12408
12409        final PackageParser.Package oldPackage;
12410        final String pkgName = pkg.packageName;
12411        final int[] allUsers;
12412        final boolean[] perUserInstalled;
12413
12414        // First find the old package info and check signatures
12415        synchronized(mPackages) {
12416            oldPackage = mPackages.get(pkgName);
12417            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12418            if (isEphemeral && !oldIsEphemeral) {
12419                // can't downgrade from full to ephemeral
12420                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12421                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12422                return;
12423            }
12424            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12425            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12426            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12427                if(!checkUpgradeKeySetLP(ps, pkg)) {
12428                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12429                            "New package not signed by keys specified by upgrade-keysets: "
12430                            + pkgName);
12431                    return;
12432                }
12433            } else {
12434                // default to original signature matching
12435                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12436                    != PackageManager.SIGNATURE_MATCH) {
12437                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12438                            "New package has a different signature: " + pkgName);
12439                    return;
12440                }
12441            }
12442
12443            // In case of rollback, remember per-user/profile install state
12444            allUsers = sUserManager.getUserIds();
12445            perUserInstalled = new boolean[allUsers.length];
12446            for (int i = 0; i < allUsers.length; i++) {
12447                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12448            }
12449        }
12450
12451        boolean sysPkg = (isSystemApp(oldPackage));
12452        if (sysPkg) {
12453            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12454                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12455        } else {
12456            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12457                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12458        }
12459    }
12460
12461    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12462            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12463            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12464            String volumeUuid, PackageInstalledInfo res) {
12465        String pkgName = deletedPackage.packageName;
12466        boolean deletedPkg = true;
12467        boolean updatedSettings = false;
12468
12469        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12470                + deletedPackage);
12471        long origUpdateTime;
12472        if (pkg.mExtras != null) {
12473            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12474        } else {
12475            origUpdateTime = 0;
12476        }
12477
12478        // First delete the existing package while retaining the data directory
12479        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12480                res.removedInfo, true)) {
12481            // If the existing package wasn't successfully deleted
12482            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12483            deletedPkg = false;
12484        } else {
12485            // Successfully deleted the old package; proceed with replace.
12486
12487            // If deleted package lived in a container, give users a chance to
12488            // relinquish resources before killing.
12489            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12490                if (DEBUG_INSTALL) {
12491                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12492                }
12493                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12494                final ArrayList<String> pkgList = new ArrayList<String>(1);
12495                pkgList.add(deletedPackage.applicationInfo.packageName);
12496                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12497            }
12498
12499            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12500            try {
12501                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12502                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12503                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12504                        perUserInstalled, res, user);
12505                updatedSettings = true;
12506            } catch (PackageManagerException e) {
12507                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12508            }
12509        }
12510
12511        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12512            // remove package from internal structures.  Note that we want deletePackageX to
12513            // delete the package data and cache directories that it created in
12514            // scanPackageLocked, unless those directories existed before we even tried to
12515            // install.
12516            if(updatedSettings) {
12517                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12518                deletePackageLI(
12519                        pkgName, null, true, allUsers, perUserInstalled,
12520                        PackageManager.DELETE_KEEP_DATA,
12521                                res.removedInfo, true);
12522            }
12523            // Since we failed to install the new package we need to restore the old
12524            // package that we deleted.
12525            if (deletedPkg) {
12526                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12527                File restoreFile = new File(deletedPackage.codePath);
12528                // Parse old package
12529                boolean oldExternal = isExternal(deletedPackage);
12530                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12531                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12532                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12533                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12534                try {
12535                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12536                            null);
12537                } catch (PackageManagerException e) {
12538                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12539                            + e.getMessage());
12540                    return;
12541                }
12542                // Restore of old package succeeded. Update permissions.
12543                // writer
12544                synchronized (mPackages) {
12545                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12546                            UPDATE_PERMISSIONS_ALL);
12547                    // can downgrade to reader
12548                    mSettings.writeLPr();
12549                }
12550                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12551            }
12552        }
12553    }
12554
12555    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12556            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12557            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12558            String volumeUuid, PackageInstalledInfo res) {
12559        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12560                + ", old=" + deletedPackage);
12561        boolean disabledSystem = false;
12562        boolean updatedSettings = false;
12563        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12564        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12565                != 0) {
12566            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12567        }
12568        String packageName = deletedPackage.packageName;
12569        if (packageName == null) {
12570            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12571                    "Attempt to delete null packageName.");
12572            return;
12573        }
12574        PackageParser.Package oldPkg;
12575        PackageSetting oldPkgSetting;
12576        // reader
12577        synchronized (mPackages) {
12578            oldPkg = mPackages.get(packageName);
12579            oldPkgSetting = mSettings.mPackages.get(packageName);
12580            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12581                    (oldPkgSetting == null)) {
12582                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12583                        "Couldn't find package:" + packageName + " information");
12584                return;
12585            }
12586        }
12587
12588        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12589
12590        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12591        res.removedInfo.removedPackage = packageName;
12592        // Remove existing system package
12593        removePackageLI(oldPkgSetting, true);
12594        // writer
12595        synchronized (mPackages) {
12596            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12597            if (!disabledSystem && deletedPackage != null) {
12598                // We didn't need to disable the .apk as a current system package,
12599                // which means we are replacing another update that is already
12600                // installed.  We need to make sure to delete the older one's .apk.
12601                res.removedInfo.args = createInstallArgsForExisting(0,
12602                        deletedPackage.applicationInfo.getCodePath(),
12603                        deletedPackage.applicationInfo.getResourcePath(),
12604                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12605            } else {
12606                res.removedInfo.args = null;
12607            }
12608        }
12609
12610        // Successfully disabled the old package. Now proceed with re-installation
12611        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12612
12613        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12614        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12615
12616        PackageParser.Package newPackage = null;
12617        try {
12618            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12619            if (newPackage.mExtras != null) {
12620                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12621                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12622                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12623
12624                // is the update attempting to change shared user? that isn't going to work...
12625                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12626                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12627                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12628                            + " to " + newPkgSetting.sharedUser);
12629                    updatedSettings = true;
12630                }
12631            }
12632
12633            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12634                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12635                        perUserInstalled, res, user);
12636                updatedSettings = true;
12637            }
12638
12639        } catch (PackageManagerException e) {
12640            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12641        }
12642
12643        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12644            // Re installation failed. Restore old information
12645            // Remove new pkg information
12646            if (newPackage != null) {
12647                removeInstalledPackageLI(newPackage, true);
12648            }
12649            // Add back the old system package
12650            try {
12651                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12652            } catch (PackageManagerException e) {
12653                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12654            }
12655            // Restore the old system information in Settings
12656            synchronized (mPackages) {
12657                if (disabledSystem) {
12658                    mSettings.enableSystemPackageLPw(packageName);
12659                }
12660                if (updatedSettings) {
12661                    mSettings.setInstallerPackageName(packageName,
12662                            oldPkgSetting.installerPackageName);
12663                }
12664                mSettings.writeLPr();
12665            }
12666        }
12667    }
12668
12669    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12670        // Collect all used permissions in the UID
12671        ArraySet<String> usedPermissions = new ArraySet<>();
12672        final int packageCount = su.packages.size();
12673        for (int i = 0; i < packageCount; i++) {
12674            PackageSetting ps = su.packages.valueAt(i);
12675            if (ps.pkg == null) {
12676                continue;
12677            }
12678            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12679            for (int j = 0; j < requestedPermCount; j++) {
12680                String permission = ps.pkg.requestedPermissions.get(j);
12681                BasePermission bp = mSettings.mPermissions.get(permission);
12682                if (bp != null) {
12683                    usedPermissions.add(permission);
12684                }
12685            }
12686        }
12687
12688        PermissionsState permissionsState = su.getPermissionsState();
12689        // Prune install permissions
12690        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12691        final int installPermCount = installPermStates.size();
12692        for (int i = installPermCount - 1; i >= 0;  i--) {
12693            PermissionState permissionState = installPermStates.get(i);
12694            if (!usedPermissions.contains(permissionState.getName())) {
12695                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12696                if (bp != null) {
12697                    permissionsState.revokeInstallPermission(bp);
12698                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12699                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12700                }
12701            }
12702        }
12703
12704        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12705
12706        // Prune runtime permissions
12707        for (int userId : allUserIds) {
12708            List<PermissionState> runtimePermStates = permissionsState
12709                    .getRuntimePermissionStates(userId);
12710            final int runtimePermCount = runtimePermStates.size();
12711            for (int i = runtimePermCount - 1; i >= 0; i--) {
12712                PermissionState permissionState = runtimePermStates.get(i);
12713                if (!usedPermissions.contains(permissionState.getName())) {
12714                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12715                    if (bp != null) {
12716                        permissionsState.revokeRuntimePermission(bp, userId);
12717                        permissionsState.updatePermissionFlags(bp, userId,
12718                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12719                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12720                                runtimePermissionChangedUserIds, userId);
12721                    }
12722                }
12723            }
12724        }
12725
12726        return runtimePermissionChangedUserIds;
12727    }
12728
12729    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12730            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12731            UserHandle user) {
12732        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12733
12734        String pkgName = newPackage.packageName;
12735        synchronized (mPackages) {
12736            //write settings. the installStatus will be incomplete at this stage.
12737            //note that the new package setting would have already been
12738            //added to mPackages. It hasn't been persisted yet.
12739            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12740            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12741            mSettings.writeLPr();
12742            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12743        }
12744
12745        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12746        synchronized (mPackages) {
12747            updatePermissionsLPw(newPackage.packageName, newPackage,
12748                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12749                            ? UPDATE_PERMISSIONS_ALL : 0));
12750            // For system-bundled packages, we assume that installing an upgraded version
12751            // of the package implies that the user actually wants to run that new code,
12752            // so we enable the package.
12753            PackageSetting ps = mSettings.mPackages.get(pkgName);
12754            if (ps != null) {
12755                if (isSystemApp(newPackage)) {
12756                    // NB: implicit assumption that system package upgrades apply to all users
12757                    if (DEBUG_INSTALL) {
12758                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12759                    }
12760                    if (res.origUsers != null) {
12761                        for (int userHandle : res.origUsers) {
12762                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12763                                    userHandle, installerPackageName);
12764                        }
12765                    }
12766                    // Also convey the prior install/uninstall state
12767                    if (allUsers != null && perUserInstalled != null) {
12768                        for (int i = 0; i < allUsers.length; i++) {
12769                            if (DEBUG_INSTALL) {
12770                                Slog.d(TAG, "    user " + allUsers[i]
12771                                        + " => " + perUserInstalled[i]);
12772                            }
12773                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12774                        }
12775                        // these install state changes will be persisted in the
12776                        // upcoming call to mSettings.writeLPr().
12777                    }
12778                }
12779                // It's implied that when a user requests installation, they want the app to be
12780                // installed and enabled.
12781                int userId = user.getIdentifier();
12782                if (userId != UserHandle.USER_ALL) {
12783                    ps.setInstalled(true, userId);
12784                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12785                }
12786            }
12787            res.name = pkgName;
12788            res.uid = newPackage.applicationInfo.uid;
12789            res.pkg = newPackage;
12790            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12791            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12792            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12793            //to update install status
12794            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12795            mSettings.writeLPr();
12796            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12797        }
12798
12799        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12800    }
12801
12802    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12803        try {
12804            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12805            installPackageLI(args, res);
12806        } finally {
12807            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12808        }
12809    }
12810
12811    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12812        final int installFlags = args.installFlags;
12813        final String installerPackageName = args.installerPackageName;
12814        final String volumeUuid = args.volumeUuid;
12815        final File tmpPackageFile = new File(args.getCodePath());
12816        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12817        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12818                || (args.volumeUuid != null));
12819        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12820        boolean replace = false;
12821        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12822        if (args.move != null) {
12823            // moving a complete application; perfom an initial scan on the new install location
12824            scanFlags |= SCAN_INITIAL;
12825        }
12826        // Result object to be returned
12827        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12828
12829        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12830
12831        // Sanity check
12832        if (ephemeral && (forwardLocked || onExternal)) {
12833            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12834                    + " external=" + onExternal);
12835            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12836            return;
12837        }
12838
12839        // Retrieve PackageSettings and parse package
12840        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12841                | PackageParser.PARSE_ENFORCE_CODE
12842                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12843                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12844                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12845        PackageParser pp = new PackageParser();
12846        pp.setSeparateProcesses(mSeparateProcesses);
12847        pp.setDisplayMetrics(mMetrics);
12848
12849        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12850        final PackageParser.Package pkg;
12851        try {
12852            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12853        } catch (PackageParserException e) {
12854            res.setError("Failed parse during installPackageLI", e);
12855            return;
12856        } finally {
12857            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12858        }
12859
12860        // Mark that we have an install time CPU ABI override.
12861        pkg.cpuAbiOverride = args.abiOverride;
12862
12863        String pkgName = res.name = pkg.packageName;
12864        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12865            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12866                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12867                return;
12868            }
12869        }
12870
12871        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12872        try {
12873            pp.collectCertificates(pkg, parseFlags);
12874        } catch (PackageParserException e) {
12875            res.setError("Failed collect during installPackageLI", e);
12876            return;
12877        } finally {
12878            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12879        }
12880
12881        /* If the installer passed in a manifest digest, compare it now. */
12882        if (args.manifestDigest != null) {
12883            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12884            try {
12885                pp.collectManifestDigest(pkg);
12886            } catch (PackageParserException e) {
12887                res.setError("Failed collect during installPackageLI", e);
12888                return;
12889            } finally {
12890                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12891            }
12892
12893            if (DEBUG_INSTALL) {
12894                final String parsedManifest = pkg.manifestDigest == null ? "null"
12895                        : pkg.manifestDigest.toString();
12896                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12897                        + parsedManifest);
12898            }
12899
12900            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12901                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12902                return;
12903            }
12904        } else if (DEBUG_INSTALL) {
12905            final String parsedManifest = pkg.manifestDigest == null
12906                    ? "null" : pkg.manifestDigest.toString();
12907            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12908        }
12909
12910        // Get rid of all references to package scan path via parser.
12911        pp = null;
12912        String oldCodePath = null;
12913        boolean systemApp = false;
12914        synchronized (mPackages) {
12915            // Check if installing already existing package
12916            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12917                String oldName = mSettings.mRenamedPackages.get(pkgName);
12918                if (pkg.mOriginalPackages != null
12919                        && pkg.mOriginalPackages.contains(oldName)
12920                        && mPackages.containsKey(oldName)) {
12921                    // This package is derived from an original package,
12922                    // and this device has been updating from that original
12923                    // name.  We must continue using the original name, so
12924                    // rename the new package here.
12925                    pkg.setPackageName(oldName);
12926                    pkgName = pkg.packageName;
12927                    replace = true;
12928                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12929                            + oldName + " pkgName=" + pkgName);
12930                } else if (mPackages.containsKey(pkgName)) {
12931                    // This package, under its official name, already exists
12932                    // on the device; we should replace it.
12933                    replace = true;
12934                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12935                }
12936
12937                // Prevent apps opting out from runtime permissions
12938                if (replace) {
12939                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12940                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12941                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12942                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12943                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12944                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12945                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12946                                        + " doesn't support runtime permissions but the old"
12947                                        + " target SDK " + oldTargetSdk + " does.");
12948                        return;
12949                    }
12950                }
12951            }
12952
12953            PackageSetting ps = mSettings.mPackages.get(pkgName);
12954            if (ps != null) {
12955                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12956
12957                // Quick sanity check that we're signed correctly if updating;
12958                // we'll check this again later when scanning, but we want to
12959                // bail early here before tripping over redefined permissions.
12960                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12961                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12962                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12963                                + pkg.packageName + " upgrade keys do not match the "
12964                                + "previously installed version");
12965                        return;
12966                    }
12967                } else {
12968                    try {
12969                        verifySignaturesLP(ps, pkg);
12970                    } catch (PackageManagerException e) {
12971                        res.setError(e.error, e.getMessage());
12972                        return;
12973                    }
12974                }
12975
12976                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12977                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12978                    systemApp = (ps.pkg.applicationInfo.flags &
12979                            ApplicationInfo.FLAG_SYSTEM) != 0;
12980                }
12981                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12982            }
12983
12984            // Check whether the newly-scanned package wants to define an already-defined perm
12985            int N = pkg.permissions.size();
12986            for (int i = N-1; i >= 0; i--) {
12987                PackageParser.Permission perm = pkg.permissions.get(i);
12988                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12989                if (bp != null) {
12990                    // If the defining package is signed with our cert, it's okay.  This
12991                    // also includes the "updating the same package" case, of course.
12992                    // "updating same package" could also involve key-rotation.
12993                    final boolean sigsOk;
12994                    if (bp.sourcePackage.equals(pkg.packageName)
12995                            && (bp.packageSetting instanceof PackageSetting)
12996                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12997                                    scanFlags))) {
12998                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12999                    } else {
13000                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13001                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13002                    }
13003                    if (!sigsOk) {
13004                        // If the owning package is the system itself, we log but allow
13005                        // install to proceed; we fail the install on all other permission
13006                        // redefinitions.
13007                        if (!bp.sourcePackage.equals("android")) {
13008                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13009                                    + pkg.packageName + " attempting to redeclare permission "
13010                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13011                            res.origPermission = perm.info.name;
13012                            res.origPackage = bp.sourcePackage;
13013                            return;
13014                        } else {
13015                            Slog.w(TAG, "Package " + pkg.packageName
13016                                    + " attempting to redeclare system permission "
13017                                    + perm.info.name + "; ignoring new declaration");
13018                            pkg.permissions.remove(i);
13019                        }
13020                    }
13021                }
13022            }
13023
13024        }
13025
13026        if (systemApp) {
13027            if (onExternal) {
13028                // Abort update; system app can't be replaced with app on sdcard
13029                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13030                        "Cannot install updates to system apps on sdcard");
13031                return;
13032            } else if (ephemeral) {
13033                // Abort update; system app can't be replaced with an ephemeral app
13034                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13035                        "Cannot update a system app with an ephemeral app");
13036                return;
13037            }
13038        }
13039
13040        if (args.move != null) {
13041            // We did an in-place move, so dex is ready to roll
13042            scanFlags |= SCAN_NO_DEX;
13043            scanFlags |= SCAN_MOVE;
13044
13045            synchronized (mPackages) {
13046                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13047                if (ps == null) {
13048                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13049                            "Missing settings for moved package " + pkgName);
13050                }
13051
13052                // We moved the entire application as-is, so bring over the
13053                // previously derived ABI information.
13054                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13055                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13056            }
13057
13058        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13059            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13060            scanFlags |= SCAN_NO_DEX;
13061
13062            try {
13063                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13064                        true /* extract libs */);
13065            } catch (PackageManagerException pme) {
13066                Slog.e(TAG, "Error deriving application ABI", pme);
13067                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13068                return;
13069            }
13070        }
13071
13072        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13073            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13074            return;
13075        }
13076
13077        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13078
13079        if (replace) {
13080            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13081                    installerPackageName, volumeUuid, res);
13082        } else {
13083            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13084                    args.user, installerPackageName, volumeUuid, res);
13085        }
13086        synchronized (mPackages) {
13087            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13088            if (ps != null) {
13089                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13090            }
13091        }
13092    }
13093
13094    private void startIntentFilterVerifications(int userId, boolean replacing,
13095            PackageParser.Package pkg) {
13096        if (mIntentFilterVerifierComponent == null) {
13097            Slog.w(TAG, "No IntentFilter verification will not be done as "
13098                    + "there is no IntentFilterVerifier available!");
13099            return;
13100        }
13101
13102        final int verifierUid = getPackageUid(
13103                mIntentFilterVerifierComponent.getPackageName(),
13104                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13105
13106        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13107        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13108        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13109        mHandler.sendMessage(msg);
13110    }
13111
13112    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13113            PackageParser.Package pkg) {
13114        int size = pkg.activities.size();
13115        if (size == 0) {
13116            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13117                    "No activity, so no need to verify any IntentFilter!");
13118            return;
13119        }
13120
13121        final boolean hasDomainURLs = hasDomainURLs(pkg);
13122        if (!hasDomainURLs) {
13123            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13124                    "No domain URLs, so no need to verify any IntentFilter!");
13125            return;
13126        }
13127
13128        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13129                + " if any IntentFilter from the " + size
13130                + " Activities needs verification ...");
13131
13132        int count = 0;
13133        final String packageName = pkg.packageName;
13134
13135        synchronized (mPackages) {
13136            // If this is a new install and we see that we've already run verification for this
13137            // package, we have nothing to do: it means the state was restored from backup.
13138            if (!replacing) {
13139                IntentFilterVerificationInfo ivi =
13140                        mSettings.getIntentFilterVerificationLPr(packageName);
13141                if (ivi != null) {
13142                    if (DEBUG_DOMAIN_VERIFICATION) {
13143                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13144                                + ivi.getStatusString());
13145                    }
13146                    return;
13147                }
13148            }
13149
13150            // If any filters need to be verified, then all need to be.
13151            boolean needToVerify = false;
13152            for (PackageParser.Activity a : pkg.activities) {
13153                for (ActivityIntentInfo filter : a.intents) {
13154                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13155                        if (DEBUG_DOMAIN_VERIFICATION) {
13156                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13157                        }
13158                        needToVerify = true;
13159                        break;
13160                    }
13161                }
13162            }
13163
13164            if (needToVerify) {
13165                final int verificationId = mIntentFilterVerificationToken++;
13166                for (PackageParser.Activity a : pkg.activities) {
13167                    for (ActivityIntentInfo filter : a.intents) {
13168                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13169                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13170                                    "Verification needed for IntentFilter:" + filter.toString());
13171                            mIntentFilterVerifier.addOneIntentFilterVerification(
13172                                    verifierUid, userId, verificationId, filter, packageName);
13173                            count++;
13174                        }
13175                    }
13176                }
13177            }
13178        }
13179
13180        if (count > 0) {
13181            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13182                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13183                    +  " for userId:" + userId);
13184            mIntentFilterVerifier.startVerifications(userId);
13185        } else {
13186            if (DEBUG_DOMAIN_VERIFICATION) {
13187                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13188            }
13189        }
13190    }
13191
13192    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13193        final ComponentName cn  = filter.activity.getComponentName();
13194        final String packageName = cn.getPackageName();
13195
13196        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13197                packageName);
13198        if (ivi == null) {
13199            return true;
13200        }
13201        int status = ivi.getStatus();
13202        switch (status) {
13203            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13204            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13205                return true;
13206
13207            default:
13208                // Nothing to do
13209                return false;
13210        }
13211    }
13212
13213    private static boolean isMultiArch(ApplicationInfo info) {
13214        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13215    }
13216
13217    private static boolean isExternal(PackageParser.Package pkg) {
13218        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13219    }
13220
13221    private static boolean isExternal(PackageSetting ps) {
13222        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13223    }
13224
13225    private static boolean isEphemeral(PackageParser.Package pkg) {
13226        return pkg.applicationInfo.isEphemeralApp();
13227    }
13228
13229    private static boolean isEphemeral(PackageSetting ps) {
13230        return ps.pkg != null && isEphemeral(ps.pkg);
13231    }
13232
13233    private static boolean isSystemApp(PackageParser.Package pkg) {
13234        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13235    }
13236
13237    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13238        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13239    }
13240
13241    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13242        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13243    }
13244
13245    private static boolean isSystemApp(PackageSetting ps) {
13246        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13247    }
13248
13249    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13250        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13251    }
13252
13253    private int packageFlagsToInstallFlags(PackageSetting ps) {
13254        int installFlags = 0;
13255        if (isEphemeral(ps)) {
13256            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13257        }
13258        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13259            // This existing package was an external ASEC install when we have
13260            // the external flag without a UUID
13261            installFlags |= PackageManager.INSTALL_EXTERNAL;
13262        }
13263        if (ps.isForwardLocked()) {
13264            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13265        }
13266        return installFlags;
13267    }
13268
13269    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13270        if (isExternal(pkg)) {
13271            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13272                return StorageManager.UUID_PRIMARY_PHYSICAL;
13273            } else {
13274                return pkg.volumeUuid;
13275            }
13276        } else {
13277            return StorageManager.UUID_PRIVATE_INTERNAL;
13278        }
13279    }
13280
13281    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13282        if (isExternal(pkg)) {
13283            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13284                return mSettings.getExternalVersion();
13285            } else {
13286                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13287            }
13288        } else {
13289            return mSettings.getInternalVersion();
13290        }
13291    }
13292
13293    private void deleteTempPackageFiles() {
13294        final FilenameFilter filter = new FilenameFilter() {
13295            public boolean accept(File dir, String name) {
13296                return name.startsWith("vmdl") && name.endsWith(".tmp");
13297            }
13298        };
13299        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13300            file.delete();
13301        }
13302    }
13303
13304    @Override
13305    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13306            int flags) {
13307        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13308                flags);
13309    }
13310
13311    @Override
13312    public void deletePackage(final String packageName,
13313            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13314        mContext.enforceCallingOrSelfPermission(
13315                android.Manifest.permission.DELETE_PACKAGES, null);
13316        Preconditions.checkNotNull(packageName);
13317        Preconditions.checkNotNull(observer);
13318        final int uid = Binder.getCallingUid();
13319        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13320        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13321        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13322            mContext.enforceCallingOrSelfPermission(
13323                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13324                    "deletePackage for user " + userId);
13325        }
13326
13327        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13328            try {
13329                observer.onPackageDeleted(packageName,
13330                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13331            } catch (RemoteException re) {
13332            }
13333            return;
13334        }
13335
13336        for (int currentUserId : users) {
13337            if (getBlockUninstallForUser(packageName, currentUserId)) {
13338                try {
13339                    observer.onPackageDeleted(packageName,
13340                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13341                } catch (RemoteException re) {
13342                }
13343                return;
13344            }
13345        }
13346
13347        if (DEBUG_REMOVE) {
13348            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13349        }
13350        // Queue up an async operation since the package deletion may take a little while.
13351        mHandler.post(new Runnable() {
13352            public void run() {
13353                mHandler.removeCallbacks(this);
13354                final int returnCode = deletePackageX(packageName, userId, flags);
13355                try {
13356                    observer.onPackageDeleted(packageName, returnCode, null);
13357                } catch (RemoteException e) {
13358                    Log.i(TAG, "Observer no longer exists.");
13359                } //end catch
13360            } //end run
13361        });
13362    }
13363
13364    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13365        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13366                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13367        try {
13368            if (dpm != null) {
13369                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13370                        /* callingUserOnly =*/ false);
13371                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13372                        : deviceOwnerComponentName.getPackageName();
13373                // Does the package contains the device owner?
13374                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13375                // this check is probably not needed, since DO should be registered as a device
13376                // admin on some user too. (Original bug for this: b/17657954)
13377                if (packageName.equals(deviceOwnerPackageName)) {
13378                    return true;
13379                }
13380                // Does it contain a device admin for any user?
13381                int[] users;
13382                if (userId == UserHandle.USER_ALL) {
13383                    users = sUserManager.getUserIds();
13384                } else {
13385                    users = new int[]{userId};
13386                }
13387                for (int i = 0; i < users.length; ++i) {
13388                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13389                        return true;
13390                    }
13391                }
13392            }
13393        } catch (RemoteException e) {
13394        }
13395        return false;
13396    }
13397
13398    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13399        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13400    }
13401
13402    /**
13403     *  This method is an internal method that could be get invoked either
13404     *  to delete an installed package or to clean up a failed installation.
13405     *  After deleting an installed package, a broadcast is sent to notify any
13406     *  listeners that the package has been installed. For cleaning up a failed
13407     *  installation, the broadcast is not necessary since the package's
13408     *  installation wouldn't have sent the initial broadcast either
13409     *  The key steps in deleting a package are
13410     *  deleting the package information in internal structures like mPackages,
13411     *  deleting the packages base directories through installd
13412     *  updating mSettings to reflect current status
13413     *  persisting settings for later use
13414     *  sending a broadcast if necessary
13415     */
13416    private int deletePackageX(String packageName, int userId, int flags) {
13417        final PackageRemovedInfo info = new PackageRemovedInfo();
13418        final boolean res;
13419
13420        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13421                ? UserHandle.ALL : new UserHandle(userId);
13422
13423        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13424            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13425            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13426        }
13427
13428        boolean removedForAllUsers = false;
13429        boolean systemUpdate = false;
13430
13431        PackageParser.Package uninstalledPkg;
13432
13433        // for the uninstall-updates case and restricted profiles, remember the per-
13434        // userhandle installed state
13435        int[] allUsers;
13436        boolean[] perUserInstalled;
13437        synchronized (mPackages) {
13438            uninstalledPkg = mPackages.get(packageName);
13439            PackageSetting ps = mSettings.mPackages.get(packageName);
13440            allUsers = sUserManager.getUserIds();
13441            perUserInstalled = new boolean[allUsers.length];
13442            for (int i = 0; i < allUsers.length; i++) {
13443                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13444            }
13445        }
13446
13447        synchronized (mInstallLock) {
13448            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13449            res = deletePackageLI(packageName, removeForUser,
13450                    true, allUsers, perUserInstalled,
13451                    flags | REMOVE_CHATTY, info, true);
13452            systemUpdate = info.isRemovedPackageSystemUpdate;
13453            synchronized (mPackages) {
13454                if (res) {
13455                    if (!systemUpdate && mPackages.get(packageName) == null) {
13456                        removedForAllUsers = true;
13457                    }
13458                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13459                }
13460            }
13461            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13462                    + " removedForAllUsers=" + removedForAllUsers);
13463        }
13464
13465        if (res) {
13466            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13467
13468            // If the removed package was a system update, the old system package
13469            // was re-enabled; we need to broadcast this information
13470            if (systemUpdate) {
13471                Bundle extras = new Bundle(1);
13472                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13473                        ? info.removedAppId : info.uid);
13474                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13475
13476                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13477                        extras, 0, null, null, null);
13478                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13479                        extras, 0, null, null, null);
13480                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13481                        null, 0, packageName, null, null);
13482            }
13483        }
13484        // Force a gc here.
13485        Runtime.getRuntime().gc();
13486        // Delete the resources here after sending the broadcast to let
13487        // other processes clean up before deleting resources.
13488        if (info.args != null) {
13489            synchronized (mInstallLock) {
13490                info.args.doPostDeleteLI(true);
13491            }
13492        }
13493
13494        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13495    }
13496
13497    class PackageRemovedInfo {
13498        String removedPackage;
13499        int uid = -1;
13500        int removedAppId = -1;
13501        int[] removedUsers = null;
13502        boolean isRemovedPackageSystemUpdate = false;
13503        // Clean up resources deleted packages.
13504        InstallArgs args = null;
13505
13506        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13507            Bundle extras = new Bundle(1);
13508            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13509            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13510            if (replacing) {
13511                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13512            }
13513            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13514            if (removedPackage != null) {
13515                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13516                        extras, 0, null, null, removedUsers);
13517                if (fullRemove && !replacing) {
13518                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13519                            extras, 0, null, null, removedUsers);
13520                }
13521            }
13522            if (removedAppId >= 0) {
13523                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13524                        removedUsers);
13525            }
13526        }
13527    }
13528
13529    /*
13530     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13531     * flag is not set, the data directory is removed as well.
13532     * make sure this flag is set for partially installed apps. If not its meaningless to
13533     * delete a partially installed application.
13534     */
13535    private void removePackageDataLI(PackageSetting ps,
13536            int[] allUserHandles, boolean[] perUserInstalled,
13537            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13538        String packageName = ps.name;
13539        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13540        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13541        // Retrieve object to delete permissions for shared user later on
13542        final PackageSetting deletedPs;
13543        // reader
13544        synchronized (mPackages) {
13545            deletedPs = mSettings.mPackages.get(packageName);
13546            if (outInfo != null) {
13547                outInfo.removedPackage = packageName;
13548                outInfo.removedUsers = deletedPs != null
13549                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13550                        : null;
13551            }
13552        }
13553        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13554            removeDataDirsLI(ps.volumeUuid, packageName);
13555            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13556        }
13557        // writer
13558        synchronized (mPackages) {
13559            if (deletedPs != null) {
13560                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13561                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13562                    clearDefaultBrowserIfNeeded(packageName);
13563                    if (outInfo != null) {
13564                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13565                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13566                    }
13567                    updatePermissionsLPw(deletedPs.name, null, 0);
13568                    if (deletedPs.sharedUser != null) {
13569                        // Remove permissions associated with package. Since runtime
13570                        // permissions are per user we have to kill the removed package
13571                        // or packages running under the shared user of the removed
13572                        // package if revoking the permissions requested only by the removed
13573                        // package is successful and this causes a change in gids.
13574                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13575                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13576                                    userId);
13577                            if (userIdToKill == UserHandle.USER_ALL
13578                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13579                                // If gids changed for this user, kill all affected packages.
13580                                mHandler.post(new Runnable() {
13581                                    @Override
13582                                    public void run() {
13583                                        // This has to happen with no lock held.
13584                                        killApplication(deletedPs.name, deletedPs.appId,
13585                                                KILL_APP_REASON_GIDS_CHANGED);
13586                                    }
13587                                });
13588                                break;
13589                            }
13590                        }
13591                    }
13592                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13593                }
13594                // make sure to preserve per-user disabled state if this removal was just
13595                // a downgrade of a system app to the factory package
13596                if (allUserHandles != null && perUserInstalled != null) {
13597                    if (DEBUG_REMOVE) {
13598                        Slog.d(TAG, "Propagating install state across downgrade");
13599                    }
13600                    for (int i = 0; i < allUserHandles.length; i++) {
13601                        if (DEBUG_REMOVE) {
13602                            Slog.d(TAG, "    user " + allUserHandles[i]
13603                                    + " => " + perUserInstalled[i]);
13604                        }
13605                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13606                    }
13607                }
13608            }
13609            // can downgrade to reader
13610            if (writeSettings) {
13611                // Save settings now
13612                mSettings.writeLPr();
13613            }
13614        }
13615        if (outInfo != null) {
13616            // A user ID was deleted here. Go through all users and remove it
13617            // from KeyStore.
13618            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13619        }
13620    }
13621
13622    static boolean locationIsPrivileged(File path) {
13623        try {
13624            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13625                    .getCanonicalPath();
13626            return path.getCanonicalPath().startsWith(privilegedAppDir);
13627        } catch (IOException e) {
13628            Slog.e(TAG, "Unable to access code path " + path);
13629        }
13630        return false;
13631    }
13632
13633    /*
13634     * Tries to delete system package.
13635     */
13636    private boolean deleteSystemPackageLI(PackageSetting newPs,
13637            int[] allUserHandles, boolean[] perUserInstalled,
13638            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13639        final boolean applyUserRestrictions
13640                = (allUserHandles != null) && (perUserInstalled != null);
13641        PackageSetting disabledPs = null;
13642        // Confirm if the system package has been updated
13643        // An updated system app can be deleted. This will also have to restore
13644        // the system pkg from system partition
13645        // reader
13646        synchronized (mPackages) {
13647            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13648        }
13649        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13650                + " disabledPs=" + disabledPs);
13651        if (disabledPs == null) {
13652            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13653            return false;
13654        } else if (DEBUG_REMOVE) {
13655            Slog.d(TAG, "Deleting system pkg from data partition");
13656        }
13657        if (DEBUG_REMOVE) {
13658            if (applyUserRestrictions) {
13659                Slog.d(TAG, "Remembering install states:");
13660                for (int i = 0; i < allUserHandles.length; i++) {
13661                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13662                }
13663            }
13664        }
13665        // Delete the updated package
13666        outInfo.isRemovedPackageSystemUpdate = true;
13667        if (disabledPs.versionCode < newPs.versionCode) {
13668            // Delete data for downgrades
13669            flags &= ~PackageManager.DELETE_KEEP_DATA;
13670        } else {
13671            // Preserve data by setting flag
13672            flags |= PackageManager.DELETE_KEEP_DATA;
13673        }
13674        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13675                allUserHandles, perUserInstalled, outInfo, writeSettings);
13676        if (!ret) {
13677            return false;
13678        }
13679        // writer
13680        synchronized (mPackages) {
13681            // Reinstate the old system package
13682            mSettings.enableSystemPackageLPw(newPs.name);
13683            // Remove any native libraries from the upgraded package.
13684            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13685        }
13686        // Install the system package
13687        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13688        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13689        if (locationIsPrivileged(disabledPs.codePath)) {
13690            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13691        }
13692
13693        final PackageParser.Package newPkg;
13694        try {
13695            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13696        } catch (PackageManagerException e) {
13697            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13698            return false;
13699        }
13700
13701        // writer
13702        synchronized (mPackages) {
13703            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13704
13705            // Propagate the permissions state as we do not want to drop on the floor
13706            // runtime permissions. The update permissions method below will take
13707            // care of removing obsolete permissions and grant install permissions.
13708            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13709            updatePermissionsLPw(newPkg.packageName, newPkg,
13710                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13711
13712            if (applyUserRestrictions) {
13713                if (DEBUG_REMOVE) {
13714                    Slog.d(TAG, "Propagating install state across reinstall");
13715                }
13716                for (int i = 0; i < allUserHandles.length; i++) {
13717                    if (DEBUG_REMOVE) {
13718                        Slog.d(TAG, "    user " + allUserHandles[i]
13719                                + " => " + perUserInstalled[i]);
13720                    }
13721                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13722
13723                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13724                }
13725                // Regardless of writeSettings we need to ensure that this restriction
13726                // state propagation is persisted
13727                mSettings.writeAllUsersPackageRestrictionsLPr();
13728            }
13729            // can downgrade to reader here
13730            if (writeSettings) {
13731                mSettings.writeLPr();
13732            }
13733        }
13734        return true;
13735    }
13736
13737    private boolean deleteInstalledPackageLI(PackageSetting ps,
13738            boolean deleteCodeAndResources, int flags,
13739            int[] allUserHandles, boolean[] perUserInstalled,
13740            PackageRemovedInfo outInfo, boolean writeSettings) {
13741        if (outInfo != null) {
13742            outInfo.uid = ps.appId;
13743        }
13744
13745        // Delete package data from internal structures and also remove data if flag is set
13746        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13747
13748        // Delete application code and resources
13749        if (deleteCodeAndResources && (outInfo != null)) {
13750            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13751                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13752            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13753        }
13754        return true;
13755    }
13756
13757    @Override
13758    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13759            int userId) {
13760        mContext.enforceCallingOrSelfPermission(
13761                android.Manifest.permission.DELETE_PACKAGES, null);
13762        synchronized (mPackages) {
13763            PackageSetting ps = mSettings.mPackages.get(packageName);
13764            if (ps == null) {
13765                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13766                return false;
13767            }
13768            if (!ps.getInstalled(userId)) {
13769                // Can't block uninstall for an app that is not installed or enabled.
13770                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13771                return false;
13772            }
13773            ps.setBlockUninstall(blockUninstall, userId);
13774            mSettings.writePackageRestrictionsLPr(userId);
13775        }
13776        return true;
13777    }
13778
13779    @Override
13780    public boolean getBlockUninstallForUser(String packageName, int userId) {
13781        synchronized (mPackages) {
13782            PackageSetting ps = mSettings.mPackages.get(packageName);
13783            if (ps == null) {
13784                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13785                return false;
13786            }
13787            return ps.getBlockUninstall(userId);
13788        }
13789    }
13790
13791    @Override
13792    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13793        int callingUid = Binder.getCallingUid();
13794        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13795            throw new SecurityException(
13796                    "setRequiredForSystemUser can only be run by the system or root");
13797        }
13798        synchronized (mPackages) {
13799            PackageSetting ps = mSettings.mPackages.get(packageName);
13800            if (ps == null) {
13801                Log.w(TAG, "Package doesn't exist: " + packageName);
13802                return false;
13803            }
13804            if (systemUserApp) {
13805                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13806            } else {
13807                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13808            }
13809            mSettings.writeLPr();
13810        }
13811        return true;
13812    }
13813
13814    /*
13815     * This method handles package deletion in general
13816     */
13817    private boolean deletePackageLI(String packageName, UserHandle user,
13818            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13819            int flags, PackageRemovedInfo outInfo,
13820            boolean writeSettings) {
13821        if (packageName == null) {
13822            Slog.w(TAG, "Attempt to delete null packageName.");
13823            return false;
13824        }
13825        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13826        PackageSetting ps;
13827        boolean dataOnly = false;
13828        int removeUser = -1;
13829        int appId = -1;
13830        synchronized (mPackages) {
13831            ps = mSettings.mPackages.get(packageName);
13832            if (ps == null) {
13833                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13834                return false;
13835            }
13836            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13837                    && user.getIdentifier() != UserHandle.USER_ALL) {
13838                // The caller is asking that the package only be deleted for a single
13839                // user.  To do this, we just mark its uninstalled state and delete
13840                // its data.  If this is a system app, we only allow this to happen if
13841                // they have set the special DELETE_SYSTEM_APP which requests different
13842                // semantics than normal for uninstalling system apps.
13843                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13844                final int userId = user.getIdentifier();
13845                ps.setUserState(userId,
13846                        COMPONENT_ENABLED_STATE_DEFAULT,
13847                        false, //installed
13848                        true,  //stopped
13849                        true,  //notLaunched
13850                        false, //hidden
13851                        false, //suspended
13852                        null, null, null,
13853                        false, // blockUninstall
13854                        ps.readUserState(userId).domainVerificationStatus, 0);
13855                if (!isSystemApp(ps)) {
13856                    // Do not uninstall the APK if an app should be cached
13857                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13858                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13859                        // Other user still have this package installed, so all
13860                        // we need to do is clear this user's data and save that
13861                        // it is uninstalled.
13862                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13863                        removeUser = user.getIdentifier();
13864                        appId = ps.appId;
13865                        scheduleWritePackageRestrictionsLocked(removeUser);
13866                    } else {
13867                        // We need to set it back to 'installed' so the uninstall
13868                        // broadcasts will be sent correctly.
13869                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13870                        ps.setInstalled(true, user.getIdentifier());
13871                    }
13872                } else {
13873                    // This is a system app, so we assume that the
13874                    // other users still have this package installed, so all
13875                    // we need to do is clear this user's data and save that
13876                    // it is uninstalled.
13877                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13878                    removeUser = user.getIdentifier();
13879                    appId = ps.appId;
13880                    scheduleWritePackageRestrictionsLocked(removeUser);
13881                }
13882            }
13883        }
13884
13885        if (removeUser >= 0) {
13886            // From above, we determined that we are deleting this only
13887            // for a single user.  Continue the work here.
13888            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13889            if (outInfo != null) {
13890                outInfo.removedPackage = packageName;
13891                outInfo.removedAppId = appId;
13892                outInfo.removedUsers = new int[] {removeUser};
13893            }
13894            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13895            removeKeystoreDataIfNeeded(removeUser, appId);
13896            schedulePackageCleaning(packageName, removeUser, false);
13897            synchronized (mPackages) {
13898                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13899                    scheduleWritePackageRestrictionsLocked(removeUser);
13900                }
13901                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13902            }
13903            return true;
13904        }
13905
13906        if (dataOnly) {
13907            // Delete application data first
13908            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13909            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13910            return true;
13911        }
13912
13913        boolean ret = false;
13914        if (isSystemApp(ps)) {
13915            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13916            // When an updated system application is deleted we delete the existing resources as well and
13917            // fall back to existing code in system partition
13918            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13919                    flags, outInfo, writeSettings);
13920        } else {
13921            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13922            // Kill application pre-emptively especially for apps on sd.
13923            killApplication(packageName, ps.appId, "uninstall pkg");
13924            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13925                    allUserHandles, perUserInstalled,
13926                    outInfo, writeSettings);
13927        }
13928
13929        return ret;
13930    }
13931
13932    private final static class ClearStorageConnection implements ServiceConnection {
13933        IMediaContainerService mContainerService;
13934
13935        @Override
13936        public void onServiceConnected(ComponentName name, IBinder service) {
13937            synchronized (this) {
13938                mContainerService = IMediaContainerService.Stub.asInterface(service);
13939                notifyAll();
13940            }
13941        }
13942
13943        @Override
13944        public void onServiceDisconnected(ComponentName name) {
13945        }
13946    }
13947
13948    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13949        final boolean mounted;
13950        if (Environment.isExternalStorageEmulated()) {
13951            mounted = true;
13952        } else {
13953            final String status = Environment.getExternalStorageState();
13954
13955            mounted = status.equals(Environment.MEDIA_MOUNTED)
13956                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13957        }
13958
13959        if (!mounted) {
13960            return;
13961        }
13962
13963        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13964        int[] users;
13965        if (userId == UserHandle.USER_ALL) {
13966            users = sUserManager.getUserIds();
13967        } else {
13968            users = new int[] { userId };
13969        }
13970        final ClearStorageConnection conn = new ClearStorageConnection();
13971        if (mContext.bindServiceAsUser(
13972                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13973            try {
13974                for (int curUser : users) {
13975                    long timeout = SystemClock.uptimeMillis() + 5000;
13976                    synchronized (conn) {
13977                        long now = SystemClock.uptimeMillis();
13978                        while (conn.mContainerService == null && now < timeout) {
13979                            try {
13980                                conn.wait(timeout - now);
13981                            } catch (InterruptedException e) {
13982                            }
13983                        }
13984                    }
13985                    if (conn.mContainerService == null) {
13986                        return;
13987                    }
13988
13989                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13990                    clearDirectory(conn.mContainerService,
13991                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13992                    if (allData) {
13993                        clearDirectory(conn.mContainerService,
13994                                userEnv.buildExternalStorageAppDataDirs(packageName));
13995                        clearDirectory(conn.mContainerService,
13996                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13997                    }
13998                }
13999            } finally {
14000                mContext.unbindService(conn);
14001            }
14002        }
14003    }
14004
14005    @Override
14006    public void clearApplicationUserData(final String packageName,
14007            final IPackageDataObserver observer, final int userId) {
14008        mContext.enforceCallingOrSelfPermission(
14009                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14010        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14011        // Queue up an async operation since the package deletion may take a little while.
14012        mHandler.post(new Runnable() {
14013            public void run() {
14014                mHandler.removeCallbacks(this);
14015                final boolean succeeded;
14016                synchronized (mInstallLock) {
14017                    succeeded = clearApplicationUserDataLI(packageName, userId);
14018                }
14019                clearExternalStorageDataSync(packageName, userId, true);
14020                if (succeeded) {
14021                    // invoke DeviceStorageMonitor's update method to clear any notifications
14022                    DeviceStorageMonitorInternal
14023                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14024                    if (dsm != null) {
14025                        dsm.checkMemory();
14026                    }
14027                }
14028                if(observer != null) {
14029                    try {
14030                        observer.onRemoveCompleted(packageName, succeeded);
14031                    } catch (RemoteException e) {
14032                        Log.i(TAG, "Observer no longer exists.");
14033                    }
14034                } //end if observer
14035            } //end run
14036        });
14037    }
14038
14039    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14040        if (packageName == null) {
14041            Slog.w(TAG, "Attempt to delete null packageName.");
14042            return false;
14043        }
14044
14045        // Try finding details about the requested package
14046        PackageParser.Package pkg;
14047        synchronized (mPackages) {
14048            pkg = mPackages.get(packageName);
14049            if (pkg == null) {
14050                final PackageSetting ps = mSettings.mPackages.get(packageName);
14051                if (ps != null) {
14052                    pkg = ps.pkg;
14053                }
14054            }
14055
14056            if (pkg == null) {
14057                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14058                return false;
14059            }
14060
14061            PackageSetting ps = (PackageSetting) pkg.mExtras;
14062            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14063        }
14064
14065        // Always delete data directories for package, even if we found no other
14066        // record of app. This helps users recover from UID mismatches without
14067        // resorting to a full data wipe.
14068        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14069        if (retCode < 0) {
14070            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
14071            return false;
14072        }
14073
14074        final int appId = pkg.applicationInfo.uid;
14075        removeKeystoreDataIfNeeded(userId, appId);
14076
14077        // Create a native library symlink only if we have native libraries
14078        // and if the native libraries are 32 bit libraries. We do not provide
14079        // this symlink for 64 bit libraries.
14080        if (pkg.applicationInfo.primaryCpuAbi != null &&
14081                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14082            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14083            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14084                    nativeLibPath, userId) < 0) {
14085                Slog.w(TAG, "Failed linking native library dir");
14086                return false;
14087            }
14088        }
14089
14090        return true;
14091    }
14092
14093    /**
14094     * Reverts user permission state changes (permissions and flags) in
14095     * all packages for a given user.
14096     *
14097     * @param userId The device user for which to do a reset.
14098     */
14099    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14100        final int packageCount = mPackages.size();
14101        for (int i = 0; i < packageCount; i++) {
14102            PackageParser.Package pkg = mPackages.valueAt(i);
14103            PackageSetting ps = (PackageSetting) pkg.mExtras;
14104            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14105        }
14106    }
14107
14108    /**
14109     * Reverts user permission state changes (permissions and flags).
14110     *
14111     * @param ps The package for which to reset.
14112     * @param userId The device user for which to do a reset.
14113     */
14114    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14115            final PackageSetting ps, final int userId) {
14116        if (ps.pkg == null) {
14117            return;
14118        }
14119
14120        // These are flags that can change base on user actions.
14121        final int userSettableMask = FLAG_PERMISSION_USER_SET
14122                | FLAG_PERMISSION_USER_FIXED
14123                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14124                | FLAG_PERMISSION_REVIEW_REQUIRED;
14125
14126        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14127                | FLAG_PERMISSION_POLICY_FIXED;
14128
14129        boolean writeInstallPermissions = false;
14130        boolean writeRuntimePermissions = false;
14131
14132        final int permissionCount = ps.pkg.requestedPermissions.size();
14133        for (int i = 0; i < permissionCount; i++) {
14134            String permission = ps.pkg.requestedPermissions.get(i);
14135
14136            BasePermission bp = mSettings.mPermissions.get(permission);
14137            if (bp == null) {
14138                continue;
14139            }
14140
14141            // If shared user we just reset the state to which only this app contributed.
14142            if (ps.sharedUser != null) {
14143                boolean used = false;
14144                final int packageCount = ps.sharedUser.packages.size();
14145                for (int j = 0; j < packageCount; j++) {
14146                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14147                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14148                            && pkg.pkg.requestedPermissions.contains(permission)) {
14149                        used = true;
14150                        break;
14151                    }
14152                }
14153                if (used) {
14154                    continue;
14155                }
14156            }
14157
14158            PermissionsState permissionsState = ps.getPermissionsState();
14159
14160            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14161
14162            // Always clear the user settable flags.
14163            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14164                    bp.name) != null;
14165            // If permission review is enabled and this is a legacy app, mark the
14166            // permission as requiring a review as this is the initial state.
14167            int flags = 0;
14168            if (Build.PERMISSIONS_REVIEW_REQUIRED
14169                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14170                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14171            }
14172            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14173                if (hasInstallState) {
14174                    writeInstallPermissions = true;
14175                } else {
14176                    writeRuntimePermissions = true;
14177                }
14178            }
14179
14180            // Below is only runtime permission handling.
14181            if (!bp.isRuntime()) {
14182                continue;
14183            }
14184
14185            // Never clobber system or policy.
14186            if ((oldFlags & policyOrSystemFlags) != 0) {
14187                continue;
14188            }
14189
14190            // If this permission was granted by default, make sure it is.
14191            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14192                if (permissionsState.grantRuntimePermission(bp, userId)
14193                        != PERMISSION_OPERATION_FAILURE) {
14194                    writeRuntimePermissions = true;
14195                }
14196            // If permission review is enabled the permissions for a legacy apps
14197            // are represented as constantly granted runtime ones, so don't revoke.
14198            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14199                // Otherwise, reset the permission.
14200                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14201                switch (revokeResult) {
14202                    case PERMISSION_OPERATION_SUCCESS: {
14203                        writeRuntimePermissions = true;
14204                    } break;
14205
14206                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14207                        writeRuntimePermissions = true;
14208                        final int appId = ps.appId;
14209                        mHandler.post(new Runnable() {
14210                            @Override
14211                            public void run() {
14212                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14213                            }
14214                        });
14215                    } break;
14216                }
14217            }
14218        }
14219
14220        // Synchronously write as we are taking permissions away.
14221        if (writeRuntimePermissions) {
14222            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14223        }
14224
14225        // Synchronously write as we are taking permissions away.
14226        if (writeInstallPermissions) {
14227            mSettings.writeLPr();
14228        }
14229    }
14230
14231    /**
14232     * Remove entries from the keystore daemon. Will only remove it if the
14233     * {@code appId} is valid.
14234     */
14235    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14236        if (appId < 0) {
14237            return;
14238        }
14239
14240        final KeyStore keyStore = KeyStore.getInstance();
14241        if (keyStore != null) {
14242            if (userId == UserHandle.USER_ALL) {
14243                for (final int individual : sUserManager.getUserIds()) {
14244                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14245                }
14246            } else {
14247                keyStore.clearUid(UserHandle.getUid(userId, appId));
14248            }
14249        } else {
14250            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14251        }
14252    }
14253
14254    @Override
14255    public void deleteApplicationCacheFiles(final String packageName,
14256            final IPackageDataObserver observer) {
14257        mContext.enforceCallingOrSelfPermission(
14258                android.Manifest.permission.DELETE_CACHE_FILES, null);
14259        // Queue up an async operation since the package deletion may take a little while.
14260        final int userId = UserHandle.getCallingUserId();
14261        mHandler.post(new Runnable() {
14262            public void run() {
14263                mHandler.removeCallbacks(this);
14264                final boolean succeded;
14265                synchronized (mInstallLock) {
14266                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14267                }
14268                clearExternalStorageDataSync(packageName, userId, false);
14269                if (observer != null) {
14270                    try {
14271                        observer.onRemoveCompleted(packageName, succeded);
14272                    } catch (RemoteException e) {
14273                        Log.i(TAG, "Observer no longer exists.");
14274                    }
14275                } //end if observer
14276            } //end run
14277        });
14278    }
14279
14280    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14281        if (packageName == null) {
14282            Slog.w(TAG, "Attempt to delete null packageName.");
14283            return false;
14284        }
14285        PackageParser.Package p;
14286        synchronized (mPackages) {
14287            p = mPackages.get(packageName);
14288        }
14289        if (p == null) {
14290            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14291            return false;
14292        }
14293        final ApplicationInfo applicationInfo = p.applicationInfo;
14294        if (applicationInfo == null) {
14295            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14296            return false;
14297        }
14298        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14299        if (retCode < 0) {
14300            Slog.w(TAG, "Couldn't remove cache files for package: "
14301                       + packageName + " u" + userId);
14302            return false;
14303        }
14304        return true;
14305    }
14306
14307    @Override
14308    public void getPackageSizeInfo(final String packageName, int userHandle,
14309            final IPackageStatsObserver observer) {
14310        mContext.enforceCallingOrSelfPermission(
14311                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14312        if (packageName == null) {
14313            throw new IllegalArgumentException("Attempt to get size of null packageName");
14314        }
14315
14316        PackageStats stats = new PackageStats(packageName, userHandle);
14317
14318        /*
14319         * Queue up an async operation since the package measurement may take a
14320         * little while.
14321         */
14322        Message msg = mHandler.obtainMessage(INIT_COPY);
14323        msg.obj = new MeasureParams(stats, observer);
14324        mHandler.sendMessage(msg);
14325    }
14326
14327    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14328            PackageStats pStats) {
14329        if (packageName == null) {
14330            Slog.w(TAG, "Attempt to get size of null packageName.");
14331            return false;
14332        }
14333        PackageParser.Package p;
14334        boolean dataOnly = false;
14335        String libDirRoot = null;
14336        String asecPath = null;
14337        PackageSetting ps = null;
14338        synchronized (mPackages) {
14339            p = mPackages.get(packageName);
14340            ps = mSettings.mPackages.get(packageName);
14341            if(p == null) {
14342                dataOnly = true;
14343                if((ps == null) || (ps.pkg == null)) {
14344                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14345                    return false;
14346                }
14347                p = ps.pkg;
14348            }
14349            if (ps != null) {
14350                libDirRoot = ps.legacyNativeLibraryPathString;
14351            }
14352            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14353                final long token = Binder.clearCallingIdentity();
14354                try {
14355                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14356                    if (secureContainerId != null) {
14357                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14358                    }
14359                } finally {
14360                    Binder.restoreCallingIdentity(token);
14361                }
14362            }
14363        }
14364        String publicSrcDir = null;
14365        if(!dataOnly) {
14366            final ApplicationInfo applicationInfo = p.applicationInfo;
14367            if (applicationInfo == null) {
14368                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14369                return false;
14370            }
14371            if (p.isForwardLocked()) {
14372                publicSrcDir = applicationInfo.getBaseResourcePath();
14373            }
14374        }
14375        // TODO: extend to measure size of split APKs
14376        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14377        // not just the first level.
14378        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14379        // just the primary.
14380        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14381
14382        String apkPath;
14383        File packageDir = new File(p.codePath);
14384
14385        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14386            apkPath = packageDir.getAbsolutePath();
14387            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14388            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14389                libDirRoot = null;
14390            }
14391        } else {
14392            apkPath = p.baseCodePath;
14393        }
14394
14395        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14396                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14397        if (res < 0) {
14398            return false;
14399        }
14400
14401        // Fix-up for forward-locked applications in ASEC containers.
14402        if (!isExternal(p)) {
14403            pStats.codeSize += pStats.externalCodeSize;
14404            pStats.externalCodeSize = 0L;
14405        }
14406
14407        return true;
14408    }
14409
14410
14411    @Override
14412    public void addPackageToPreferred(String packageName) {
14413        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14414    }
14415
14416    @Override
14417    public void removePackageFromPreferred(String packageName) {
14418        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14419    }
14420
14421    @Override
14422    public List<PackageInfo> getPreferredPackages(int flags) {
14423        return new ArrayList<PackageInfo>();
14424    }
14425
14426    private int getUidTargetSdkVersionLockedLPr(int uid) {
14427        Object obj = mSettings.getUserIdLPr(uid);
14428        if (obj instanceof SharedUserSetting) {
14429            final SharedUserSetting sus = (SharedUserSetting) obj;
14430            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14431            final Iterator<PackageSetting> it = sus.packages.iterator();
14432            while (it.hasNext()) {
14433                final PackageSetting ps = it.next();
14434                if (ps.pkg != null) {
14435                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14436                    if (v < vers) vers = v;
14437                }
14438            }
14439            return vers;
14440        } else if (obj instanceof PackageSetting) {
14441            final PackageSetting ps = (PackageSetting) obj;
14442            if (ps.pkg != null) {
14443                return ps.pkg.applicationInfo.targetSdkVersion;
14444            }
14445        }
14446        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14447    }
14448
14449    @Override
14450    public void addPreferredActivity(IntentFilter filter, int match,
14451            ComponentName[] set, ComponentName activity, int userId) {
14452        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14453                "Adding preferred");
14454    }
14455
14456    private void addPreferredActivityInternal(IntentFilter filter, int match,
14457            ComponentName[] set, ComponentName activity, boolean always, int userId,
14458            String opname) {
14459        // writer
14460        int callingUid = Binder.getCallingUid();
14461        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14462        if (filter.countActions() == 0) {
14463            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14464            return;
14465        }
14466        synchronized (mPackages) {
14467            if (mContext.checkCallingOrSelfPermission(
14468                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14469                    != PackageManager.PERMISSION_GRANTED) {
14470                if (getUidTargetSdkVersionLockedLPr(callingUid)
14471                        < Build.VERSION_CODES.FROYO) {
14472                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14473                            + callingUid);
14474                    return;
14475                }
14476                mContext.enforceCallingOrSelfPermission(
14477                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14478            }
14479
14480            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14481            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14482                    + userId + ":");
14483            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14484            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14485            scheduleWritePackageRestrictionsLocked(userId);
14486        }
14487    }
14488
14489    @Override
14490    public void replacePreferredActivity(IntentFilter filter, int match,
14491            ComponentName[] set, ComponentName activity, int userId) {
14492        if (filter.countActions() != 1) {
14493            throw new IllegalArgumentException(
14494                    "replacePreferredActivity expects filter to have only 1 action.");
14495        }
14496        if (filter.countDataAuthorities() != 0
14497                || filter.countDataPaths() != 0
14498                || filter.countDataSchemes() > 1
14499                || filter.countDataTypes() != 0) {
14500            throw new IllegalArgumentException(
14501                    "replacePreferredActivity expects filter to have no data authorities, " +
14502                    "paths, or types; and at most one scheme.");
14503        }
14504
14505        final int callingUid = Binder.getCallingUid();
14506        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14507        synchronized (mPackages) {
14508            if (mContext.checkCallingOrSelfPermission(
14509                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14510                    != PackageManager.PERMISSION_GRANTED) {
14511                if (getUidTargetSdkVersionLockedLPr(callingUid)
14512                        < Build.VERSION_CODES.FROYO) {
14513                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14514                            + Binder.getCallingUid());
14515                    return;
14516                }
14517                mContext.enforceCallingOrSelfPermission(
14518                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14519            }
14520
14521            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14522            if (pir != null) {
14523                // Get all of the existing entries that exactly match this filter.
14524                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14525                if (existing != null && existing.size() == 1) {
14526                    PreferredActivity cur = existing.get(0);
14527                    if (DEBUG_PREFERRED) {
14528                        Slog.i(TAG, "Checking replace of preferred:");
14529                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14530                        if (!cur.mPref.mAlways) {
14531                            Slog.i(TAG, "  -- CUR; not mAlways!");
14532                        } else {
14533                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14534                            Slog.i(TAG, "  -- CUR: mSet="
14535                                    + Arrays.toString(cur.mPref.mSetComponents));
14536                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14537                            Slog.i(TAG, "  -- NEW: mMatch="
14538                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14539                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14540                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14541                        }
14542                    }
14543                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14544                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14545                            && cur.mPref.sameSet(set)) {
14546                        // Setting the preferred activity to what it happens to be already
14547                        if (DEBUG_PREFERRED) {
14548                            Slog.i(TAG, "Replacing with same preferred activity "
14549                                    + cur.mPref.mShortComponent + " for user "
14550                                    + userId + ":");
14551                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14552                        }
14553                        return;
14554                    }
14555                }
14556
14557                if (existing != null) {
14558                    if (DEBUG_PREFERRED) {
14559                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14560                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14561                    }
14562                    for (int i = 0; i < existing.size(); i++) {
14563                        PreferredActivity pa = existing.get(i);
14564                        if (DEBUG_PREFERRED) {
14565                            Slog.i(TAG, "Removing existing preferred activity "
14566                                    + pa.mPref.mComponent + ":");
14567                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14568                        }
14569                        pir.removeFilter(pa);
14570                    }
14571                }
14572            }
14573            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14574                    "Replacing preferred");
14575        }
14576    }
14577
14578    @Override
14579    public void clearPackagePreferredActivities(String packageName) {
14580        final int uid = Binder.getCallingUid();
14581        // writer
14582        synchronized (mPackages) {
14583            PackageParser.Package pkg = mPackages.get(packageName);
14584            if (pkg == null || pkg.applicationInfo.uid != uid) {
14585                if (mContext.checkCallingOrSelfPermission(
14586                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14587                        != PackageManager.PERMISSION_GRANTED) {
14588                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14589                            < Build.VERSION_CODES.FROYO) {
14590                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14591                                + Binder.getCallingUid());
14592                        return;
14593                    }
14594                    mContext.enforceCallingOrSelfPermission(
14595                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14596                }
14597            }
14598
14599            int user = UserHandle.getCallingUserId();
14600            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14601                scheduleWritePackageRestrictionsLocked(user);
14602            }
14603        }
14604    }
14605
14606    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14607    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14608        ArrayList<PreferredActivity> removed = null;
14609        boolean changed = false;
14610        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14611            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14612            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14613            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14614                continue;
14615            }
14616            Iterator<PreferredActivity> it = pir.filterIterator();
14617            while (it.hasNext()) {
14618                PreferredActivity pa = it.next();
14619                // Mark entry for removal only if it matches the package name
14620                // and the entry is of type "always".
14621                if (packageName == null ||
14622                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14623                                && pa.mPref.mAlways)) {
14624                    if (removed == null) {
14625                        removed = new ArrayList<PreferredActivity>();
14626                    }
14627                    removed.add(pa);
14628                }
14629            }
14630            if (removed != null) {
14631                for (int j=0; j<removed.size(); j++) {
14632                    PreferredActivity pa = removed.get(j);
14633                    pir.removeFilter(pa);
14634                }
14635                changed = true;
14636            }
14637        }
14638        return changed;
14639    }
14640
14641    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14642    private void clearIntentFilterVerificationsLPw(int userId) {
14643        final int packageCount = mPackages.size();
14644        for (int i = 0; i < packageCount; i++) {
14645            PackageParser.Package pkg = mPackages.valueAt(i);
14646            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14647        }
14648    }
14649
14650    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14651    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14652        if (userId == UserHandle.USER_ALL) {
14653            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14654                    sUserManager.getUserIds())) {
14655                for (int oneUserId : sUserManager.getUserIds()) {
14656                    scheduleWritePackageRestrictionsLocked(oneUserId);
14657                }
14658            }
14659        } else {
14660            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14661                scheduleWritePackageRestrictionsLocked(userId);
14662            }
14663        }
14664    }
14665
14666    void clearDefaultBrowserIfNeeded(String packageName) {
14667        for (int oneUserId : sUserManager.getUserIds()) {
14668            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14669            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14670            if (packageName.equals(defaultBrowserPackageName)) {
14671                setDefaultBrowserPackageName(null, oneUserId);
14672            }
14673        }
14674    }
14675
14676    @Override
14677    public void resetApplicationPreferences(int userId) {
14678        mContext.enforceCallingOrSelfPermission(
14679                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14680        // writer
14681        synchronized (mPackages) {
14682            final long identity = Binder.clearCallingIdentity();
14683            try {
14684                clearPackagePreferredActivitiesLPw(null, userId);
14685                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14686                // TODO: We have to reset the default SMS and Phone. This requires
14687                // significant refactoring to keep all default apps in the package
14688                // manager (cleaner but more work) or have the services provide
14689                // callbacks to the package manager to request a default app reset.
14690                applyFactoryDefaultBrowserLPw(userId);
14691                clearIntentFilterVerificationsLPw(userId);
14692                primeDomainVerificationsLPw(userId);
14693                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14694                scheduleWritePackageRestrictionsLocked(userId);
14695            } finally {
14696                Binder.restoreCallingIdentity(identity);
14697            }
14698        }
14699    }
14700
14701    @Override
14702    public int getPreferredActivities(List<IntentFilter> outFilters,
14703            List<ComponentName> outActivities, String packageName) {
14704
14705        int num = 0;
14706        final int userId = UserHandle.getCallingUserId();
14707        // reader
14708        synchronized (mPackages) {
14709            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14710            if (pir != null) {
14711                final Iterator<PreferredActivity> it = pir.filterIterator();
14712                while (it.hasNext()) {
14713                    final PreferredActivity pa = it.next();
14714                    if (packageName == null
14715                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14716                                    && pa.mPref.mAlways)) {
14717                        if (outFilters != null) {
14718                            outFilters.add(new IntentFilter(pa));
14719                        }
14720                        if (outActivities != null) {
14721                            outActivities.add(pa.mPref.mComponent);
14722                        }
14723                    }
14724                }
14725            }
14726        }
14727
14728        return num;
14729    }
14730
14731    @Override
14732    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14733            int userId) {
14734        int callingUid = Binder.getCallingUid();
14735        if (callingUid != Process.SYSTEM_UID) {
14736            throw new SecurityException(
14737                    "addPersistentPreferredActivity can only be run by the system");
14738        }
14739        if (filter.countActions() == 0) {
14740            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14741            return;
14742        }
14743        synchronized (mPackages) {
14744            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14745                    " :");
14746            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14747            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14748                    new PersistentPreferredActivity(filter, activity));
14749            scheduleWritePackageRestrictionsLocked(userId);
14750        }
14751    }
14752
14753    @Override
14754    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14755        int callingUid = Binder.getCallingUid();
14756        if (callingUid != Process.SYSTEM_UID) {
14757            throw new SecurityException(
14758                    "clearPackagePersistentPreferredActivities can only be run by the system");
14759        }
14760        ArrayList<PersistentPreferredActivity> removed = null;
14761        boolean changed = false;
14762        synchronized (mPackages) {
14763            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14764                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14765                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14766                        .valueAt(i);
14767                if (userId != thisUserId) {
14768                    continue;
14769                }
14770                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14771                while (it.hasNext()) {
14772                    PersistentPreferredActivity ppa = it.next();
14773                    // Mark entry for removal only if it matches the package name.
14774                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14775                        if (removed == null) {
14776                            removed = new ArrayList<PersistentPreferredActivity>();
14777                        }
14778                        removed.add(ppa);
14779                    }
14780                }
14781                if (removed != null) {
14782                    for (int j=0; j<removed.size(); j++) {
14783                        PersistentPreferredActivity ppa = removed.get(j);
14784                        ppir.removeFilter(ppa);
14785                    }
14786                    changed = true;
14787                }
14788            }
14789
14790            if (changed) {
14791                scheduleWritePackageRestrictionsLocked(userId);
14792            }
14793        }
14794    }
14795
14796    /**
14797     * Common machinery for picking apart a restored XML blob and passing
14798     * it to a caller-supplied functor to be applied to the running system.
14799     */
14800    private void restoreFromXml(XmlPullParser parser, int userId,
14801            String expectedStartTag, BlobXmlRestorer functor)
14802            throws IOException, XmlPullParserException {
14803        int type;
14804        while ((type = parser.next()) != XmlPullParser.START_TAG
14805                && type != XmlPullParser.END_DOCUMENT) {
14806        }
14807        if (type != XmlPullParser.START_TAG) {
14808            // oops didn't find a start tag?!
14809            if (DEBUG_BACKUP) {
14810                Slog.e(TAG, "Didn't find start tag during restore");
14811            }
14812            return;
14813        }
14814
14815        // this is supposed to be TAG_PREFERRED_BACKUP
14816        if (!expectedStartTag.equals(parser.getName())) {
14817            if (DEBUG_BACKUP) {
14818                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14819            }
14820            return;
14821        }
14822
14823        // skip interfering stuff, then we're aligned with the backing implementation
14824        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14825        functor.apply(parser, userId);
14826    }
14827
14828    private interface BlobXmlRestorer {
14829        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14830    }
14831
14832    /**
14833     * Non-Binder method, support for the backup/restore mechanism: write the
14834     * full set of preferred activities in its canonical XML format.  Returns the
14835     * XML output as a byte array, or null if there is none.
14836     */
14837    @Override
14838    public byte[] getPreferredActivityBackup(int userId) {
14839        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14840            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14841        }
14842
14843        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14844        try {
14845            final XmlSerializer serializer = new FastXmlSerializer();
14846            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14847            serializer.startDocument(null, true);
14848            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14849
14850            synchronized (mPackages) {
14851                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14852            }
14853
14854            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14855            serializer.endDocument();
14856            serializer.flush();
14857        } catch (Exception e) {
14858            if (DEBUG_BACKUP) {
14859                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14860            }
14861            return null;
14862        }
14863
14864        return dataStream.toByteArray();
14865    }
14866
14867    @Override
14868    public void restorePreferredActivities(byte[] backup, int userId) {
14869        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14870            throw new SecurityException("Only the system may call restorePreferredActivities()");
14871        }
14872
14873        try {
14874            final XmlPullParser parser = Xml.newPullParser();
14875            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14876            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14877                    new BlobXmlRestorer() {
14878                        @Override
14879                        public void apply(XmlPullParser parser, int userId)
14880                                throws XmlPullParserException, IOException {
14881                            synchronized (mPackages) {
14882                                mSettings.readPreferredActivitiesLPw(parser, userId);
14883                            }
14884                        }
14885                    } );
14886        } catch (Exception e) {
14887            if (DEBUG_BACKUP) {
14888                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14889            }
14890        }
14891    }
14892
14893    /**
14894     * Non-Binder method, support for the backup/restore mechanism: write the
14895     * default browser (etc) settings in its canonical XML format.  Returns the default
14896     * browser XML representation as a byte array, or null if there is none.
14897     */
14898    @Override
14899    public byte[] getDefaultAppsBackup(int userId) {
14900        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14901            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14902        }
14903
14904        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14905        try {
14906            final XmlSerializer serializer = new FastXmlSerializer();
14907            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14908            serializer.startDocument(null, true);
14909            serializer.startTag(null, TAG_DEFAULT_APPS);
14910
14911            synchronized (mPackages) {
14912                mSettings.writeDefaultAppsLPr(serializer, userId);
14913            }
14914
14915            serializer.endTag(null, TAG_DEFAULT_APPS);
14916            serializer.endDocument();
14917            serializer.flush();
14918        } catch (Exception e) {
14919            if (DEBUG_BACKUP) {
14920                Slog.e(TAG, "Unable to write default apps for backup", e);
14921            }
14922            return null;
14923        }
14924
14925        return dataStream.toByteArray();
14926    }
14927
14928    @Override
14929    public void restoreDefaultApps(byte[] backup, int userId) {
14930        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14931            throw new SecurityException("Only the system may call restoreDefaultApps()");
14932        }
14933
14934        try {
14935            final XmlPullParser parser = Xml.newPullParser();
14936            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14937            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14938                    new BlobXmlRestorer() {
14939                        @Override
14940                        public void apply(XmlPullParser parser, int userId)
14941                                throws XmlPullParserException, IOException {
14942                            synchronized (mPackages) {
14943                                mSettings.readDefaultAppsLPw(parser, userId);
14944                            }
14945                        }
14946                    } );
14947        } catch (Exception e) {
14948            if (DEBUG_BACKUP) {
14949                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14950            }
14951        }
14952    }
14953
14954    @Override
14955    public byte[] getIntentFilterVerificationBackup(int userId) {
14956        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14957            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14958        }
14959
14960        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14961        try {
14962            final XmlSerializer serializer = new FastXmlSerializer();
14963            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14964            serializer.startDocument(null, true);
14965            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14966
14967            synchronized (mPackages) {
14968                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14969            }
14970
14971            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14972            serializer.endDocument();
14973            serializer.flush();
14974        } catch (Exception e) {
14975            if (DEBUG_BACKUP) {
14976                Slog.e(TAG, "Unable to write default apps for backup", e);
14977            }
14978            return null;
14979        }
14980
14981        return dataStream.toByteArray();
14982    }
14983
14984    @Override
14985    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14986        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14987            throw new SecurityException("Only the system may call restorePreferredActivities()");
14988        }
14989
14990        try {
14991            final XmlPullParser parser = Xml.newPullParser();
14992            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14993            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14994                    new BlobXmlRestorer() {
14995                        @Override
14996                        public void apply(XmlPullParser parser, int userId)
14997                                throws XmlPullParserException, IOException {
14998                            synchronized (mPackages) {
14999                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15000                                mSettings.writeLPr();
15001                            }
15002                        }
15003                    } );
15004        } catch (Exception e) {
15005            if (DEBUG_BACKUP) {
15006                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15007            }
15008        }
15009    }
15010
15011    @Override
15012    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15013            int sourceUserId, int targetUserId, int flags) {
15014        mContext.enforceCallingOrSelfPermission(
15015                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15016        int callingUid = Binder.getCallingUid();
15017        enforceOwnerRights(ownerPackage, callingUid);
15018        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15019        if (intentFilter.countActions() == 0) {
15020            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15021            return;
15022        }
15023        synchronized (mPackages) {
15024            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15025                    ownerPackage, targetUserId, flags);
15026            CrossProfileIntentResolver resolver =
15027                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15028            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15029            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15030            if (existing != null) {
15031                int size = existing.size();
15032                for (int i = 0; i < size; i++) {
15033                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15034                        return;
15035                    }
15036                }
15037            }
15038            resolver.addFilter(newFilter);
15039            scheduleWritePackageRestrictionsLocked(sourceUserId);
15040        }
15041    }
15042
15043    @Override
15044    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15045        mContext.enforceCallingOrSelfPermission(
15046                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15047        int callingUid = Binder.getCallingUid();
15048        enforceOwnerRights(ownerPackage, callingUid);
15049        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15050        synchronized (mPackages) {
15051            CrossProfileIntentResolver resolver =
15052                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15053            ArraySet<CrossProfileIntentFilter> set =
15054                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15055            for (CrossProfileIntentFilter filter : set) {
15056                if (filter.getOwnerPackage().equals(ownerPackage)) {
15057                    resolver.removeFilter(filter);
15058                }
15059            }
15060            scheduleWritePackageRestrictionsLocked(sourceUserId);
15061        }
15062    }
15063
15064    // Enforcing that callingUid is owning pkg on userId
15065    private void enforceOwnerRights(String pkg, int callingUid) {
15066        // The system owns everything.
15067        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15068            return;
15069        }
15070        int callingUserId = UserHandle.getUserId(callingUid);
15071        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15072        if (pi == null) {
15073            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15074                    + callingUserId);
15075        }
15076        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15077            throw new SecurityException("Calling uid " + callingUid
15078                    + " does not own package " + pkg);
15079        }
15080    }
15081
15082    @Override
15083    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15084        Intent intent = new Intent(Intent.ACTION_MAIN);
15085        intent.addCategory(Intent.CATEGORY_HOME);
15086
15087        final int callingUserId = UserHandle.getCallingUserId();
15088        List<ResolveInfo> list = queryIntentActivities(intent, null,
15089                PackageManager.GET_META_DATA, callingUserId);
15090        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15091                true, false, false, callingUserId);
15092
15093        allHomeCandidates.clear();
15094        if (list != null) {
15095            for (ResolveInfo ri : list) {
15096                allHomeCandidates.add(ri);
15097            }
15098        }
15099        return (preferred == null || preferred.activityInfo == null)
15100                ? null
15101                : new ComponentName(preferred.activityInfo.packageName,
15102                        preferred.activityInfo.name);
15103    }
15104
15105    @Override
15106    public void setApplicationEnabledSetting(String appPackageName,
15107            int newState, int flags, int userId, String callingPackage) {
15108        if (!sUserManager.exists(userId)) return;
15109        if (callingPackage == null) {
15110            callingPackage = Integer.toString(Binder.getCallingUid());
15111        }
15112        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15113    }
15114
15115    @Override
15116    public void setComponentEnabledSetting(ComponentName componentName,
15117            int newState, int flags, int userId) {
15118        if (!sUserManager.exists(userId)) return;
15119        setEnabledSetting(componentName.getPackageName(),
15120                componentName.getClassName(), newState, flags, userId, null);
15121    }
15122
15123    private void setEnabledSetting(final String packageName, String className, int newState,
15124            final int flags, int userId, String callingPackage) {
15125        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15126              || newState == COMPONENT_ENABLED_STATE_ENABLED
15127              || newState == COMPONENT_ENABLED_STATE_DISABLED
15128              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15129              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15130            throw new IllegalArgumentException("Invalid new component state: "
15131                    + newState);
15132        }
15133        PackageSetting pkgSetting;
15134        final int uid = Binder.getCallingUid();
15135        final int permission = mContext.checkCallingOrSelfPermission(
15136                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15137        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15138        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15139        boolean sendNow = false;
15140        boolean isApp = (className == null);
15141        String componentName = isApp ? packageName : className;
15142        int packageUid = -1;
15143        ArrayList<String> components;
15144
15145        // writer
15146        synchronized (mPackages) {
15147            pkgSetting = mSettings.mPackages.get(packageName);
15148            if (pkgSetting == null) {
15149                if (className == null) {
15150                    throw new IllegalArgumentException(
15151                            "Unknown package: " + packageName);
15152                }
15153                throw new IllegalArgumentException(
15154                        "Unknown component: " + packageName
15155                        + "/" + className);
15156            }
15157            // Allow root and verify that userId is not being specified by a different user
15158            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15159                throw new SecurityException(
15160                        "Permission Denial: attempt to change component state from pid="
15161                        + Binder.getCallingPid()
15162                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15163            }
15164            if (className == null) {
15165                // We're dealing with an application/package level state change
15166                if (pkgSetting.getEnabled(userId) == newState) {
15167                    // Nothing to do
15168                    return;
15169                }
15170                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15171                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15172                    // Don't care about who enables an app.
15173                    callingPackage = null;
15174                }
15175                pkgSetting.setEnabled(newState, userId, callingPackage);
15176                // pkgSetting.pkg.mSetEnabled = newState;
15177            } else {
15178                // We're dealing with a component level state change
15179                // First, verify that this is a valid class name.
15180                PackageParser.Package pkg = pkgSetting.pkg;
15181                if (pkg == null || !pkg.hasComponentClassName(className)) {
15182                    if (pkg != null &&
15183                            pkg.applicationInfo.targetSdkVersion >=
15184                                    Build.VERSION_CODES.JELLY_BEAN) {
15185                        throw new IllegalArgumentException("Component class " + className
15186                                + " does not exist in " + packageName);
15187                    } else {
15188                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15189                                + className + " does not exist in " + packageName);
15190                    }
15191                }
15192                switch (newState) {
15193                case COMPONENT_ENABLED_STATE_ENABLED:
15194                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15195                        return;
15196                    }
15197                    break;
15198                case COMPONENT_ENABLED_STATE_DISABLED:
15199                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15200                        return;
15201                    }
15202                    break;
15203                case COMPONENT_ENABLED_STATE_DEFAULT:
15204                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15205                        return;
15206                    }
15207                    break;
15208                default:
15209                    Slog.e(TAG, "Invalid new component state: " + newState);
15210                    return;
15211                }
15212            }
15213            scheduleWritePackageRestrictionsLocked(userId);
15214            components = mPendingBroadcasts.get(userId, packageName);
15215            final boolean newPackage = components == null;
15216            if (newPackage) {
15217                components = new ArrayList<String>();
15218            }
15219            if (!components.contains(componentName)) {
15220                components.add(componentName);
15221            }
15222            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15223                sendNow = true;
15224                // Purge entry from pending broadcast list if another one exists already
15225                // since we are sending one right away.
15226                mPendingBroadcasts.remove(userId, packageName);
15227            } else {
15228                if (newPackage) {
15229                    mPendingBroadcasts.put(userId, packageName, components);
15230                }
15231                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15232                    // Schedule a message
15233                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15234                }
15235            }
15236        }
15237
15238        long callingId = Binder.clearCallingIdentity();
15239        try {
15240            if (sendNow) {
15241                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15242                sendPackageChangedBroadcast(packageName,
15243                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15244            }
15245        } finally {
15246            Binder.restoreCallingIdentity(callingId);
15247        }
15248    }
15249
15250    private void sendPackageChangedBroadcast(String packageName,
15251            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15252        if (DEBUG_INSTALL)
15253            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15254                    + componentNames);
15255        Bundle extras = new Bundle(4);
15256        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15257        String nameList[] = new String[componentNames.size()];
15258        componentNames.toArray(nameList);
15259        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15260        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15261        extras.putInt(Intent.EXTRA_UID, packageUid);
15262        // If this is not reporting a change of the overall package, then only send it
15263        // to registered receivers.  We don't want to launch a swath of apps for every
15264        // little component state change.
15265        final int flags = !componentNames.contains(packageName)
15266                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15267        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15268                new int[] {UserHandle.getUserId(packageUid)});
15269    }
15270
15271    @Override
15272    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15273        if (!sUserManager.exists(userId)) return;
15274        final int uid = Binder.getCallingUid();
15275        final int permission = mContext.checkCallingOrSelfPermission(
15276                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15277        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15278        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15279        // writer
15280        synchronized (mPackages) {
15281            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15282                    allowedByPermission, uid, userId)) {
15283                scheduleWritePackageRestrictionsLocked(userId);
15284            }
15285        }
15286    }
15287
15288    @Override
15289    public String getInstallerPackageName(String packageName) {
15290        // reader
15291        synchronized (mPackages) {
15292            return mSettings.getInstallerPackageNameLPr(packageName);
15293        }
15294    }
15295
15296    @Override
15297    public int getApplicationEnabledSetting(String packageName, int userId) {
15298        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15299        int uid = Binder.getCallingUid();
15300        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15301        // reader
15302        synchronized (mPackages) {
15303            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15304        }
15305    }
15306
15307    @Override
15308    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15309        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15310        int uid = Binder.getCallingUid();
15311        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15312        // reader
15313        synchronized (mPackages) {
15314            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15315        }
15316    }
15317
15318    @Override
15319    public void enterSafeMode() {
15320        enforceSystemOrRoot("Only the system can request entering safe mode");
15321
15322        if (!mSystemReady) {
15323            mSafeMode = true;
15324        }
15325    }
15326
15327    @Override
15328    public void systemReady() {
15329        mSystemReady = true;
15330
15331        // Read the compatibilty setting when the system is ready.
15332        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15333                mContext.getContentResolver(),
15334                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15335        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15336        if (DEBUG_SETTINGS) {
15337            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15338        }
15339
15340        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15341
15342        synchronized (mPackages) {
15343            // Verify that all of the preferred activity components actually
15344            // exist.  It is possible for applications to be updated and at
15345            // that point remove a previously declared activity component that
15346            // had been set as a preferred activity.  We try to clean this up
15347            // the next time we encounter that preferred activity, but it is
15348            // possible for the user flow to never be able to return to that
15349            // situation so here we do a sanity check to make sure we haven't
15350            // left any junk around.
15351            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15352            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15353                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15354                removed.clear();
15355                for (PreferredActivity pa : pir.filterSet()) {
15356                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15357                        removed.add(pa);
15358                    }
15359                }
15360                if (removed.size() > 0) {
15361                    for (int r=0; r<removed.size(); r++) {
15362                        PreferredActivity pa = removed.get(r);
15363                        Slog.w(TAG, "Removing dangling preferred activity: "
15364                                + pa.mPref.mComponent);
15365                        pir.removeFilter(pa);
15366                    }
15367                    mSettings.writePackageRestrictionsLPr(
15368                            mSettings.mPreferredActivities.keyAt(i));
15369                }
15370            }
15371
15372            for (int userId : UserManagerService.getInstance().getUserIds()) {
15373                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15374                    grantPermissionsUserIds = ArrayUtils.appendInt(
15375                            grantPermissionsUserIds, userId);
15376                }
15377            }
15378        }
15379        sUserManager.systemReady();
15380
15381        // If we upgraded grant all default permissions before kicking off.
15382        for (int userId : grantPermissionsUserIds) {
15383            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15384        }
15385
15386        // Kick off any messages waiting for system ready
15387        if (mPostSystemReadyMessages != null) {
15388            for (Message msg : mPostSystemReadyMessages) {
15389                msg.sendToTarget();
15390            }
15391            mPostSystemReadyMessages = null;
15392        }
15393
15394        // Watch for external volumes that come and go over time
15395        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15396        storage.registerListener(mStorageListener);
15397
15398        mInstallerService.systemReady();
15399        mPackageDexOptimizer.systemReady();
15400
15401        MountServiceInternal mountServiceInternal = LocalServices.getService(
15402                MountServiceInternal.class);
15403        mountServiceInternal.addExternalStoragePolicy(
15404                new MountServiceInternal.ExternalStorageMountPolicy() {
15405            @Override
15406            public int getMountMode(int uid, String packageName) {
15407                if (Process.isIsolated(uid)) {
15408                    return Zygote.MOUNT_EXTERNAL_NONE;
15409                }
15410                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15411                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15412                }
15413                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15414                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15415                }
15416                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15417                    return Zygote.MOUNT_EXTERNAL_READ;
15418                }
15419                return Zygote.MOUNT_EXTERNAL_WRITE;
15420            }
15421
15422            @Override
15423            public boolean hasExternalStorage(int uid, String packageName) {
15424                return true;
15425            }
15426        });
15427    }
15428
15429    @Override
15430    public boolean isSafeMode() {
15431        return mSafeMode;
15432    }
15433
15434    @Override
15435    public boolean hasSystemUidErrors() {
15436        return mHasSystemUidErrors;
15437    }
15438
15439    static String arrayToString(int[] array) {
15440        StringBuffer buf = new StringBuffer(128);
15441        buf.append('[');
15442        if (array != null) {
15443            for (int i=0; i<array.length; i++) {
15444                if (i > 0) buf.append(", ");
15445                buf.append(array[i]);
15446            }
15447        }
15448        buf.append(']');
15449        return buf.toString();
15450    }
15451
15452    static class DumpState {
15453        public static final int DUMP_LIBS = 1 << 0;
15454        public static final int DUMP_FEATURES = 1 << 1;
15455        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15456        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15457        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15458        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15459        public static final int DUMP_PERMISSIONS = 1 << 6;
15460        public static final int DUMP_PACKAGES = 1 << 7;
15461        public static final int DUMP_SHARED_USERS = 1 << 8;
15462        public static final int DUMP_MESSAGES = 1 << 9;
15463        public static final int DUMP_PROVIDERS = 1 << 10;
15464        public static final int DUMP_VERIFIERS = 1 << 11;
15465        public static final int DUMP_PREFERRED = 1 << 12;
15466        public static final int DUMP_PREFERRED_XML = 1 << 13;
15467        public static final int DUMP_KEYSETS = 1 << 14;
15468        public static final int DUMP_VERSION = 1 << 15;
15469        public static final int DUMP_INSTALLS = 1 << 16;
15470        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15471        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15472
15473        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15474
15475        private int mTypes;
15476
15477        private int mOptions;
15478
15479        private boolean mTitlePrinted;
15480
15481        private SharedUserSetting mSharedUser;
15482
15483        public boolean isDumping(int type) {
15484            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15485                return true;
15486            }
15487
15488            return (mTypes & type) != 0;
15489        }
15490
15491        public void setDump(int type) {
15492            mTypes |= type;
15493        }
15494
15495        public boolean isOptionEnabled(int option) {
15496            return (mOptions & option) != 0;
15497        }
15498
15499        public void setOptionEnabled(int option) {
15500            mOptions |= option;
15501        }
15502
15503        public boolean onTitlePrinted() {
15504            final boolean printed = mTitlePrinted;
15505            mTitlePrinted = true;
15506            return printed;
15507        }
15508
15509        public boolean getTitlePrinted() {
15510            return mTitlePrinted;
15511        }
15512
15513        public void setTitlePrinted(boolean enabled) {
15514            mTitlePrinted = enabled;
15515        }
15516
15517        public SharedUserSetting getSharedUser() {
15518            return mSharedUser;
15519        }
15520
15521        public void setSharedUser(SharedUserSetting user) {
15522            mSharedUser = user;
15523        }
15524    }
15525
15526    @Override
15527    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15528            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15529        (new PackageManagerShellCommand(this)).exec(
15530                this, in, out, err, args, resultReceiver);
15531    }
15532
15533    @Override
15534    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15535        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15536                != PackageManager.PERMISSION_GRANTED) {
15537            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15538                    + Binder.getCallingPid()
15539                    + ", uid=" + Binder.getCallingUid()
15540                    + " without permission "
15541                    + android.Manifest.permission.DUMP);
15542            return;
15543        }
15544
15545        DumpState dumpState = new DumpState();
15546        boolean fullPreferred = false;
15547        boolean checkin = false;
15548
15549        String packageName = null;
15550        ArraySet<String> permissionNames = null;
15551
15552        int opti = 0;
15553        while (opti < args.length) {
15554            String opt = args[opti];
15555            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15556                break;
15557            }
15558            opti++;
15559
15560            if ("-a".equals(opt)) {
15561                // Right now we only know how to print all.
15562            } else if ("-h".equals(opt)) {
15563                pw.println("Package manager dump options:");
15564                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15565                pw.println("    --checkin: dump for a checkin");
15566                pw.println("    -f: print details of intent filters");
15567                pw.println("    -h: print this help");
15568                pw.println("  cmd may be one of:");
15569                pw.println("    l[ibraries]: list known shared libraries");
15570                pw.println("    f[eatures]: list device features");
15571                pw.println("    k[eysets]: print known keysets");
15572                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15573                pw.println("    perm[issions]: dump permissions");
15574                pw.println("    permission [name ...]: dump declaration and use of given permission");
15575                pw.println("    pref[erred]: print preferred package settings");
15576                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15577                pw.println("    prov[iders]: dump content providers");
15578                pw.println("    p[ackages]: dump installed packages");
15579                pw.println("    s[hared-users]: dump shared user IDs");
15580                pw.println("    m[essages]: print collected runtime messages");
15581                pw.println("    v[erifiers]: print package verifier info");
15582                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15583                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15584                pw.println("    version: print database version info");
15585                pw.println("    write: write current settings now");
15586                pw.println("    installs: details about install sessions");
15587                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15588                pw.println("    <package.name>: info about given package");
15589                return;
15590            } else if ("--checkin".equals(opt)) {
15591                checkin = true;
15592            } else if ("-f".equals(opt)) {
15593                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15594            } else {
15595                pw.println("Unknown argument: " + opt + "; use -h for help");
15596            }
15597        }
15598
15599        // Is the caller requesting to dump a particular piece of data?
15600        if (opti < args.length) {
15601            String cmd = args[opti];
15602            opti++;
15603            // Is this a package name?
15604            if ("android".equals(cmd) || cmd.contains(".")) {
15605                packageName = cmd;
15606                // When dumping a single package, we always dump all of its
15607                // filter information since the amount of data will be reasonable.
15608                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15609            } else if ("check-permission".equals(cmd)) {
15610                if (opti >= args.length) {
15611                    pw.println("Error: check-permission missing permission argument");
15612                    return;
15613                }
15614                String perm = args[opti];
15615                opti++;
15616                if (opti >= args.length) {
15617                    pw.println("Error: check-permission missing package argument");
15618                    return;
15619                }
15620                String pkg = args[opti];
15621                opti++;
15622                int user = UserHandle.getUserId(Binder.getCallingUid());
15623                if (opti < args.length) {
15624                    try {
15625                        user = Integer.parseInt(args[opti]);
15626                    } catch (NumberFormatException e) {
15627                        pw.println("Error: check-permission user argument is not a number: "
15628                                + args[opti]);
15629                        return;
15630                    }
15631                }
15632                pw.println(checkPermission(perm, pkg, user));
15633                return;
15634            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15635                dumpState.setDump(DumpState.DUMP_LIBS);
15636            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15637                dumpState.setDump(DumpState.DUMP_FEATURES);
15638            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15639                if (opti >= args.length) {
15640                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15641                            | DumpState.DUMP_SERVICE_RESOLVERS
15642                            | DumpState.DUMP_RECEIVER_RESOLVERS
15643                            | DumpState.DUMP_CONTENT_RESOLVERS);
15644                } else {
15645                    while (opti < args.length) {
15646                        String name = args[opti];
15647                        if ("a".equals(name) || "activity".equals(name)) {
15648                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15649                        } else if ("s".equals(name) || "service".equals(name)) {
15650                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15651                        } else if ("r".equals(name) || "receiver".equals(name)) {
15652                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15653                        } else if ("c".equals(name) || "content".equals(name)) {
15654                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15655                        } else {
15656                            pw.println("Error: unknown resolver table type: " + name);
15657                            return;
15658                        }
15659                        opti++;
15660                    }
15661                }
15662            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15663                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15664            } else if ("permission".equals(cmd)) {
15665                if (opti >= args.length) {
15666                    pw.println("Error: permission requires permission name");
15667                    return;
15668                }
15669                permissionNames = new ArraySet<>();
15670                while (opti < args.length) {
15671                    permissionNames.add(args[opti]);
15672                    opti++;
15673                }
15674                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15675                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15676            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15677                dumpState.setDump(DumpState.DUMP_PREFERRED);
15678            } else if ("preferred-xml".equals(cmd)) {
15679                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15680                if (opti < args.length && "--full".equals(args[opti])) {
15681                    fullPreferred = true;
15682                    opti++;
15683                }
15684            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15685                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15686            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15687                dumpState.setDump(DumpState.DUMP_PACKAGES);
15688            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15689                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15690            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15691                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15692            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15693                dumpState.setDump(DumpState.DUMP_MESSAGES);
15694            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15695                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15696            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15697                    || "intent-filter-verifiers".equals(cmd)) {
15698                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15699            } else if ("version".equals(cmd)) {
15700                dumpState.setDump(DumpState.DUMP_VERSION);
15701            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15702                dumpState.setDump(DumpState.DUMP_KEYSETS);
15703            } else if ("installs".equals(cmd)) {
15704                dumpState.setDump(DumpState.DUMP_INSTALLS);
15705            } else if ("write".equals(cmd)) {
15706                synchronized (mPackages) {
15707                    mSettings.writeLPr();
15708                    pw.println("Settings written.");
15709                    return;
15710                }
15711            }
15712        }
15713
15714        if (checkin) {
15715            pw.println("vers,1");
15716        }
15717
15718        // reader
15719        synchronized (mPackages) {
15720            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15721                if (!checkin) {
15722                    if (dumpState.onTitlePrinted())
15723                        pw.println();
15724                    pw.println("Database versions:");
15725                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15726                }
15727            }
15728
15729            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15730                if (!checkin) {
15731                    if (dumpState.onTitlePrinted())
15732                        pw.println();
15733                    pw.println("Verifiers:");
15734                    pw.print("  Required: ");
15735                    pw.print(mRequiredVerifierPackage);
15736                    pw.print(" (uid=");
15737                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15738                    pw.println(")");
15739                } else if (mRequiredVerifierPackage != null) {
15740                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15741                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15742                }
15743            }
15744
15745            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15746                    packageName == null) {
15747                if (mIntentFilterVerifierComponent != null) {
15748                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15749                    if (!checkin) {
15750                        if (dumpState.onTitlePrinted())
15751                            pw.println();
15752                        pw.println("Intent Filter Verifier:");
15753                        pw.print("  Using: ");
15754                        pw.print(verifierPackageName);
15755                        pw.print(" (uid=");
15756                        pw.print(getPackageUid(verifierPackageName, 0));
15757                        pw.println(")");
15758                    } else if (verifierPackageName != null) {
15759                        pw.print("ifv,"); pw.print(verifierPackageName);
15760                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15761                    }
15762                } else {
15763                    pw.println();
15764                    pw.println("No Intent Filter Verifier available!");
15765                }
15766            }
15767
15768            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15769                boolean printedHeader = false;
15770                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15771                while (it.hasNext()) {
15772                    String name = it.next();
15773                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15774                    if (!checkin) {
15775                        if (!printedHeader) {
15776                            if (dumpState.onTitlePrinted())
15777                                pw.println();
15778                            pw.println("Libraries:");
15779                            printedHeader = true;
15780                        }
15781                        pw.print("  ");
15782                    } else {
15783                        pw.print("lib,");
15784                    }
15785                    pw.print(name);
15786                    if (!checkin) {
15787                        pw.print(" -> ");
15788                    }
15789                    if (ent.path != null) {
15790                        if (!checkin) {
15791                            pw.print("(jar) ");
15792                            pw.print(ent.path);
15793                        } else {
15794                            pw.print(",jar,");
15795                            pw.print(ent.path);
15796                        }
15797                    } else {
15798                        if (!checkin) {
15799                            pw.print("(apk) ");
15800                            pw.print(ent.apk);
15801                        } else {
15802                            pw.print(",apk,");
15803                            pw.print(ent.apk);
15804                        }
15805                    }
15806                    pw.println();
15807                }
15808            }
15809
15810            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15811                if (dumpState.onTitlePrinted())
15812                    pw.println();
15813                if (!checkin) {
15814                    pw.println("Features:");
15815                }
15816                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15817                while (it.hasNext()) {
15818                    String name = it.next();
15819                    if (!checkin) {
15820                        pw.print("  ");
15821                    } else {
15822                        pw.print("feat,");
15823                    }
15824                    pw.println(name);
15825                }
15826            }
15827
15828            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15829                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15830                        : "Activity Resolver Table:", "  ", packageName,
15831                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15832                    dumpState.setTitlePrinted(true);
15833                }
15834            }
15835            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15836                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15837                        : "Receiver Resolver Table:", "  ", packageName,
15838                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15839                    dumpState.setTitlePrinted(true);
15840                }
15841            }
15842            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15843                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15844                        : "Service Resolver Table:", "  ", packageName,
15845                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15846                    dumpState.setTitlePrinted(true);
15847                }
15848            }
15849            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15850                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15851                        : "Provider Resolver Table:", "  ", packageName,
15852                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15853                    dumpState.setTitlePrinted(true);
15854                }
15855            }
15856
15857            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15858                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15859                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15860                    int user = mSettings.mPreferredActivities.keyAt(i);
15861                    if (pir.dump(pw,
15862                            dumpState.getTitlePrinted()
15863                                ? "\nPreferred Activities User " + user + ":"
15864                                : "Preferred Activities User " + user + ":", "  ",
15865                            packageName, true, false)) {
15866                        dumpState.setTitlePrinted(true);
15867                    }
15868                }
15869            }
15870
15871            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15872                pw.flush();
15873                FileOutputStream fout = new FileOutputStream(fd);
15874                BufferedOutputStream str = new BufferedOutputStream(fout);
15875                XmlSerializer serializer = new FastXmlSerializer();
15876                try {
15877                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15878                    serializer.startDocument(null, true);
15879                    serializer.setFeature(
15880                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15881                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15882                    serializer.endDocument();
15883                    serializer.flush();
15884                } catch (IllegalArgumentException e) {
15885                    pw.println("Failed writing: " + e);
15886                } catch (IllegalStateException e) {
15887                    pw.println("Failed writing: " + e);
15888                } catch (IOException e) {
15889                    pw.println("Failed writing: " + e);
15890                }
15891            }
15892
15893            if (!checkin
15894                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15895                    && packageName == null) {
15896                pw.println();
15897                int count = mSettings.mPackages.size();
15898                if (count == 0) {
15899                    pw.println("No applications!");
15900                    pw.println();
15901                } else {
15902                    final String prefix = "  ";
15903                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15904                    if (allPackageSettings.size() == 0) {
15905                        pw.println("No domain preferred apps!");
15906                        pw.println();
15907                    } else {
15908                        pw.println("App verification status:");
15909                        pw.println();
15910                        count = 0;
15911                        for (PackageSetting ps : allPackageSettings) {
15912                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15913                            if (ivi == null || ivi.getPackageName() == null) continue;
15914                            pw.println(prefix + "Package: " + ivi.getPackageName());
15915                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15916                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15917                            pw.println();
15918                            count++;
15919                        }
15920                        if (count == 0) {
15921                            pw.println(prefix + "No app verification established.");
15922                            pw.println();
15923                        }
15924                        for (int userId : sUserManager.getUserIds()) {
15925                            pw.println("App linkages for user " + userId + ":");
15926                            pw.println();
15927                            count = 0;
15928                            for (PackageSetting ps : allPackageSettings) {
15929                                final long status = ps.getDomainVerificationStatusForUser(userId);
15930                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15931                                    continue;
15932                                }
15933                                pw.println(prefix + "Package: " + ps.name);
15934                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15935                                String statusStr = IntentFilterVerificationInfo.
15936                                        getStatusStringFromValue(status);
15937                                pw.println(prefix + "Status:  " + statusStr);
15938                                pw.println();
15939                                count++;
15940                            }
15941                            if (count == 0) {
15942                                pw.println(prefix + "No configured app linkages.");
15943                                pw.println();
15944                            }
15945                        }
15946                    }
15947                }
15948            }
15949
15950            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15951                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15952                if (packageName == null && permissionNames == null) {
15953                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15954                        if (iperm == 0) {
15955                            if (dumpState.onTitlePrinted())
15956                                pw.println();
15957                            pw.println("AppOp Permissions:");
15958                        }
15959                        pw.print("  AppOp Permission ");
15960                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15961                        pw.println(":");
15962                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15963                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15964                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15965                        }
15966                    }
15967                }
15968            }
15969
15970            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15971                boolean printedSomething = false;
15972                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15973                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15974                        continue;
15975                    }
15976                    if (!printedSomething) {
15977                        if (dumpState.onTitlePrinted())
15978                            pw.println();
15979                        pw.println("Registered ContentProviders:");
15980                        printedSomething = true;
15981                    }
15982                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15983                    pw.print("    "); pw.println(p.toString());
15984                }
15985                printedSomething = false;
15986                for (Map.Entry<String, PackageParser.Provider> entry :
15987                        mProvidersByAuthority.entrySet()) {
15988                    PackageParser.Provider p = entry.getValue();
15989                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15990                        continue;
15991                    }
15992                    if (!printedSomething) {
15993                        if (dumpState.onTitlePrinted())
15994                            pw.println();
15995                        pw.println("ContentProvider Authorities:");
15996                        printedSomething = true;
15997                    }
15998                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15999                    pw.print("    "); pw.println(p.toString());
16000                    if (p.info != null && p.info.applicationInfo != null) {
16001                        final String appInfo = p.info.applicationInfo.toString();
16002                        pw.print("      applicationInfo="); pw.println(appInfo);
16003                    }
16004                }
16005            }
16006
16007            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16008                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16009            }
16010
16011            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16012                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16013            }
16014
16015            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16016                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16017            }
16018
16019            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16020                // XXX should handle packageName != null by dumping only install data that
16021                // the given package is involved with.
16022                if (dumpState.onTitlePrinted()) pw.println();
16023                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16024            }
16025
16026            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16027                if (dumpState.onTitlePrinted()) pw.println();
16028                mSettings.dumpReadMessagesLPr(pw, dumpState);
16029
16030                pw.println();
16031                pw.println("Package warning messages:");
16032                BufferedReader in = null;
16033                String line = null;
16034                try {
16035                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16036                    while ((line = in.readLine()) != null) {
16037                        if (line.contains("ignored: updated version")) continue;
16038                        pw.println(line);
16039                    }
16040                } catch (IOException ignored) {
16041                } finally {
16042                    IoUtils.closeQuietly(in);
16043                }
16044            }
16045
16046            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16047                BufferedReader in = null;
16048                String line = null;
16049                try {
16050                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16051                    while ((line = in.readLine()) != null) {
16052                        if (line.contains("ignored: updated version")) continue;
16053                        pw.print("msg,");
16054                        pw.println(line);
16055                    }
16056                } catch (IOException ignored) {
16057                } finally {
16058                    IoUtils.closeQuietly(in);
16059                }
16060            }
16061        }
16062    }
16063
16064    private String dumpDomainString(String packageName) {
16065        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16066        List<IntentFilter> filters = getAllIntentFilters(packageName);
16067
16068        ArraySet<String> result = new ArraySet<>();
16069        if (iviList.size() > 0) {
16070            for (IntentFilterVerificationInfo ivi : iviList) {
16071                for (String host : ivi.getDomains()) {
16072                    result.add(host);
16073                }
16074            }
16075        }
16076        if (filters != null && filters.size() > 0) {
16077            for (IntentFilter filter : filters) {
16078                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16079                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16080                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16081                    result.addAll(filter.getHostsList());
16082                }
16083            }
16084        }
16085
16086        StringBuilder sb = new StringBuilder(result.size() * 16);
16087        for (String domain : result) {
16088            if (sb.length() > 0) sb.append(" ");
16089            sb.append(domain);
16090        }
16091        return sb.toString();
16092    }
16093
16094    // ------- apps on sdcard specific code -------
16095    static final boolean DEBUG_SD_INSTALL = false;
16096
16097    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16098
16099    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16100
16101    private boolean mMediaMounted = false;
16102
16103    static String getEncryptKey() {
16104        try {
16105            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16106                    SD_ENCRYPTION_KEYSTORE_NAME);
16107            if (sdEncKey == null) {
16108                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16109                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16110                if (sdEncKey == null) {
16111                    Slog.e(TAG, "Failed to create encryption keys");
16112                    return null;
16113                }
16114            }
16115            return sdEncKey;
16116        } catch (NoSuchAlgorithmException nsae) {
16117            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16118            return null;
16119        } catch (IOException ioe) {
16120            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16121            return null;
16122        }
16123    }
16124
16125    /*
16126     * Update media status on PackageManager.
16127     */
16128    @Override
16129    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16130        int callingUid = Binder.getCallingUid();
16131        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16132            throw new SecurityException("Media status can only be updated by the system");
16133        }
16134        // reader; this apparently protects mMediaMounted, but should probably
16135        // be a different lock in that case.
16136        synchronized (mPackages) {
16137            Log.i(TAG, "Updating external media status from "
16138                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16139                    + (mediaStatus ? "mounted" : "unmounted"));
16140            if (DEBUG_SD_INSTALL)
16141                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16142                        + ", mMediaMounted=" + mMediaMounted);
16143            if (mediaStatus == mMediaMounted) {
16144                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16145                        : 0, -1);
16146                mHandler.sendMessage(msg);
16147                return;
16148            }
16149            mMediaMounted = mediaStatus;
16150        }
16151        // Queue up an async operation since the package installation may take a
16152        // little while.
16153        mHandler.post(new Runnable() {
16154            public void run() {
16155                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16156            }
16157        });
16158    }
16159
16160    /**
16161     * Called by MountService when the initial ASECs to scan are available.
16162     * Should block until all the ASEC containers are finished being scanned.
16163     */
16164    public void scanAvailableAsecs() {
16165        updateExternalMediaStatusInner(true, false, false);
16166        if (mShouldRestoreconData) {
16167            SELinuxMMAC.setRestoreconDone();
16168            mShouldRestoreconData = false;
16169        }
16170    }
16171
16172    /*
16173     * Collect information of applications on external media, map them against
16174     * existing containers and update information based on current mount status.
16175     * Please note that we always have to report status if reportStatus has been
16176     * set to true especially when unloading packages.
16177     */
16178    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16179            boolean externalStorage) {
16180        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16181        int[] uidArr = EmptyArray.INT;
16182
16183        final String[] list = PackageHelper.getSecureContainerList();
16184        if (ArrayUtils.isEmpty(list)) {
16185            Log.i(TAG, "No secure containers found");
16186        } else {
16187            // Process list of secure containers and categorize them
16188            // as active or stale based on their package internal state.
16189
16190            // reader
16191            synchronized (mPackages) {
16192                for (String cid : list) {
16193                    // Leave stages untouched for now; installer service owns them
16194                    if (PackageInstallerService.isStageName(cid)) continue;
16195
16196                    if (DEBUG_SD_INSTALL)
16197                        Log.i(TAG, "Processing container " + cid);
16198                    String pkgName = getAsecPackageName(cid);
16199                    if (pkgName == null) {
16200                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16201                        continue;
16202                    }
16203                    if (DEBUG_SD_INSTALL)
16204                        Log.i(TAG, "Looking for pkg : " + pkgName);
16205
16206                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16207                    if (ps == null) {
16208                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16209                        continue;
16210                    }
16211
16212                    /*
16213                     * Skip packages that are not external if we're unmounting
16214                     * external storage.
16215                     */
16216                    if (externalStorage && !isMounted && !isExternal(ps)) {
16217                        continue;
16218                    }
16219
16220                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16221                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16222                    // The package status is changed only if the code path
16223                    // matches between settings and the container id.
16224                    if (ps.codePathString != null
16225                            && ps.codePathString.startsWith(args.getCodePath())) {
16226                        if (DEBUG_SD_INSTALL) {
16227                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16228                                    + " at code path: " + ps.codePathString);
16229                        }
16230
16231                        // We do have a valid package installed on sdcard
16232                        processCids.put(args, ps.codePathString);
16233                        final int uid = ps.appId;
16234                        if (uid != -1) {
16235                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16236                        }
16237                    } else {
16238                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16239                                + ps.codePathString);
16240                    }
16241                }
16242            }
16243
16244            Arrays.sort(uidArr);
16245        }
16246
16247        // Process packages with valid entries.
16248        if (isMounted) {
16249            if (DEBUG_SD_INSTALL)
16250                Log.i(TAG, "Loading packages");
16251            loadMediaPackages(processCids, uidArr, externalStorage);
16252            startCleaningPackages();
16253            mInstallerService.onSecureContainersAvailable();
16254        } else {
16255            if (DEBUG_SD_INSTALL)
16256                Log.i(TAG, "Unloading packages");
16257            unloadMediaPackages(processCids, uidArr, reportStatus);
16258        }
16259    }
16260
16261    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16262            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16263        final int size = infos.size();
16264        final String[] packageNames = new String[size];
16265        final int[] packageUids = new int[size];
16266        for (int i = 0; i < size; i++) {
16267            final ApplicationInfo info = infos.get(i);
16268            packageNames[i] = info.packageName;
16269            packageUids[i] = info.uid;
16270        }
16271        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16272                finishedReceiver);
16273    }
16274
16275    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16276            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16277        sendResourcesChangedBroadcast(mediaStatus, replacing,
16278                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16279    }
16280
16281    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16282            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16283        int size = pkgList.length;
16284        if (size > 0) {
16285            // Send broadcasts here
16286            Bundle extras = new Bundle();
16287            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16288            if (uidArr != null) {
16289                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16290            }
16291            if (replacing) {
16292                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16293            }
16294            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16295                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16296            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16297        }
16298    }
16299
16300   /*
16301     * Look at potentially valid container ids from processCids If package
16302     * information doesn't match the one on record or package scanning fails,
16303     * the cid is added to list of removeCids. We currently don't delete stale
16304     * containers.
16305     */
16306    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16307            boolean externalStorage) {
16308        ArrayList<String> pkgList = new ArrayList<String>();
16309        Set<AsecInstallArgs> keys = processCids.keySet();
16310
16311        for (AsecInstallArgs args : keys) {
16312            String codePath = processCids.get(args);
16313            if (DEBUG_SD_INSTALL)
16314                Log.i(TAG, "Loading container : " + args.cid);
16315            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16316            try {
16317                // Make sure there are no container errors first.
16318                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16319                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16320                            + " when installing from sdcard");
16321                    continue;
16322                }
16323                // Check code path here.
16324                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16325                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16326                            + " does not match one in settings " + codePath);
16327                    continue;
16328                }
16329                // Parse package
16330                int parseFlags = mDefParseFlags;
16331                if (args.isExternalAsec()) {
16332                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16333                }
16334                if (args.isFwdLocked()) {
16335                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16336                }
16337
16338                synchronized (mInstallLock) {
16339                    PackageParser.Package pkg = null;
16340                    try {
16341                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16342                    } catch (PackageManagerException e) {
16343                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16344                    }
16345                    // Scan the package
16346                    if (pkg != null) {
16347                        /*
16348                         * TODO why is the lock being held? doPostInstall is
16349                         * called in other places without the lock. This needs
16350                         * to be straightened out.
16351                         */
16352                        // writer
16353                        synchronized (mPackages) {
16354                            retCode = PackageManager.INSTALL_SUCCEEDED;
16355                            pkgList.add(pkg.packageName);
16356                            // Post process args
16357                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16358                                    pkg.applicationInfo.uid);
16359                        }
16360                    } else {
16361                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16362                    }
16363                }
16364
16365            } finally {
16366                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16367                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16368                }
16369            }
16370        }
16371        // writer
16372        synchronized (mPackages) {
16373            // If the platform SDK has changed since the last time we booted,
16374            // we need to re-grant app permission to catch any new ones that
16375            // appear. This is really a hack, and means that apps can in some
16376            // cases get permissions that the user didn't initially explicitly
16377            // allow... it would be nice to have some better way to handle
16378            // this situation.
16379            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16380                    : mSettings.getInternalVersion();
16381            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16382                    : StorageManager.UUID_PRIVATE_INTERNAL;
16383
16384            int updateFlags = UPDATE_PERMISSIONS_ALL;
16385            if (ver.sdkVersion != mSdkVersion) {
16386                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16387                        + mSdkVersion + "; regranting permissions for external");
16388                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16389            }
16390            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16391
16392            // Yay, everything is now upgraded
16393            ver.forceCurrent();
16394
16395            // can downgrade to reader
16396            // Persist settings
16397            mSettings.writeLPr();
16398        }
16399        // Send a broadcast to let everyone know we are done processing
16400        if (pkgList.size() > 0) {
16401            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16402        }
16403    }
16404
16405   /*
16406     * Utility method to unload a list of specified containers
16407     */
16408    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16409        // Just unmount all valid containers.
16410        for (AsecInstallArgs arg : cidArgs) {
16411            synchronized (mInstallLock) {
16412                arg.doPostDeleteLI(false);
16413           }
16414       }
16415   }
16416
16417    /*
16418     * Unload packages mounted on external media. This involves deleting package
16419     * data from internal structures, sending broadcasts about diabled packages,
16420     * gc'ing to free up references, unmounting all secure containers
16421     * corresponding to packages on external media, and posting a
16422     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16423     * that we always have to post this message if status has been requested no
16424     * matter what.
16425     */
16426    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16427            final boolean reportStatus) {
16428        if (DEBUG_SD_INSTALL)
16429            Log.i(TAG, "unloading media packages");
16430        ArrayList<String> pkgList = new ArrayList<String>();
16431        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16432        final Set<AsecInstallArgs> keys = processCids.keySet();
16433        for (AsecInstallArgs args : keys) {
16434            String pkgName = args.getPackageName();
16435            if (DEBUG_SD_INSTALL)
16436                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16437            // Delete package internally
16438            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16439            synchronized (mInstallLock) {
16440                boolean res = deletePackageLI(pkgName, null, false, null, null,
16441                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16442                if (res) {
16443                    pkgList.add(pkgName);
16444                } else {
16445                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16446                    failedList.add(args);
16447                }
16448            }
16449        }
16450
16451        // reader
16452        synchronized (mPackages) {
16453            // We didn't update the settings after removing each package;
16454            // write them now for all packages.
16455            mSettings.writeLPr();
16456        }
16457
16458        // We have to absolutely send UPDATED_MEDIA_STATUS only
16459        // after confirming that all the receivers processed the ordered
16460        // broadcast when packages get disabled, force a gc to clean things up.
16461        // and unload all the containers.
16462        if (pkgList.size() > 0) {
16463            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16464                    new IIntentReceiver.Stub() {
16465                public void performReceive(Intent intent, int resultCode, String data,
16466                        Bundle extras, boolean ordered, boolean sticky,
16467                        int sendingUser) throws RemoteException {
16468                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16469                            reportStatus ? 1 : 0, 1, keys);
16470                    mHandler.sendMessage(msg);
16471                }
16472            });
16473        } else {
16474            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16475                    keys);
16476            mHandler.sendMessage(msg);
16477        }
16478    }
16479
16480    private void loadPrivatePackages(final VolumeInfo vol) {
16481        mHandler.post(new Runnable() {
16482            @Override
16483            public void run() {
16484                loadPrivatePackagesInner(vol);
16485            }
16486        });
16487    }
16488
16489    private void loadPrivatePackagesInner(VolumeInfo vol) {
16490        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16491        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16492
16493        final VersionInfo ver;
16494        final List<PackageSetting> packages;
16495        synchronized (mPackages) {
16496            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16497            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16498        }
16499
16500        for (PackageSetting ps : packages) {
16501            synchronized (mInstallLock) {
16502                final PackageParser.Package pkg;
16503                try {
16504                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16505                    loaded.add(pkg.applicationInfo);
16506                } catch (PackageManagerException e) {
16507                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16508                }
16509
16510                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16511                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16512                }
16513            }
16514        }
16515
16516        synchronized (mPackages) {
16517            int updateFlags = UPDATE_PERMISSIONS_ALL;
16518            if (ver.sdkVersion != mSdkVersion) {
16519                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16520                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16521                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16522            }
16523            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16524
16525            // Yay, everything is now upgraded
16526            ver.forceCurrent();
16527
16528            mSettings.writeLPr();
16529        }
16530
16531        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16532        sendResourcesChangedBroadcast(true, false, loaded, null);
16533    }
16534
16535    private void unloadPrivatePackages(final VolumeInfo vol) {
16536        mHandler.post(new Runnable() {
16537            @Override
16538            public void run() {
16539                unloadPrivatePackagesInner(vol);
16540            }
16541        });
16542    }
16543
16544    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16545        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16546        synchronized (mInstallLock) {
16547        synchronized (mPackages) {
16548            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16549            for (PackageSetting ps : packages) {
16550                if (ps.pkg == null) continue;
16551
16552                final ApplicationInfo info = ps.pkg.applicationInfo;
16553                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16554                if (deletePackageLI(ps.name, null, false, null, null,
16555                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16556                    unloaded.add(info);
16557                } else {
16558                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16559                }
16560            }
16561
16562            mSettings.writeLPr();
16563        }
16564        }
16565
16566        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16567        sendResourcesChangedBroadcast(false, false, unloaded, null);
16568    }
16569
16570    /**
16571     * Examine all users present on given mounted volume, and destroy data
16572     * belonging to users that are no longer valid, or whose user ID has been
16573     * recycled.
16574     */
16575    private void reconcileUsers(String volumeUuid) {
16576        final File[] files = FileUtils
16577                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16578        for (File file : files) {
16579            if (!file.isDirectory()) continue;
16580
16581            final int userId;
16582            final UserInfo info;
16583            try {
16584                userId = Integer.parseInt(file.getName());
16585                info = sUserManager.getUserInfo(userId);
16586            } catch (NumberFormatException e) {
16587                Slog.w(TAG, "Invalid user directory " + file);
16588                continue;
16589            }
16590
16591            boolean destroyUser = false;
16592            if (info == null) {
16593                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16594                        + " because no matching user was found");
16595                destroyUser = true;
16596            } else {
16597                try {
16598                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16599                } catch (IOException e) {
16600                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16601                            + " because we failed to enforce serial number: " + e);
16602                    destroyUser = true;
16603                }
16604            }
16605
16606            if (destroyUser) {
16607                synchronized (mInstallLock) {
16608                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16609                }
16610            }
16611        }
16612
16613        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16614        final UserManager um = mContext.getSystemService(UserManager.class);
16615        for (UserInfo user : um.getUsers()) {
16616            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16617            if (userDir.exists()) continue;
16618
16619            try {
16620                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16621                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16622            } catch (IOException e) {
16623                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16624            }
16625        }
16626    }
16627
16628    /**
16629     * Examine all apps present on given mounted volume, and destroy apps that
16630     * aren't expected, either due to uninstallation or reinstallation on
16631     * another volume.
16632     */
16633    private void reconcileApps(String volumeUuid) {
16634        final File[] files = FileUtils
16635                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16636        for (File file : files) {
16637            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16638                    && !PackageInstallerService.isStageName(file.getName());
16639            if (!isPackage) {
16640                // Ignore entries which are not packages
16641                continue;
16642            }
16643
16644            boolean destroyApp = false;
16645            String packageName = null;
16646            try {
16647                final PackageLite pkg = PackageParser.parsePackageLite(file,
16648                        PackageParser.PARSE_MUST_BE_APK);
16649                packageName = pkg.packageName;
16650
16651                synchronized (mPackages) {
16652                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16653                    if (ps == null) {
16654                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16655                                + volumeUuid + " because we found no install record");
16656                        destroyApp = true;
16657                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16658                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16659                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16660                        destroyApp = true;
16661                    }
16662                }
16663
16664            } catch (PackageParserException e) {
16665                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16666                destroyApp = true;
16667            }
16668
16669            if (destroyApp) {
16670                synchronized (mInstallLock) {
16671                    if (packageName != null) {
16672                        removeDataDirsLI(volumeUuid, packageName);
16673                    }
16674                    if (file.isDirectory()) {
16675                        mInstaller.rmPackageDir(file.getAbsolutePath());
16676                    } else {
16677                        file.delete();
16678                    }
16679                }
16680            }
16681        }
16682    }
16683
16684    private void unfreezePackage(String packageName) {
16685        synchronized (mPackages) {
16686            final PackageSetting ps = mSettings.mPackages.get(packageName);
16687            if (ps != null) {
16688                ps.frozen = false;
16689            }
16690        }
16691    }
16692
16693    @Override
16694    public int movePackage(final String packageName, final String volumeUuid) {
16695        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16696
16697        final int moveId = mNextMoveId.getAndIncrement();
16698        mHandler.post(new Runnable() {
16699            @Override
16700            public void run() {
16701                try {
16702                    movePackageInternal(packageName, volumeUuid, moveId);
16703                } catch (PackageManagerException e) {
16704                    Slog.w(TAG, "Failed to move " + packageName, e);
16705                    mMoveCallbacks.notifyStatusChanged(moveId,
16706                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16707                }
16708            }
16709        });
16710        return moveId;
16711    }
16712
16713    private void movePackageInternal(final String packageName, final String volumeUuid,
16714            final int moveId) throws PackageManagerException {
16715        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16716        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16717        final PackageManager pm = mContext.getPackageManager();
16718
16719        final boolean currentAsec;
16720        final String currentVolumeUuid;
16721        final File codeFile;
16722        final String installerPackageName;
16723        final String packageAbiOverride;
16724        final int appId;
16725        final String seinfo;
16726        final String label;
16727
16728        // reader
16729        synchronized (mPackages) {
16730            final PackageParser.Package pkg = mPackages.get(packageName);
16731            final PackageSetting ps = mSettings.mPackages.get(packageName);
16732            if (pkg == null || ps == null) {
16733                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16734            }
16735
16736            if (pkg.applicationInfo.isSystemApp()) {
16737                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16738                        "Cannot move system application");
16739            }
16740
16741            if (pkg.applicationInfo.isExternalAsec()) {
16742                currentAsec = true;
16743                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16744            } else if (pkg.applicationInfo.isForwardLocked()) {
16745                currentAsec = true;
16746                currentVolumeUuid = "forward_locked";
16747            } else {
16748                currentAsec = false;
16749                currentVolumeUuid = ps.volumeUuid;
16750
16751                final File probe = new File(pkg.codePath);
16752                final File probeOat = new File(probe, "oat");
16753                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16754                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16755                            "Move only supported for modern cluster style installs");
16756                }
16757            }
16758
16759            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16760                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16761                        "Package already moved to " + volumeUuid);
16762            }
16763
16764            if (ps.frozen) {
16765                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16766                        "Failed to move already frozen package");
16767            }
16768            ps.frozen = true;
16769
16770            codeFile = new File(pkg.codePath);
16771            installerPackageName = ps.installerPackageName;
16772            packageAbiOverride = ps.cpuAbiOverrideString;
16773            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16774            seinfo = pkg.applicationInfo.seinfo;
16775            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16776        }
16777
16778        // Now that we're guarded by frozen state, kill app during move
16779        final long token = Binder.clearCallingIdentity();
16780        try {
16781            killApplication(packageName, appId, "move pkg");
16782        } finally {
16783            Binder.restoreCallingIdentity(token);
16784        }
16785
16786        final Bundle extras = new Bundle();
16787        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16788        extras.putString(Intent.EXTRA_TITLE, label);
16789        mMoveCallbacks.notifyCreated(moveId, extras);
16790
16791        int installFlags;
16792        final boolean moveCompleteApp;
16793        final File measurePath;
16794
16795        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16796            installFlags = INSTALL_INTERNAL;
16797            moveCompleteApp = !currentAsec;
16798            measurePath = Environment.getDataAppDirectory(volumeUuid);
16799        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16800            installFlags = INSTALL_EXTERNAL;
16801            moveCompleteApp = false;
16802            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16803        } else {
16804            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16805            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16806                    || !volume.isMountedWritable()) {
16807                unfreezePackage(packageName);
16808                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16809                        "Move location not mounted private volume");
16810            }
16811
16812            Preconditions.checkState(!currentAsec);
16813
16814            installFlags = INSTALL_INTERNAL;
16815            moveCompleteApp = true;
16816            measurePath = Environment.getDataAppDirectory(volumeUuid);
16817        }
16818
16819        final PackageStats stats = new PackageStats(null, -1);
16820        synchronized (mInstaller) {
16821            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16822                unfreezePackage(packageName);
16823                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16824                        "Failed to measure package size");
16825            }
16826        }
16827
16828        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16829                + stats.dataSize);
16830
16831        final long startFreeBytes = measurePath.getFreeSpace();
16832        final long sizeBytes;
16833        if (moveCompleteApp) {
16834            sizeBytes = stats.codeSize + stats.dataSize;
16835        } else {
16836            sizeBytes = stats.codeSize;
16837        }
16838
16839        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16840            unfreezePackage(packageName);
16841            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16842                    "Not enough free space to move");
16843        }
16844
16845        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16846
16847        final CountDownLatch installedLatch = new CountDownLatch(1);
16848        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16849            @Override
16850            public void onUserActionRequired(Intent intent) throws RemoteException {
16851                throw new IllegalStateException();
16852            }
16853
16854            @Override
16855            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16856                    Bundle extras) throws RemoteException {
16857                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16858                        + PackageManager.installStatusToString(returnCode, msg));
16859
16860                installedLatch.countDown();
16861
16862                // Regardless of success or failure of the move operation,
16863                // always unfreeze the package
16864                unfreezePackage(packageName);
16865
16866                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16867                switch (status) {
16868                    case PackageInstaller.STATUS_SUCCESS:
16869                        mMoveCallbacks.notifyStatusChanged(moveId,
16870                                PackageManager.MOVE_SUCCEEDED);
16871                        break;
16872                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16873                        mMoveCallbacks.notifyStatusChanged(moveId,
16874                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16875                        break;
16876                    default:
16877                        mMoveCallbacks.notifyStatusChanged(moveId,
16878                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16879                        break;
16880                }
16881            }
16882        };
16883
16884        final MoveInfo move;
16885        if (moveCompleteApp) {
16886            // Kick off a thread to report progress estimates
16887            new Thread() {
16888                @Override
16889                public void run() {
16890                    while (true) {
16891                        try {
16892                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16893                                break;
16894                            }
16895                        } catch (InterruptedException ignored) {
16896                        }
16897
16898                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16899                        final int progress = 10 + (int) MathUtils.constrain(
16900                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16901                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16902                    }
16903                }
16904            }.start();
16905
16906            final String dataAppName = codeFile.getName();
16907            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16908                    dataAppName, appId, seinfo);
16909        } else {
16910            move = null;
16911        }
16912
16913        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16914
16915        final Message msg = mHandler.obtainMessage(INIT_COPY);
16916        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16917        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16918                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16919        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16920        msg.obj = params;
16921
16922        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16923                System.identityHashCode(msg.obj));
16924        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16925                System.identityHashCode(msg.obj));
16926
16927        mHandler.sendMessage(msg);
16928    }
16929
16930    @Override
16931    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16932        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16933
16934        final int realMoveId = mNextMoveId.getAndIncrement();
16935        final Bundle extras = new Bundle();
16936        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16937        mMoveCallbacks.notifyCreated(realMoveId, extras);
16938
16939        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16940            @Override
16941            public void onCreated(int moveId, Bundle extras) {
16942                // Ignored
16943            }
16944
16945            @Override
16946            public void onStatusChanged(int moveId, int status, long estMillis) {
16947                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16948            }
16949        };
16950
16951        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16952        storage.setPrimaryStorageUuid(volumeUuid, callback);
16953        return realMoveId;
16954    }
16955
16956    @Override
16957    public int getMoveStatus(int moveId) {
16958        mContext.enforceCallingOrSelfPermission(
16959                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16960        return mMoveCallbacks.mLastStatus.get(moveId);
16961    }
16962
16963    @Override
16964    public void registerMoveCallback(IPackageMoveObserver callback) {
16965        mContext.enforceCallingOrSelfPermission(
16966                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16967        mMoveCallbacks.register(callback);
16968    }
16969
16970    @Override
16971    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16972        mContext.enforceCallingOrSelfPermission(
16973                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16974        mMoveCallbacks.unregister(callback);
16975    }
16976
16977    @Override
16978    public boolean setInstallLocation(int loc) {
16979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16980                null);
16981        if (getInstallLocation() == loc) {
16982            return true;
16983        }
16984        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16985                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16986            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16987                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16988            return true;
16989        }
16990        return false;
16991   }
16992
16993    @Override
16994    public int getInstallLocation() {
16995        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16996                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16997                PackageHelper.APP_INSTALL_AUTO);
16998    }
16999
17000    /** Called by UserManagerService */
17001    void cleanUpUser(UserManagerService userManager, int userHandle) {
17002        synchronized (mPackages) {
17003            mDirtyUsers.remove(userHandle);
17004            mUserNeedsBadging.delete(userHandle);
17005            mSettings.removeUserLPw(userHandle);
17006            mPendingBroadcasts.remove(userHandle);
17007            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17008        }
17009        synchronized (mInstallLock) {
17010            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17011            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17012                final String volumeUuid = vol.getFsUuid();
17013                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17014                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17015            }
17016            synchronized (mPackages) {
17017                removeUnusedPackagesLILPw(userManager, userHandle);
17018            }
17019        }
17020    }
17021
17022    /**
17023     * We're removing userHandle and would like to remove any downloaded packages
17024     * that are no longer in use by any other user.
17025     * @param userHandle the user being removed
17026     */
17027    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17028        final boolean DEBUG_CLEAN_APKS = false;
17029        int [] users = userManager.getUserIds();
17030        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17031        while (psit.hasNext()) {
17032            PackageSetting ps = psit.next();
17033            if (ps.pkg == null) {
17034                continue;
17035            }
17036            final String packageName = ps.pkg.packageName;
17037            // Skip over if system app
17038            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17039                continue;
17040            }
17041            if (DEBUG_CLEAN_APKS) {
17042                Slog.i(TAG, "Checking package " + packageName);
17043            }
17044            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17045            if (keep) {
17046                if (DEBUG_CLEAN_APKS) {
17047                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17048                }
17049            } else {
17050                for (int i = 0; i < users.length; i++) {
17051                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17052                        keep = true;
17053                        if (DEBUG_CLEAN_APKS) {
17054                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17055                                    + users[i]);
17056                        }
17057                        break;
17058                    }
17059                }
17060            }
17061            if (!keep) {
17062                if (DEBUG_CLEAN_APKS) {
17063                    Slog.i(TAG, "  Removing package " + packageName);
17064                }
17065                mHandler.post(new Runnable() {
17066                    public void run() {
17067                        deletePackageX(packageName, userHandle, 0);
17068                    } //end run
17069                });
17070            }
17071        }
17072    }
17073
17074    /** Called by UserManagerService */
17075    void createNewUser(int userHandle) {
17076        synchronized (mInstallLock) {
17077            mInstaller.createUserConfig(userHandle);
17078            mSettings.createNewUserLI(this, mInstaller, userHandle);
17079        }
17080        synchronized (mPackages) {
17081            applyFactoryDefaultBrowserLPw(userHandle);
17082            primeDomainVerificationsLPw(userHandle);
17083        }
17084    }
17085
17086    void newUserCreated(final int userHandle) {
17087        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17088        // If permission review for legacy apps is required, we represent
17089        // dagerous permissions for such apps as always granted runtime
17090        // permissions to keep per user flag state whether review is needed.
17091        // Hence, if a new user is added we have to propagate dangerous
17092        // permission grants for these legacy apps.
17093        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17094            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17095                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17096        }
17097    }
17098
17099    @Override
17100    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17101        mContext.enforceCallingOrSelfPermission(
17102                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17103                "Only package verification agents can read the verifier device identity");
17104
17105        synchronized (mPackages) {
17106            return mSettings.getVerifierDeviceIdentityLPw();
17107        }
17108    }
17109
17110    @Override
17111    public void setPermissionEnforced(String permission, boolean enforced) {
17112        // TODO: Now that we no longer change GID for storage, this should to away.
17113        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17114                "setPermissionEnforced");
17115        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17116            synchronized (mPackages) {
17117                if (mSettings.mReadExternalStorageEnforced == null
17118                        || mSettings.mReadExternalStorageEnforced != enforced) {
17119                    mSettings.mReadExternalStorageEnforced = enforced;
17120                    mSettings.writeLPr();
17121                }
17122            }
17123            // kill any non-foreground processes so we restart them and
17124            // grant/revoke the GID.
17125            final IActivityManager am = ActivityManagerNative.getDefault();
17126            if (am != null) {
17127                final long token = Binder.clearCallingIdentity();
17128                try {
17129                    am.killProcessesBelowForeground("setPermissionEnforcement");
17130                } catch (RemoteException e) {
17131                } finally {
17132                    Binder.restoreCallingIdentity(token);
17133                }
17134            }
17135        } else {
17136            throw new IllegalArgumentException("No selective enforcement for " + permission);
17137        }
17138    }
17139
17140    @Override
17141    @Deprecated
17142    public boolean isPermissionEnforced(String permission) {
17143        return true;
17144    }
17145
17146    @Override
17147    public boolean isStorageLow() {
17148        final long token = Binder.clearCallingIdentity();
17149        try {
17150            final DeviceStorageMonitorInternal
17151                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17152            if (dsm != null) {
17153                return dsm.isMemoryLow();
17154            } else {
17155                return false;
17156            }
17157        } finally {
17158            Binder.restoreCallingIdentity(token);
17159        }
17160    }
17161
17162    @Override
17163    public IPackageInstaller getPackageInstaller() {
17164        return mInstallerService;
17165    }
17166
17167    private boolean userNeedsBadging(int userId) {
17168        int index = mUserNeedsBadging.indexOfKey(userId);
17169        if (index < 0) {
17170            final UserInfo userInfo;
17171            final long token = Binder.clearCallingIdentity();
17172            try {
17173                userInfo = sUserManager.getUserInfo(userId);
17174            } finally {
17175                Binder.restoreCallingIdentity(token);
17176            }
17177            final boolean b;
17178            if (userInfo != null && userInfo.isManagedProfile()) {
17179                b = true;
17180            } else {
17181                b = false;
17182            }
17183            mUserNeedsBadging.put(userId, b);
17184            return b;
17185        }
17186        return mUserNeedsBadging.valueAt(index);
17187    }
17188
17189    @Override
17190    public KeySet getKeySetByAlias(String packageName, String alias) {
17191        if (packageName == null || alias == null) {
17192            return null;
17193        }
17194        synchronized(mPackages) {
17195            final PackageParser.Package pkg = mPackages.get(packageName);
17196            if (pkg == null) {
17197                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17198                throw new IllegalArgumentException("Unknown package: " + packageName);
17199            }
17200            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17201            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17202        }
17203    }
17204
17205    @Override
17206    public KeySet getSigningKeySet(String packageName) {
17207        if (packageName == null) {
17208            return null;
17209        }
17210        synchronized(mPackages) {
17211            final PackageParser.Package pkg = mPackages.get(packageName);
17212            if (pkg == null) {
17213                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17214                throw new IllegalArgumentException("Unknown package: " + packageName);
17215            }
17216            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17217                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17218                throw new SecurityException("May not access signing KeySet of other apps.");
17219            }
17220            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17221            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17222        }
17223    }
17224
17225    @Override
17226    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17227        if (packageName == null || ks == null) {
17228            return false;
17229        }
17230        synchronized(mPackages) {
17231            final PackageParser.Package pkg = mPackages.get(packageName);
17232            if (pkg == null) {
17233                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17234                throw new IllegalArgumentException("Unknown package: " + packageName);
17235            }
17236            IBinder ksh = ks.getToken();
17237            if (ksh instanceof KeySetHandle) {
17238                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17239                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17240            }
17241            return false;
17242        }
17243    }
17244
17245    @Override
17246    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17247        if (packageName == null || ks == null) {
17248            return false;
17249        }
17250        synchronized(mPackages) {
17251            final PackageParser.Package pkg = mPackages.get(packageName);
17252            if (pkg == null) {
17253                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17254                throw new IllegalArgumentException("Unknown package: " + packageName);
17255            }
17256            IBinder ksh = ks.getToken();
17257            if (ksh instanceof KeySetHandle) {
17258                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17259                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17260            }
17261            return false;
17262        }
17263    }
17264
17265    private void deletePackageIfUnusedLPr(final String packageName) {
17266        PackageSetting ps = mSettings.mPackages.get(packageName);
17267        if (ps == null) {
17268            return;
17269        }
17270        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17271            // TODO Implement atomic delete if package is unused
17272            // It is currently possible that the package will be deleted even if it is installed
17273            // after this method returns.
17274            mHandler.post(new Runnable() {
17275                public void run() {
17276                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17277                }
17278            });
17279        }
17280    }
17281
17282    /**
17283     * Check and throw if the given before/after packages would be considered a
17284     * downgrade.
17285     */
17286    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17287            throws PackageManagerException {
17288        if (after.versionCode < before.mVersionCode) {
17289            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17290                    "Update version code " + after.versionCode + " is older than current "
17291                    + before.mVersionCode);
17292        } else if (after.versionCode == before.mVersionCode) {
17293            if (after.baseRevisionCode < before.baseRevisionCode) {
17294                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17295                        "Update base revision code " + after.baseRevisionCode
17296                        + " is older than current " + before.baseRevisionCode);
17297            }
17298
17299            if (!ArrayUtils.isEmpty(after.splitNames)) {
17300                for (int i = 0; i < after.splitNames.length; i++) {
17301                    final String splitName = after.splitNames[i];
17302                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17303                    if (j != -1) {
17304                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17305                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17306                                    "Update split " + splitName + " revision code "
17307                                    + after.splitRevisionCodes[i] + " is older than current "
17308                                    + before.splitRevisionCodes[j]);
17309                        }
17310                    }
17311                }
17312            }
17313        }
17314    }
17315
17316    private static class MoveCallbacks extends Handler {
17317        private static final int MSG_CREATED = 1;
17318        private static final int MSG_STATUS_CHANGED = 2;
17319
17320        private final RemoteCallbackList<IPackageMoveObserver>
17321                mCallbacks = new RemoteCallbackList<>();
17322
17323        private final SparseIntArray mLastStatus = new SparseIntArray();
17324
17325        public MoveCallbacks(Looper looper) {
17326            super(looper);
17327        }
17328
17329        public void register(IPackageMoveObserver callback) {
17330            mCallbacks.register(callback);
17331        }
17332
17333        public void unregister(IPackageMoveObserver callback) {
17334            mCallbacks.unregister(callback);
17335        }
17336
17337        @Override
17338        public void handleMessage(Message msg) {
17339            final SomeArgs args = (SomeArgs) msg.obj;
17340            final int n = mCallbacks.beginBroadcast();
17341            for (int i = 0; i < n; i++) {
17342                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17343                try {
17344                    invokeCallback(callback, msg.what, args);
17345                } catch (RemoteException ignored) {
17346                }
17347            }
17348            mCallbacks.finishBroadcast();
17349            args.recycle();
17350        }
17351
17352        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17353                throws RemoteException {
17354            switch (what) {
17355                case MSG_CREATED: {
17356                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17357                    break;
17358                }
17359                case MSG_STATUS_CHANGED: {
17360                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17361                    break;
17362                }
17363            }
17364        }
17365
17366        private void notifyCreated(int moveId, Bundle extras) {
17367            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17368
17369            final SomeArgs args = SomeArgs.obtain();
17370            args.argi1 = moveId;
17371            args.arg2 = extras;
17372            obtainMessage(MSG_CREATED, args).sendToTarget();
17373        }
17374
17375        private void notifyStatusChanged(int moveId, int status) {
17376            notifyStatusChanged(moveId, status, -1);
17377        }
17378
17379        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17380            Slog.v(TAG, "Move " + moveId + " status " + status);
17381
17382            final SomeArgs args = SomeArgs.obtain();
17383            args.argi1 = moveId;
17384            args.argi2 = status;
17385            args.arg3 = estMillis;
17386            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17387
17388            synchronized (mLastStatus) {
17389                mLastStatus.put(moveId, status);
17390            }
17391        }
17392    }
17393
17394    private final static class OnPermissionChangeListeners extends Handler {
17395        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17396
17397        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17398                new RemoteCallbackList<>();
17399
17400        public OnPermissionChangeListeners(Looper looper) {
17401            super(looper);
17402        }
17403
17404        @Override
17405        public void handleMessage(Message msg) {
17406            switch (msg.what) {
17407                case MSG_ON_PERMISSIONS_CHANGED: {
17408                    final int uid = msg.arg1;
17409                    handleOnPermissionsChanged(uid);
17410                } break;
17411            }
17412        }
17413
17414        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17415            mPermissionListeners.register(listener);
17416
17417        }
17418
17419        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17420            mPermissionListeners.unregister(listener);
17421        }
17422
17423        public void onPermissionsChanged(int uid) {
17424            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17425                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17426            }
17427        }
17428
17429        private void handleOnPermissionsChanged(int uid) {
17430            final int count = mPermissionListeners.beginBroadcast();
17431            try {
17432                for (int i = 0; i < count; i++) {
17433                    IOnPermissionsChangeListener callback = mPermissionListeners
17434                            .getBroadcastItem(i);
17435                    try {
17436                        callback.onPermissionsChanged(uid);
17437                    } catch (RemoteException e) {
17438                        Log.e(TAG, "Permission listener is dead", e);
17439                    }
17440                }
17441            } finally {
17442                mPermissionListeners.finishBroadcast();
17443            }
17444        }
17445    }
17446
17447    private class PackageManagerInternalImpl extends PackageManagerInternal {
17448        @Override
17449        public void setLocationPackagesProvider(PackagesProvider provider) {
17450            synchronized (mPackages) {
17451                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17452            }
17453        }
17454
17455        @Override
17456        public void setImePackagesProvider(PackagesProvider provider) {
17457            synchronized (mPackages) {
17458                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17459            }
17460        }
17461
17462        @Override
17463        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17464            synchronized (mPackages) {
17465                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17466            }
17467        }
17468
17469        @Override
17470        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17471            synchronized (mPackages) {
17472                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17473            }
17474        }
17475
17476        @Override
17477        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17478            synchronized (mPackages) {
17479                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17480            }
17481        }
17482
17483        @Override
17484        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17485            synchronized (mPackages) {
17486                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17487            }
17488        }
17489
17490        @Override
17491        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17492            synchronized (mPackages) {
17493                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17494            }
17495        }
17496
17497        @Override
17498        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17499            synchronized (mPackages) {
17500                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17501                        packageName, userId);
17502            }
17503        }
17504
17505        @Override
17506        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17507            synchronized (mPackages) {
17508                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17509                        packageName, userId);
17510            }
17511        }
17512
17513        @Override
17514        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17515            synchronized (mPackages) {
17516                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17517                        packageName, userId);
17518            }
17519        }
17520
17521        @Override
17522        public void setKeepUninstalledPackages(final List<String> packageList) {
17523            Preconditions.checkNotNull(packageList);
17524            List<String> removedFromList = null;
17525            synchronized (mPackages) {
17526                if (mKeepUninstalledPackages != null) {
17527                    final int packagesCount = mKeepUninstalledPackages.size();
17528                    for (int i = 0; i < packagesCount; i++) {
17529                        String oldPackage = mKeepUninstalledPackages.get(i);
17530                        if (packageList != null && packageList.contains(oldPackage)) {
17531                            continue;
17532                        }
17533                        if (removedFromList == null) {
17534                            removedFromList = new ArrayList<>();
17535                        }
17536                        removedFromList.add(oldPackage);
17537                    }
17538                }
17539                mKeepUninstalledPackages = new ArrayList<>(packageList);
17540                if (removedFromList != null) {
17541                    final int removedCount = removedFromList.size();
17542                    for (int i = 0; i < removedCount; i++) {
17543                        deletePackageIfUnusedLPr(removedFromList.get(i));
17544                    }
17545                }
17546            }
17547        }
17548
17549        @Override
17550        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17551            synchronized (mPackages) {
17552                // If we do not support permission review, done.
17553                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17554                    return false;
17555                }
17556
17557                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17558                if (packageSetting == null) {
17559                    return false;
17560                }
17561
17562                // Permission review applies only to apps not supporting the new permission model.
17563                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17564                    return false;
17565                }
17566
17567                // Legacy apps have the permission and get user consent on launch.
17568                PermissionsState permissionsState = packageSetting.getPermissionsState();
17569                return permissionsState.isPermissionReviewRequired(userId);
17570            }
17571        }
17572    }
17573
17574    @Override
17575    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17576        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17577        synchronized (mPackages) {
17578            final long identity = Binder.clearCallingIdentity();
17579            try {
17580                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17581                        packageNames, userId);
17582            } finally {
17583                Binder.restoreCallingIdentity(identity);
17584            }
17585        }
17586    }
17587
17588    private static void enforceSystemOrPhoneCaller(String tag) {
17589        int callingUid = Binder.getCallingUid();
17590        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17591            throw new SecurityException(
17592                    "Cannot call " + tag + " from UID " + callingUid);
17593        }
17594    }
17595}
17596