PackageManagerService.java revision c4dd021322d38ea32ac49930e904b6d08ce6490c
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_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
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;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
76import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
77import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
78import static com.android.internal.util.ArrayUtils.appendInt;
79import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
80import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
83import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
84import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
88
89import android.Manifest;
90import android.app.ActivityManager;
91import android.app.ActivityManagerNative;
92import android.app.AppGlobals;
93import android.app.IActivityManager;
94import android.app.admin.IDevicePolicyManager;
95import android.app.backup.IBackupManager;
96import android.content.BroadcastReceiver;
97import android.content.ComponentName;
98import android.content.Context;
99import android.content.IIntentReceiver;
100import android.content.Intent;
101import android.content.IntentFilter;
102import android.content.IntentSender;
103import android.content.IntentSender.SendIntentException;
104import android.content.ServiceConnection;
105import android.content.pm.ActivityInfo;
106import android.content.pm.ApplicationInfo;
107import android.content.pm.AppsQueryHelper;
108import android.content.pm.FeatureInfo;
109import android.content.pm.IOnPermissionsChangeListener;
110import android.content.pm.IPackageDataObserver;
111import android.content.pm.IPackageDeleteObserver;
112import android.content.pm.IPackageDeleteObserver2;
113import android.content.pm.IPackageInstallObserver2;
114import android.content.pm.IPackageInstaller;
115import android.content.pm.IPackageManager;
116import android.content.pm.IPackageMoveObserver;
117import android.content.pm.IPackageStatsObserver;
118import android.content.pm.InstrumentationInfo;
119import android.content.pm.IntentFilterVerificationInfo;
120import android.content.pm.KeySet;
121import android.content.pm.ManifestDigest;
122import android.content.pm.PackageCleanItem;
123import android.content.pm.PackageInfo;
124import android.content.pm.PackageInfoLite;
125import android.content.pm.PackageInstaller;
126import android.content.pm.PackageManager;
127import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
128import android.content.pm.PackageManagerInternal;
129import android.content.pm.PackageParser;
130import android.content.pm.PackageParser.ActivityIntentInfo;
131import android.content.pm.PackageParser.PackageLite;
132import android.content.pm.PackageParser.PackageParserException;
133import android.content.pm.PackageStats;
134import android.content.pm.PackageUserState;
135import android.content.pm.ParceledListSlice;
136import android.content.pm.PermissionGroupInfo;
137import android.content.pm.PermissionInfo;
138import android.content.pm.ProviderInfo;
139import android.content.pm.ResolveInfo;
140import android.content.pm.ServiceInfo;
141import android.content.pm.Signature;
142import android.content.pm.UserInfo;
143import android.content.pm.VerificationParams;
144import android.content.pm.VerifierDeviceIdentity;
145import android.content.pm.VerifierInfo;
146import android.content.res.Resources;
147import android.hardware.display.DisplayManager;
148import android.net.Uri;
149import android.os.Debug;
150import android.os.Binder;
151import android.os.Build;
152import android.os.Bundle;
153import android.os.Environment;
154import android.os.Environment.UserEnvironment;
155import android.os.FileUtils;
156import android.os.Handler;
157import android.os.IBinder;
158import android.os.Looper;
159import android.os.Message;
160import android.os.Parcel;
161import android.os.ParcelFileDescriptor;
162import android.os.Process;
163import android.os.RemoteCallbackList;
164import android.os.RemoteException;
165import android.os.ResultReceiver;
166import android.os.SELinux;
167import android.os.ServiceManager;
168import android.os.SystemClock;
169import android.os.SystemProperties;
170import android.os.Trace;
171import android.os.UserHandle;
172import android.os.UserManager;
173import android.os.storage.IMountService;
174import android.os.storage.MountServiceInternal;
175import android.os.storage.StorageEventListener;
176import android.os.storage.StorageManager;
177import android.os.storage.VolumeInfo;
178import android.os.storage.VolumeRecord;
179import android.security.KeyStore;
180import android.security.SystemKeyStore;
181import android.system.ErrnoException;
182import android.system.Os;
183import android.system.StructStat;
184import android.text.TextUtils;
185import android.text.format.DateUtils;
186import android.util.ArrayMap;
187import android.util.ArraySet;
188import android.util.AtomicFile;
189import android.util.DisplayMetrics;
190import android.util.EventLog;
191import android.util.ExceptionUtils;
192import android.util.Log;
193import android.util.LogPrinter;
194import android.util.MathUtils;
195import android.util.PrintStreamPrinter;
196import android.util.Slog;
197import android.util.SparseArray;
198import android.util.SparseBooleanArray;
199import android.util.SparseIntArray;
200import android.util.Xml;
201import android.view.Display;
202
203import dalvik.system.DexFile;
204import dalvik.system.VMRuntime;
205
206import libcore.io.IoUtils;
207import libcore.util.EmptyArray;
208
209import com.android.internal.R;
210import com.android.internal.annotations.GuardedBy;
211import com.android.internal.app.EphemeralResolveInfo;
212import com.android.internal.app.IMediaContainerService;
213import com.android.internal.app.ResolverActivity;
214import com.android.internal.content.NativeLibraryHelper;
215import com.android.internal.content.PackageHelper;
216import com.android.internal.os.IParcelFileDescriptorFactory;
217import com.android.internal.os.SomeArgs;
218import com.android.internal.os.Zygote;
219import com.android.internal.util.ArrayUtils;
220import com.android.internal.util.FastPrintWriter;
221import com.android.internal.util.FastXmlSerializer;
222import com.android.internal.util.IndentingPrintWriter;
223import com.android.internal.util.Preconditions;
224import com.android.server.EventLogTags;
225import com.android.server.FgThread;
226import com.android.server.IntentResolver;
227import com.android.server.LocalServices;
228import com.android.server.ServiceThread;
229import com.android.server.SystemConfig;
230import com.android.server.Watchdog;
231import com.android.server.pm.PermissionsState.PermissionState;
232import com.android.server.pm.Settings.DatabaseVersion;
233import com.android.server.pm.Settings.VersionInfo;
234import com.android.server.storage.DeviceStorageMonitorInternal;
235
236import org.xmlpull.v1.XmlPullParser;
237import org.xmlpull.v1.XmlPullParserException;
238import org.xmlpull.v1.XmlSerializer;
239
240import java.io.BufferedInputStream;
241import java.io.BufferedOutputStream;
242import java.io.BufferedReader;
243import java.io.ByteArrayInputStream;
244import java.io.ByteArrayOutputStream;
245import java.io.File;
246import java.io.FileDescriptor;
247import java.io.FileNotFoundException;
248import java.io.FileOutputStream;
249import java.io.FileReader;
250import java.io.FilenameFilter;
251import java.io.IOException;
252import java.io.InputStream;
253import java.io.PrintWriter;
254import java.nio.charset.StandardCharsets;
255import java.security.MessageDigest;
256import java.security.NoSuchAlgorithmException;
257import java.security.PublicKey;
258import java.security.cert.CertificateEncodingException;
259import java.security.cert.CertificateException;
260import java.text.SimpleDateFormat;
261import java.util.ArrayList;
262import java.util.Arrays;
263import java.util.Collection;
264import java.util.Collections;
265import java.util.Comparator;
266import java.util.Date;
267import java.util.Iterator;
268import java.util.List;
269import java.util.Map;
270import java.util.Objects;
271import java.util.Set;
272import java.util.concurrent.CountDownLatch;
273import java.util.concurrent.TimeUnit;
274import java.util.concurrent.atomic.AtomicBoolean;
275import java.util.concurrent.atomic.AtomicInteger;
276import java.util.concurrent.atomic.AtomicLong;
277
278/**
279 * Keep track of all those .apks everywhere.
280 *
281 * This is very central to the platform's security; please run the unit
282 * tests whenever making modifications here:
283 *
284runtest -c android.content.pm.PackageManagerTests frameworks-core
285 *
286 * {@hide}
287 */
288public class PackageManagerService extends IPackageManager.Stub {
289    static final String TAG = "PackageManager";
290    static final boolean DEBUG_SETTINGS = false;
291    static final boolean DEBUG_PREFERRED = false;
292    static final boolean DEBUG_UPGRADE = false;
293    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
294    private static final boolean DEBUG_BACKUP = false;
295    private static final boolean DEBUG_INSTALL = false;
296    private static final boolean DEBUG_REMOVE = false;
297    private static final boolean DEBUG_BROADCASTS = false;
298    private static final boolean DEBUG_SHOW_INFO = false;
299    private static final boolean DEBUG_PACKAGE_INFO = false;
300    private static final boolean DEBUG_INTENT_MATCHING = false;
301    private static final boolean DEBUG_PACKAGE_SCANNING = false;
302    private static final boolean DEBUG_VERIFY = false;
303    private static final boolean DEBUG_DEXOPT = false;
304    private static final boolean DEBUG_ABI_SELECTION = false;
305    private static final boolean DEBUG_EPHEMERAL = false;
306
307    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
308
309    private static final int RADIO_UID = Process.PHONE_UID;
310    private static final int LOG_UID = Process.LOG_UID;
311    private static final int NFC_UID = Process.NFC_UID;
312    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
313    private static final int SHELL_UID = Process.SHELL_UID;
314
315    // Cap the size of permission trees that 3rd party apps can define
316    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
317
318    // Suffix used during package installation when copying/moving
319    // package apks to install directory.
320    private static final String INSTALL_PACKAGE_SUFFIX = "-";
321
322    static final int SCAN_NO_DEX = 1<<1;
323    static final int SCAN_FORCE_DEX = 1<<2;
324    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
325    static final int SCAN_NEW_INSTALL = 1<<4;
326    static final int SCAN_NO_PATHS = 1<<5;
327    static final int SCAN_UPDATE_TIME = 1<<6;
328    static final int SCAN_DEFER_DEX = 1<<7;
329    static final int SCAN_BOOTING = 1<<8;
330    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
331    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
332    static final int SCAN_REPLACING = 1<<11;
333    static final int SCAN_REQUIRE_KNOWN = 1<<12;
334    static final int SCAN_MOVE = 1<<13;
335    static final int SCAN_INITIAL = 1<<14;
336
337    static final int REMOVE_CHATTY = 1<<16;
338
339    private static final int[] EMPTY_INT_ARRAY = new int[0];
340
341    /**
342     * Timeout (in milliseconds) after which the watchdog should declare that
343     * our handler thread is wedged.  The usual default for such things is one
344     * minute but we sometimes do very lengthy I/O operations on this thread,
345     * such as installing multi-gigabyte applications, so ours needs to be longer.
346     */
347    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
348
349    /**
350     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
351     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
352     * settings entry if available, otherwise we use the hardcoded default.  If it's been
353     * more than this long since the last fstrim, we force one during the boot sequence.
354     *
355     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
356     * one gets run at the next available charging+idle time.  This final mandatory
357     * no-fstrim check kicks in only of the other scheduling criteria is never met.
358     */
359    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
360
361    /**
362     * Whether verification is enabled by default.
363     */
364    private static final boolean DEFAULT_VERIFY_ENABLE = true;
365
366    /**
367     * The default maximum time to wait for the verification agent to return in
368     * milliseconds.
369     */
370    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
371
372    /**
373     * The default response for package verification timeout.
374     *
375     * This can be either PackageManager.VERIFICATION_ALLOW or
376     * PackageManager.VERIFICATION_REJECT.
377     */
378    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
379
380    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
381
382    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
383            DEFAULT_CONTAINER_PACKAGE,
384            "com.android.defcontainer.DefaultContainerService");
385
386    private static final String KILL_APP_REASON_GIDS_CHANGED =
387            "permission grant or revoke changed gids";
388
389    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
390            "permissions revoked";
391
392    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
393
394    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
395
396    /** Permission grant: not grant the permission. */
397    private static final int GRANT_DENIED = 1;
398
399    /** Permission grant: grant the permission as an install permission. */
400    private static final int GRANT_INSTALL = 2;
401
402    /** Permission grant: grant the permission as a runtime one. */
403    private static final int GRANT_RUNTIME = 3;
404
405    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
406    private static final int GRANT_UPGRADE = 4;
407
408    /** Canonical intent used to identify what counts as a "web browser" app */
409    private static final Intent sBrowserIntent;
410    static {
411        sBrowserIntent = new Intent();
412        sBrowserIntent.setAction(Intent.ACTION_VIEW);
413        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
414        sBrowserIntent.setData(Uri.parse("http:"));
415    }
416
417    final ServiceThread mHandlerThread;
418
419    final PackageHandler mHandler;
420
421    /**
422     * Messages for {@link #mHandler} that need to wait for system ready before
423     * being dispatched.
424     */
425    private ArrayList<Message> mPostSystemReadyMessages;
426
427    final int mSdkVersion = Build.VERSION.SDK_INT;
428
429    final Context mContext;
430    final boolean mFactoryTest;
431    final boolean mOnlyCore;
432    final DisplayMetrics mMetrics;
433    final int mDefParseFlags;
434    final String[] mSeparateProcesses;
435    final boolean mIsUpgrade;
436
437    // This is where all application persistent data goes.
438    final File mAppDataDir;
439
440    // This is where all application persistent data goes for secondary users.
441    final File mUserAppDataDir;
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    public static final class SharedLibraryEntry {
516        public final String path;
517        public final String apk;
518
519        SharedLibraryEntry(String _path, String _apk) {
520            path = _path;
521            apk = _apk;
522        }
523    }
524
525    // Currently known shared libraries.
526    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
527            new ArrayMap<String, SharedLibraryEntry>();
528
529    // All available activities, for your resolving pleasure.
530    final ActivityIntentResolver mActivities =
531            new ActivityIntentResolver();
532
533    // All available receivers, for your resolving pleasure.
534    final ActivityIntentResolver mReceivers =
535            new ActivityIntentResolver();
536
537    // All available services, for your resolving pleasure.
538    final ServiceIntentResolver mServices = new ServiceIntentResolver();
539
540    // All available providers, for your resolving pleasure.
541    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
542
543    // Mapping from provider base names (first directory in content URI codePath)
544    // to the provider information.
545    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
546            new ArrayMap<String, PackageParser.Provider>();
547
548    // Mapping from instrumentation class names to info about them.
549    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
550            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
551
552    // Mapping from permission names to info about them.
553    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
554            new ArrayMap<String, PackageParser.PermissionGroup>();
555
556    // Packages whose data we have transfered into another package, thus
557    // should no longer exist.
558    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
559
560    // Broadcast actions that are only available to the system.
561    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
562
563    /** List of packages waiting for verification. */
564    final SparseArray<PackageVerificationState> mPendingVerification
565            = new SparseArray<PackageVerificationState>();
566
567    /** Set of packages associated with each app op permission. */
568    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
569
570    final PackageInstallerService mInstallerService;
571
572    private final PackageDexOptimizer mPackageDexOptimizer;
573
574    private AtomicInteger mNextMoveId = new AtomicInteger();
575    private final MoveCallbacks mMoveCallbacks;
576
577    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
578
579    // Cache of users who need badging.
580    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
581
582    /** Token for keys in mPendingVerification. */
583    private int mPendingVerificationToken = 0;
584
585    volatile boolean mSystemReady;
586    volatile boolean mSafeMode;
587    volatile boolean mHasSystemUidErrors;
588
589    ApplicationInfo mAndroidApplication;
590    final ActivityInfo mResolveActivity = new ActivityInfo();
591    final ResolveInfo mResolveInfo = new ResolveInfo();
592    ComponentName mResolveComponentName;
593    PackageParser.Package mPlatformPackage;
594    ComponentName mCustomResolverComponentName;
595
596    boolean mResolverReplaced = false;
597
598    private final ComponentName mIntentFilterVerifierComponent;
599    private int mIntentFilterVerificationToken = 0;
600
601    /** Component that knows whether or not an ephemeral application exists */
602    final ComponentName mEphemeralResolverComponent;
603    /** The service connection to the ephemeral resolver */
604    final EphemeralResolverConnection mEphemeralResolverConnection;
605
606    /** Component used to install ephemeral applications */
607    final ComponentName mEphemeralInstallerComponent;
608    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
609    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
610
611    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
612            = new SparseArray<IntentFilterVerificationState>();
613
614    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
615            new DefaultPermissionGrantPolicy(this);
616
617    // List of packages names to keep cached, even if they are uninstalled for all users
618    private List<String> mKeepUninstalledPackages;
619
620    private static class IFVerificationParams {
621        PackageParser.Package pkg;
622        boolean replacing;
623        int userId;
624        int verifierUid;
625
626        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
627                int _userId, int _verifierUid) {
628            pkg = _pkg;
629            replacing = _replacing;
630            userId = _userId;
631            replacing = _replacing;
632            verifierUid = _verifierUid;
633        }
634    }
635
636    private interface IntentFilterVerifier<T extends IntentFilter> {
637        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
638                                               T filter, String packageName);
639        void startVerifications(int userId);
640        void receiveVerificationResponse(int verificationId);
641    }
642
643    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
644        private Context mContext;
645        private ComponentName mIntentFilterVerifierComponent;
646        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
647
648        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
649            mContext = context;
650            mIntentFilterVerifierComponent = verifierComponent;
651        }
652
653        private String getDefaultScheme() {
654            return IntentFilter.SCHEME_HTTPS;
655        }
656
657        @Override
658        public void startVerifications(int userId) {
659            // Launch verifications requests
660            int count = mCurrentIntentFilterVerifications.size();
661            for (int n=0; n<count; n++) {
662                int verificationId = mCurrentIntentFilterVerifications.get(n);
663                final IntentFilterVerificationState ivs =
664                        mIntentFilterVerificationStates.get(verificationId);
665
666                String packageName = ivs.getPackageName();
667
668                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
669                final int filterCount = filters.size();
670                ArraySet<String> domainsSet = new ArraySet<>();
671                for (int m=0; m<filterCount; m++) {
672                    PackageParser.ActivityIntentInfo filter = filters.get(m);
673                    domainsSet.addAll(filter.getHostsList());
674                }
675                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
676                synchronized (mPackages) {
677                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
678                            packageName, domainsList) != null) {
679                        scheduleWriteSettingsLocked();
680                    }
681                }
682                sendVerificationRequest(userId, verificationId, ivs);
683            }
684            mCurrentIntentFilterVerifications.clear();
685        }
686
687        private void sendVerificationRequest(int userId, int verificationId,
688                IntentFilterVerificationState ivs) {
689
690            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
691            verificationIntent.putExtra(
692                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
693                    verificationId);
694            verificationIntent.putExtra(
695                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
696                    getDefaultScheme());
697            verificationIntent.putExtra(
698                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
699                    ivs.getHostsString());
700            verificationIntent.putExtra(
701                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
702                    ivs.getPackageName());
703            verificationIntent.setComponent(mIntentFilterVerifierComponent);
704            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
705
706            UserHandle user = new UserHandle(userId);
707            mContext.sendBroadcastAsUser(verificationIntent, user);
708            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
709                    "Sending IntentFilter verification broadcast");
710        }
711
712        public void receiveVerificationResponse(int verificationId) {
713            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
714
715            final boolean verified = ivs.isVerified();
716
717            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
718            final int count = filters.size();
719            if (DEBUG_DOMAIN_VERIFICATION) {
720                Slog.i(TAG, "Received verification response " + verificationId
721                        + " for " + count + " filters, verified=" + verified);
722            }
723            for (int n=0; n<count; n++) {
724                PackageParser.ActivityIntentInfo filter = filters.get(n);
725                filter.setVerified(verified);
726
727                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
728                        + " verified with result:" + verified + " and hosts:"
729                        + ivs.getHostsString());
730            }
731
732            mIntentFilterVerificationStates.remove(verificationId);
733
734            final String packageName = ivs.getPackageName();
735            IntentFilterVerificationInfo ivi = null;
736
737            synchronized (mPackages) {
738                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
739            }
740            if (ivi == null) {
741                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
742                        + verificationId + " packageName:" + packageName);
743                return;
744            }
745            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
746                    "Updating IntentFilterVerificationInfo for package " + packageName
747                            +" verificationId:" + verificationId);
748
749            synchronized (mPackages) {
750                if (verified) {
751                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
752                } else {
753                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
754                }
755                scheduleWriteSettingsLocked();
756
757                final int userId = ivs.getUserId();
758                if (userId != UserHandle.USER_ALL) {
759                    final int userStatus =
760                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
761
762                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
763                    boolean needUpdate = false;
764
765                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
766                    // already been set by the User thru the Disambiguation dialog
767                    switch (userStatus) {
768                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
769                            if (verified) {
770                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
771                            } else {
772                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
773                            }
774                            needUpdate = true;
775                            break;
776
777                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
778                            if (verified) {
779                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
780                                needUpdate = true;
781                            }
782                            break;
783
784                        default:
785                            // Nothing to do
786                    }
787
788                    if (needUpdate) {
789                        mSettings.updateIntentFilterVerificationStatusLPw(
790                                packageName, updatedStatus, userId);
791                        scheduleWritePackageRestrictionsLocked(userId);
792                    }
793                }
794            }
795        }
796
797        @Override
798        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
799                    ActivityIntentInfo filter, String packageName) {
800            if (!hasValidDomains(filter)) {
801                return false;
802            }
803            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
804            if (ivs == null) {
805                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
806                        packageName);
807            }
808            if (DEBUG_DOMAIN_VERIFICATION) {
809                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
810            }
811            ivs.addFilter(filter);
812            return true;
813        }
814
815        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
816                int userId, int verificationId, String packageName) {
817            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
818                    verifierUid, userId, packageName);
819            ivs.setPendingState();
820            synchronized (mPackages) {
821                mIntentFilterVerificationStates.append(verificationId, ivs);
822                mCurrentIntentFilterVerifications.add(verificationId);
823            }
824            return ivs;
825        }
826    }
827
828    private static boolean hasValidDomains(ActivityIntentInfo filter) {
829        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
830                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
831                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
832    }
833
834    private IntentFilterVerifier mIntentFilterVerifier;
835
836    // Set of pending broadcasts for aggregating enable/disable of components.
837    static class PendingPackageBroadcasts {
838        // for each user id, a map of <package name -> components within that package>
839        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
840
841        public PendingPackageBroadcasts() {
842            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
843        }
844
845        public ArrayList<String> get(int userId, String packageName) {
846            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
847            return packages.get(packageName);
848        }
849
850        public void put(int userId, String packageName, ArrayList<String> components) {
851            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
852            packages.put(packageName, components);
853        }
854
855        public void remove(int userId, String packageName) {
856            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
857            if (packages != null) {
858                packages.remove(packageName);
859            }
860        }
861
862        public void remove(int userId) {
863            mUidMap.remove(userId);
864        }
865
866        public int userIdCount() {
867            return mUidMap.size();
868        }
869
870        public int userIdAt(int n) {
871            return mUidMap.keyAt(n);
872        }
873
874        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
875            return mUidMap.get(userId);
876        }
877
878        public int size() {
879            // total number of pending broadcast entries across all userIds
880            int num = 0;
881            for (int i = 0; i< mUidMap.size(); i++) {
882                num += mUidMap.valueAt(i).size();
883            }
884            return num;
885        }
886
887        public void clear() {
888            mUidMap.clear();
889        }
890
891        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
892            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
893            if (map == null) {
894                map = new ArrayMap<String, ArrayList<String>>();
895                mUidMap.put(userId, map);
896            }
897            return map;
898        }
899    }
900    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
901
902    // Service Connection to remote media container service to copy
903    // package uri's from external media onto secure containers
904    // or internal storage.
905    private IMediaContainerService mContainerService = null;
906
907    static final int SEND_PENDING_BROADCAST = 1;
908    static final int MCS_BOUND = 3;
909    static final int END_COPY = 4;
910    static final int INIT_COPY = 5;
911    static final int MCS_UNBIND = 6;
912    static final int START_CLEANING_PACKAGE = 7;
913    static final int FIND_INSTALL_LOC = 8;
914    static final int POST_INSTALL = 9;
915    static final int MCS_RECONNECT = 10;
916    static final int MCS_GIVE_UP = 11;
917    static final int UPDATED_MEDIA_STATUS = 12;
918    static final int WRITE_SETTINGS = 13;
919    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
920    static final int PACKAGE_VERIFIED = 15;
921    static final int CHECK_PENDING_VERIFICATION = 16;
922    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
923    static final int INTENT_FILTER_VERIFIED = 18;
924
925    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
926
927    // Delay time in millisecs
928    static final int BROADCAST_DELAY = 10 * 1000;
929
930    static UserManagerService sUserManager;
931
932    // Stores a list of users whose package restrictions file needs to be updated
933    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
934
935    final private DefaultContainerConnection mDefContainerConn =
936            new DefaultContainerConnection();
937    class DefaultContainerConnection implements ServiceConnection {
938        public void onServiceConnected(ComponentName name, IBinder service) {
939            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
940            IMediaContainerService imcs =
941                IMediaContainerService.Stub.asInterface(service);
942            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
943        }
944
945        public void onServiceDisconnected(ComponentName name) {
946            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
947        }
948    }
949
950    // Recordkeeping of restore-after-install operations that are currently in flight
951    // between the Package Manager and the Backup Manager
952    class PostInstallData {
953        public InstallArgs args;
954        public PackageInstalledInfo res;
955
956        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
957            args = _a;
958            res = _r;
959        }
960    }
961
962    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
963    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
964
965    // XML tags for backup/restore of various bits of state
966    private static final String TAG_PREFERRED_BACKUP = "pa";
967    private static final String TAG_DEFAULT_APPS = "da";
968    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
969
970    final String mRequiredVerifierPackage;
971    final String mRequiredInstallerPackage;
972
973    private final PackageUsage mPackageUsage = new PackageUsage();
974
975    private class PackageUsage {
976        private static final int WRITE_INTERVAL
977            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
978
979        private final Object mFileLock = new Object();
980        private final AtomicLong mLastWritten = new AtomicLong(0);
981        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
982
983        private boolean mIsHistoricalPackageUsageAvailable = true;
984
985        boolean isHistoricalPackageUsageAvailable() {
986            return mIsHistoricalPackageUsageAvailable;
987        }
988
989        void write(boolean force) {
990            if (force) {
991                writeInternal();
992                return;
993            }
994            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
995                && !DEBUG_DEXOPT) {
996                return;
997            }
998            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
999                new Thread("PackageUsage_DiskWriter") {
1000                    @Override
1001                    public void run() {
1002                        try {
1003                            writeInternal();
1004                        } finally {
1005                            mBackgroundWriteRunning.set(false);
1006                        }
1007                    }
1008                }.start();
1009            }
1010        }
1011
1012        private void writeInternal() {
1013            synchronized (mPackages) {
1014                synchronized (mFileLock) {
1015                    AtomicFile file = getFile();
1016                    FileOutputStream f = null;
1017                    try {
1018                        f = file.startWrite();
1019                        BufferedOutputStream out = new BufferedOutputStream(f);
1020                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1021                        StringBuilder sb = new StringBuilder();
1022                        for (PackageParser.Package pkg : mPackages.values()) {
1023                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1024                                continue;
1025                            }
1026                            sb.setLength(0);
1027                            sb.append(pkg.packageName);
1028                            sb.append(' ');
1029                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1030                            sb.append('\n');
1031                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1032                        }
1033                        out.flush();
1034                        file.finishWrite(f);
1035                    } catch (IOException e) {
1036                        if (f != null) {
1037                            file.failWrite(f);
1038                        }
1039                        Log.e(TAG, "Failed to write package usage times", e);
1040                    }
1041                }
1042            }
1043            mLastWritten.set(SystemClock.elapsedRealtime());
1044        }
1045
1046        void readLP() {
1047            synchronized (mFileLock) {
1048                AtomicFile file = getFile();
1049                BufferedInputStream in = null;
1050                try {
1051                    in = new BufferedInputStream(file.openRead());
1052                    StringBuffer sb = new StringBuffer();
1053                    while (true) {
1054                        String packageName = readToken(in, sb, ' ');
1055                        if (packageName == null) {
1056                            break;
1057                        }
1058                        String timeInMillisString = readToken(in, sb, '\n');
1059                        if (timeInMillisString == null) {
1060                            throw new IOException("Failed to find last usage time for package "
1061                                                  + packageName);
1062                        }
1063                        PackageParser.Package pkg = mPackages.get(packageName);
1064                        if (pkg == null) {
1065                            continue;
1066                        }
1067                        long timeInMillis;
1068                        try {
1069                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1070                        } catch (NumberFormatException e) {
1071                            throw new IOException("Failed to parse " + timeInMillisString
1072                                                  + " as a long.", e);
1073                        }
1074                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1075                    }
1076                } catch (FileNotFoundException expected) {
1077                    mIsHistoricalPackageUsageAvailable = false;
1078                } catch (IOException e) {
1079                    Log.w(TAG, "Failed to read package usage times", e);
1080                } finally {
1081                    IoUtils.closeQuietly(in);
1082                }
1083            }
1084            mLastWritten.set(SystemClock.elapsedRealtime());
1085        }
1086
1087        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1088                throws IOException {
1089            sb.setLength(0);
1090            while (true) {
1091                int ch = in.read();
1092                if (ch == -1) {
1093                    if (sb.length() == 0) {
1094                        return null;
1095                    }
1096                    throw new IOException("Unexpected EOF");
1097                }
1098                if (ch == endOfToken) {
1099                    return sb.toString();
1100                }
1101                sb.append((char)ch);
1102            }
1103        }
1104
1105        private AtomicFile getFile() {
1106            File dataDir = Environment.getDataDirectory();
1107            File systemDir = new File(dataDir, "system");
1108            File fname = new File(systemDir, "package-usage.list");
1109            return new AtomicFile(fname);
1110        }
1111    }
1112
1113    class PackageHandler extends Handler {
1114        private boolean mBound = false;
1115        final ArrayList<HandlerParams> mPendingInstalls =
1116            new ArrayList<HandlerParams>();
1117
1118        private boolean connectToService() {
1119            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1120                    " DefaultContainerService");
1121            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1124                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1125                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126                mBound = true;
1127                return true;
1128            }
1129            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1130            return false;
1131        }
1132
1133        private void disconnectService() {
1134            mContainerService = null;
1135            mBound = false;
1136            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1137            mContext.unbindService(mDefContainerConn);
1138            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1139        }
1140
1141        PackageHandler(Looper looper) {
1142            super(looper);
1143        }
1144
1145        public void handleMessage(Message msg) {
1146            try {
1147                doHandleMessage(msg);
1148            } finally {
1149                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1150            }
1151        }
1152
1153        void doHandleMessage(Message msg) {
1154            switch (msg.what) {
1155                case INIT_COPY: {
1156                    HandlerParams params = (HandlerParams) msg.obj;
1157                    int idx = mPendingInstalls.size();
1158                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1159                    // If a bind was already initiated we dont really
1160                    // need to do anything. The pending install
1161                    // will be processed later on.
1162                    if (!mBound) {
1163                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1164                                System.identityHashCode(mHandler));
1165                        // If this is the only one pending we might
1166                        // have to bind to the service again.
1167                        if (!connectToService()) {
1168                            Slog.e(TAG, "Failed to bind to media container service");
1169                            params.serviceError();
1170                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1171                                    System.identityHashCode(mHandler));
1172                            if (params.traceMethod != null) {
1173                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1174                                        params.traceCookie);
1175                            }
1176                            return;
1177                        } else {
1178                            // Once we bind to the service, the first
1179                            // pending request will be processed.
1180                            mPendingInstalls.add(idx, params);
1181                        }
1182                    } else {
1183                        mPendingInstalls.add(idx, params);
1184                        // Already bound to the service. Just make
1185                        // sure we trigger off processing the first request.
1186                        if (idx == 0) {
1187                            mHandler.sendEmptyMessage(MCS_BOUND);
1188                        }
1189                    }
1190                    break;
1191                }
1192                case MCS_BOUND: {
1193                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1194                    if (msg.obj != null) {
1195                        mContainerService = (IMediaContainerService) msg.obj;
1196                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1197                                System.identityHashCode(mHandler));
1198                    }
1199                    if (mContainerService == null) {
1200                        if (!mBound) {
1201                            // Something seriously wrong since we are not bound and we are not
1202                            // waiting for connection. Bail out.
1203                            Slog.e(TAG, "Cannot bind to media container service");
1204                            for (HandlerParams params : mPendingInstalls) {
1205                                // Indicate service bind error
1206                                params.serviceError();
1207                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1208                                        System.identityHashCode(params));
1209                                if (params.traceMethod != null) {
1210                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1211                                            params.traceMethod, params.traceCookie);
1212                                }
1213                                return;
1214                            }
1215                            mPendingInstalls.clear();
1216                        } else {
1217                            Slog.w(TAG, "Waiting to connect to media container service");
1218                        }
1219                    } else if (mPendingInstalls.size() > 0) {
1220                        HandlerParams params = mPendingInstalls.get(0);
1221                        if (params != null) {
1222                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1223                                    System.identityHashCode(params));
1224                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1225                            if (params.startCopy()) {
1226                                // We are done...  look for more work or to
1227                                // go idle.
1228                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1229                                        "Checking for more work or unbind...");
1230                                // Delete pending install
1231                                if (mPendingInstalls.size() > 0) {
1232                                    mPendingInstalls.remove(0);
1233                                }
1234                                if (mPendingInstalls.size() == 0) {
1235                                    if (mBound) {
1236                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1237                                                "Posting delayed MCS_UNBIND");
1238                                        removeMessages(MCS_UNBIND);
1239                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1240                                        // Unbind after a little delay, to avoid
1241                                        // continual thrashing.
1242                                        sendMessageDelayed(ubmsg, 10000);
1243                                    }
1244                                } else {
1245                                    // There are more pending requests in queue.
1246                                    // Just post MCS_BOUND message to trigger processing
1247                                    // of next pending install.
1248                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1249                                            "Posting MCS_BOUND for next work");
1250                                    mHandler.sendEmptyMessage(MCS_BOUND);
1251                                }
1252                            }
1253                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1254                        }
1255                    } else {
1256                        // Should never happen ideally.
1257                        Slog.w(TAG, "Empty queue");
1258                    }
1259                    break;
1260                }
1261                case MCS_RECONNECT: {
1262                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1263                    if (mPendingInstalls.size() > 0) {
1264                        if (mBound) {
1265                            disconnectService();
1266                        }
1267                        if (!connectToService()) {
1268                            Slog.e(TAG, "Failed to bind to media container service");
1269                            for (HandlerParams params : mPendingInstalls) {
1270                                // Indicate service bind error
1271                                params.serviceError();
1272                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1273                                        System.identityHashCode(params));
1274                            }
1275                            mPendingInstalls.clear();
1276                        }
1277                    }
1278                    break;
1279                }
1280                case MCS_UNBIND: {
1281                    // If there is no actual work left, then time to unbind.
1282                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1283
1284                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1285                        if (mBound) {
1286                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1287
1288                            disconnectService();
1289                        }
1290                    } else if (mPendingInstalls.size() > 0) {
1291                        // There are more pending requests in queue.
1292                        // Just post MCS_BOUND message to trigger processing
1293                        // of next pending install.
1294                        mHandler.sendEmptyMessage(MCS_BOUND);
1295                    }
1296
1297                    break;
1298                }
1299                case MCS_GIVE_UP: {
1300                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1301                    HandlerParams params = mPendingInstalls.remove(0);
1302                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1303                            System.identityHashCode(params));
1304                    break;
1305                }
1306                case SEND_PENDING_BROADCAST: {
1307                    String packages[];
1308                    ArrayList<String> components[];
1309                    int size = 0;
1310                    int uids[];
1311                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1312                    synchronized (mPackages) {
1313                        if (mPendingBroadcasts == null) {
1314                            return;
1315                        }
1316                        size = mPendingBroadcasts.size();
1317                        if (size <= 0) {
1318                            // Nothing to be done. Just return
1319                            return;
1320                        }
1321                        packages = new String[size];
1322                        components = new ArrayList[size];
1323                        uids = new int[size];
1324                        int i = 0;  // filling out the above arrays
1325
1326                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1327                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1328                            Iterator<Map.Entry<String, ArrayList<String>>> it
1329                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1330                                            .entrySet().iterator();
1331                            while (it.hasNext() && i < size) {
1332                                Map.Entry<String, ArrayList<String>> ent = it.next();
1333                                packages[i] = ent.getKey();
1334                                components[i] = ent.getValue();
1335                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1336                                uids[i] = (ps != null)
1337                                        ? UserHandle.getUid(packageUserId, ps.appId)
1338                                        : -1;
1339                                i++;
1340                            }
1341                        }
1342                        size = i;
1343                        mPendingBroadcasts.clear();
1344                    }
1345                    // Send broadcasts
1346                    for (int i = 0; i < size; i++) {
1347                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1348                    }
1349                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1350                    break;
1351                }
1352                case START_CLEANING_PACKAGE: {
1353                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1354                    final String packageName = (String)msg.obj;
1355                    final int userId = msg.arg1;
1356                    final boolean andCode = msg.arg2 != 0;
1357                    synchronized (mPackages) {
1358                        if (userId == UserHandle.USER_ALL) {
1359                            int[] users = sUserManager.getUserIds();
1360                            for (int user : users) {
1361                                mSettings.addPackageToCleanLPw(
1362                                        new PackageCleanItem(user, packageName, andCode));
1363                            }
1364                        } else {
1365                            mSettings.addPackageToCleanLPw(
1366                                    new PackageCleanItem(userId, packageName, andCode));
1367                        }
1368                    }
1369                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1370                    startCleaningPackages();
1371                } break;
1372                case POST_INSTALL: {
1373                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1374
1375                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1376                    mRunningInstalls.delete(msg.arg1);
1377                    boolean deleteOld = false;
1378
1379                    if (data != null) {
1380                        InstallArgs args = data.args;
1381                        PackageInstalledInfo res = data.res;
1382
1383                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1384                            final String packageName = res.pkg.applicationInfo.packageName;
1385                            res.removedInfo.sendBroadcast(false, true, false);
1386                            Bundle extras = new Bundle(1);
1387                            extras.putInt(Intent.EXTRA_UID, res.uid);
1388
1389                            // Now that we successfully installed the package, grant runtime
1390                            // permissions if requested before broadcasting the install.
1391                            if ((args.installFlags
1392                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1393                                    && res.pkg.applicationInfo.targetSdkVersion
1394                                            >= Build.VERSION_CODES.M) {
1395                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1396                                        args.installGrantPermissions);
1397                            }
1398
1399                            // Determine the set of users who are adding this
1400                            // package for the first time vs. those who are seeing
1401                            // an update.
1402                            int[] firstUsers;
1403                            int[] updateUsers = new int[0];
1404                            if (res.origUsers == null || res.origUsers.length == 0) {
1405                                firstUsers = res.newUsers;
1406                            } else {
1407                                firstUsers = new int[0];
1408                                for (int i=0; i<res.newUsers.length; i++) {
1409                                    int user = res.newUsers[i];
1410                                    boolean isNew = true;
1411                                    for (int j=0; j<res.origUsers.length; j++) {
1412                                        if (res.origUsers[j] == user) {
1413                                            isNew = false;
1414                                            break;
1415                                        }
1416                                    }
1417                                    if (isNew) {
1418                                        int[] newFirst = new int[firstUsers.length+1];
1419                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1420                                                firstUsers.length);
1421                                        newFirst[firstUsers.length] = user;
1422                                        firstUsers = newFirst;
1423                                    } else {
1424                                        int[] newUpdate = new int[updateUsers.length+1];
1425                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1426                                                updateUsers.length);
1427                                        newUpdate[updateUsers.length] = user;
1428                                        updateUsers = newUpdate;
1429                                    }
1430                                }
1431                            }
1432                            // don't broadcast for ephemeral installs/updates
1433                            final boolean isEphemeral = isEphemeral(res.pkg);
1434                            if (!isEphemeral) {
1435                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1436                                        extras, 0 /*flags*/, null /*targetPackage*/,
1437                                        null /*finishedReceiver*/, firstUsers);
1438                            }
1439                            final boolean update = res.removedInfo.removedPackage != null;
1440                            if (update) {
1441                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1442                            }
1443                            if (!isEphemeral) {
1444                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1445                                        extras, 0 /*flags*/, null /*targetPackage*/,
1446                                        null /*finishedReceiver*/, updateUsers);
1447                            }
1448                            if (update) {
1449                                if (!isEphemeral) {
1450                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1451                                            packageName, extras, 0 /*flags*/,
1452                                            null /*targetPackage*/, null /*finishedReceiver*/,
1453                                            updateUsers);
1454                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1455                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1456                                            packageName /*targetPackage*/,
1457                                            null /*finishedReceiver*/, updateUsers);
1458                                }
1459
1460                                // treat asec-hosted packages like removable media on upgrade
1461                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1462                                    if (DEBUG_INSTALL) {
1463                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1464                                                + " is ASEC-hosted -> AVAILABLE");
1465                                    }
1466                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1467                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1468                                    pkgList.add(packageName);
1469                                    sendResourcesChangedBroadcast(true, true,
1470                                            pkgList,uidArray, null);
1471                                }
1472                            }
1473                            if (res.removedInfo.args != null) {
1474                                // Remove the replaced package's older resources safely now
1475                                deleteOld = true;
1476                            }
1477
1478                            // If this app is a browser and it's newly-installed for some
1479                            // users, clear any default-browser state in those users
1480                            if (firstUsers.length > 0) {
1481                                // the app's nature doesn't depend on the user, so we can just
1482                                // check its browser nature in any user and generalize.
1483                                if (packageIsBrowser(packageName, firstUsers[0])) {
1484                                    synchronized (mPackages) {
1485                                        for (int userId : firstUsers) {
1486                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1487                                        }
1488                                    }
1489                                }
1490                            }
1491                            // Log current value of "unknown sources" setting
1492                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1493                                getUnknownSourcesSettings());
1494                        }
1495                        // Force a gc to clear up things
1496                        Runtime.getRuntime().gc();
1497                        // We delete after a gc for applications  on sdcard.
1498                        if (deleteOld) {
1499                            synchronized (mInstallLock) {
1500                                res.removedInfo.args.doPostDeleteLI(true);
1501                            }
1502                        }
1503                        if (args.observer != null) {
1504                            try {
1505                                Bundle extras = extrasForInstallResult(res);
1506                                args.observer.onPackageInstalled(res.name, res.returnCode,
1507                                        res.returnMsg, extras);
1508                            } catch (RemoteException e) {
1509                                Slog.i(TAG, "Observer no longer exists.");
1510                            }
1511                        }
1512                        if (args.traceMethod != null) {
1513                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1514                                    args.traceCookie);
1515                        }
1516                        return;
1517                    } else {
1518                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1519                    }
1520
1521                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1522                } break;
1523                case UPDATED_MEDIA_STATUS: {
1524                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1525                    boolean reportStatus = msg.arg1 == 1;
1526                    boolean doGc = msg.arg2 == 1;
1527                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1528                    if (doGc) {
1529                        // Force a gc to clear up stale containers.
1530                        Runtime.getRuntime().gc();
1531                    }
1532                    if (msg.obj != null) {
1533                        @SuppressWarnings("unchecked")
1534                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1535                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1536                        // Unload containers
1537                        unloadAllContainers(args);
1538                    }
1539                    if (reportStatus) {
1540                        try {
1541                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1542                            PackageHelper.getMountService().finishMediaUpdate();
1543                        } catch (RemoteException e) {
1544                            Log.e(TAG, "MountService not running?");
1545                        }
1546                    }
1547                } break;
1548                case WRITE_SETTINGS: {
1549                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1550                    synchronized (mPackages) {
1551                        removeMessages(WRITE_SETTINGS);
1552                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1553                        mSettings.writeLPr();
1554                        mDirtyUsers.clear();
1555                    }
1556                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1557                } break;
1558                case WRITE_PACKAGE_RESTRICTIONS: {
1559                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1560                    synchronized (mPackages) {
1561                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1562                        for (int userId : mDirtyUsers) {
1563                            mSettings.writePackageRestrictionsLPr(userId);
1564                        }
1565                        mDirtyUsers.clear();
1566                    }
1567                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1568                } break;
1569                case CHECK_PENDING_VERIFICATION: {
1570                    final int verificationId = msg.arg1;
1571                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1572
1573                    if ((state != null) && !state.timeoutExtended()) {
1574                        final InstallArgs args = state.getInstallArgs();
1575                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1576
1577                        Slog.i(TAG, "Verification timed out for " + originUri);
1578                        mPendingVerification.remove(verificationId);
1579
1580                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1581
1582                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1583                            Slog.i(TAG, "Continuing with installation of " + originUri);
1584                            state.setVerifierResponse(Binder.getCallingUid(),
1585                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1586                            broadcastPackageVerified(verificationId, originUri,
1587                                    PackageManager.VERIFICATION_ALLOW,
1588                                    state.getInstallArgs().getUser());
1589                            try {
1590                                ret = args.copyApk(mContainerService, true);
1591                            } catch (RemoteException e) {
1592                                Slog.e(TAG, "Could not contact the ContainerService");
1593                            }
1594                        } else {
1595                            broadcastPackageVerified(verificationId, originUri,
1596                                    PackageManager.VERIFICATION_REJECT,
1597                                    state.getInstallArgs().getUser());
1598                        }
1599
1600                        Trace.asyncTraceEnd(
1601                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1602
1603                        processPendingInstall(args, ret);
1604                        mHandler.sendEmptyMessage(MCS_UNBIND);
1605                    }
1606                    break;
1607                }
1608                case PACKAGE_VERIFIED: {
1609                    final int verificationId = msg.arg1;
1610
1611                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1612                    if (state == null) {
1613                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1614                        break;
1615                    }
1616
1617                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1618
1619                    state.setVerifierResponse(response.callerUid, response.code);
1620
1621                    if (state.isVerificationComplete()) {
1622                        mPendingVerification.remove(verificationId);
1623
1624                        final InstallArgs args = state.getInstallArgs();
1625                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1626
1627                        int ret;
1628                        if (state.isInstallAllowed()) {
1629                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1630                            broadcastPackageVerified(verificationId, originUri,
1631                                    response.code, state.getInstallArgs().getUser());
1632                            try {
1633                                ret = args.copyApk(mContainerService, true);
1634                            } catch (RemoteException e) {
1635                                Slog.e(TAG, "Could not contact the ContainerService");
1636                            }
1637                        } else {
1638                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1639                        }
1640
1641                        Trace.asyncTraceEnd(
1642                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1643
1644                        processPendingInstall(args, ret);
1645                        mHandler.sendEmptyMessage(MCS_UNBIND);
1646                    }
1647
1648                    break;
1649                }
1650                case START_INTENT_FILTER_VERIFICATIONS: {
1651                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1652                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1653                            params.replacing, params.pkg);
1654                    break;
1655                }
1656                case INTENT_FILTER_VERIFIED: {
1657                    final int verificationId = msg.arg1;
1658
1659                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1660                            verificationId);
1661                    if (state == null) {
1662                        Slog.w(TAG, "Invalid IntentFilter verification token "
1663                                + verificationId + " received");
1664                        break;
1665                    }
1666
1667                    final int userId = state.getUserId();
1668
1669                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1670                            "Processing IntentFilter verification with token:"
1671                            + verificationId + " and userId:" + userId);
1672
1673                    final IntentFilterVerificationResponse response =
1674                            (IntentFilterVerificationResponse) msg.obj;
1675
1676                    state.setVerifierResponse(response.callerUid, response.code);
1677
1678                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1679                            "IntentFilter verification with token:" + verificationId
1680                            + " and userId:" + userId
1681                            + " is settings verifier response with response code:"
1682                            + response.code);
1683
1684                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1685                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1686                                + response.getFailedDomainsString());
1687                    }
1688
1689                    if (state.isVerificationComplete()) {
1690                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1691                    } else {
1692                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1693                                "IntentFilter verification with token:" + verificationId
1694                                + " was not said to be complete");
1695                    }
1696
1697                    break;
1698                }
1699            }
1700        }
1701    }
1702
1703    private StorageEventListener mStorageListener = new StorageEventListener() {
1704        @Override
1705        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1706            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1707                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1708                    final String volumeUuid = vol.getFsUuid();
1709
1710                    // Clean up any users or apps that were removed or recreated
1711                    // while this volume was missing
1712                    reconcileUsers(volumeUuid);
1713                    reconcileApps(volumeUuid);
1714
1715                    // Clean up any install sessions that expired or were
1716                    // cancelled while this volume was missing
1717                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1718
1719                    loadPrivatePackages(vol);
1720
1721                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1722                    unloadPrivatePackages(vol);
1723                }
1724            }
1725
1726            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1727                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1728                    updateExternalMediaStatus(true, false);
1729                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1730                    updateExternalMediaStatus(false, false);
1731                }
1732            }
1733        }
1734
1735        @Override
1736        public void onVolumeForgotten(String fsUuid) {
1737            if (TextUtils.isEmpty(fsUuid)) {
1738                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1739                return;
1740            }
1741
1742            // Remove any apps installed on the forgotten volume
1743            synchronized (mPackages) {
1744                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1745                for (PackageSetting ps : packages) {
1746                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1747                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1748                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1749                }
1750
1751                mSettings.onVolumeForgotten(fsUuid);
1752                mSettings.writeLPr();
1753            }
1754        }
1755    };
1756
1757    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1758            String[] grantedPermissions) {
1759        if (userId >= UserHandle.USER_SYSTEM) {
1760            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1761        } else if (userId == UserHandle.USER_ALL) {
1762            final int[] userIds;
1763            synchronized (mPackages) {
1764                userIds = UserManagerService.getInstance().getUserIds();
1765            }
1766            for (int someUserId : userIds) {
1767                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1768            }
1769        }
1770
1771        // We could have touched GID membership, so flush out packages.list
1772        synchronized (mPackages) {
1773            mSettings.writePackageListLPr();
1774        }
1775    }
1776
1777    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1778            String[] grantedPermissions) {
1779        SettingBase sb = (SettingBase) pkg.mExtras;
1780        if (sb == null) {
1781            return;
1782        }
1783
1784        PermissionsState permissionsState = sb.getPermissionsState();
1785
1786        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1787                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1788
1789        synchronized (mPackages) {
1790            for (String permission : pkg.requestedPermissions) {
1791                BasePermission bp = mSettings.mPermissions.get(permission);
1792                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1793                        && (grantedPermissions == null
1794                               || ArrayUtils.contains(grantedPermissions, permission))) {
1795                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1796                    // Installer cannot change immutable permissions.
1797                    if ((flags & immutableFlags) == 0) {
1798                        grantRuntimePermission(pkg.packageName, permission, userId);
1799                    }
1800                }
1801            }
1802        }
1803    }
1804
1805    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1806        Bundle extras = null;
1807        switch (res.returnCode) {
1808            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1809                extras = new Bundle();
1810                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1811                        res.origPermission);
1812                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1813                        res.origPackage);
1814                break;
1815            }
1816            case PackageManager.INSTALL_SUCCEEDED: {
1817                extras = new Bundle();
1818                extras.putBoolean(Intent.EXTRA_REPLACING,
1819                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1820                break;
1821            }
1822        }
1823        return extras;
1824    }
1825
1826    void scheduleWriteSettingsLocked() {
1827        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1828            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1829        }
1830    }
1831
1832    void scheduleWritePackageRestrictionsLocked(int userId) {
1833        if (!sUserManager.exists(userId)) return;
1834        mDirtyUsers.add(userId);
1835        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1836            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1837        }
1838    }
1839
1840    public static PackageManagerService main(Context context, Installer installer,
1841            boolean factoryTest, boolean onlyCore) {
1842        PackageManagerService m = new PackageManagerService(context, installer,
1843                factoryTest, onlyCore);
1844        m.enableSystemUserApps();
1845        ServiceManager.addService("package", m);
1846        return m;
1847    }
1848
1849    private void enableSystemUserApps() {
1850        if (!UserManager.isSplitSystemUser()) {
1851            return;
1852        }
1853        // For system user, enable apps based on the following conditions:
1854        // - app is whitelisted or belong to one of these groups:
1855        //   -- system app which has no launcher icons
1856        //   -- system app which has INTERACT_ACROSS_USERS permission
1857        //   -- system IME app
1858        // - app is not in the blacklist
1859        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1860        Set<String> enableApps = new ArraySet<>();
1861        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1862                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1863                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1864        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1865        enableApps.addAll(wlApps);
1866        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1867        enableApps.removeAll(blApps);
1868
1869        List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true,
1870                UserHandle.SYSTEM);
1871        final int systemAppsSize = systemApps.size();
1872        synchronized (mPackages) {
1873            for (int i = 0; i < systemAppsSize; i++) {
1874                String pName = systemApps.get(i);
1875                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1876                // Should not happen, but we shouldn't be failing if it does
1877                if (pkgSetting == null) {
1878                    continue;
1879                }
1880                boolean installed = enableApps.contains(pName);
1881                pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM);
1882            }
1883        }
1884    }
1885
1886    static String[] splitString(String str, char sep) {
1887        int count = 1;
1888        int i = 0;
1889        while ((i=str.indexOf(sep, i)) >= 0) {
1890            count++;
1891            i++;
1892        }
1893
1894        String[] res = new String[count];
1895        i=0;
1896        count = 0;
1897        int lastI=0;
1898        while ((i=str.indexOf(sep, i)) >= 0) {
1899            res[count] = str.substring(lastI, i);
1900            count++;
1901            i++;
1902            lastI = i;
1903        }
1904        res[count] = str.substring(lastI, str.length());
1905        return res;
1906    }
1907
1908    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1909        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1910                Context.DISPLAY_SERVICE);
1911        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1912    }
1913
1914    public PackageManagerService(Context context, Installer installer,
1915            boolean factoryTest, boolean onlyCore) {
1916        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1917                SystemClock.uptimeMillis());
1918
1919        if (mSdkVersion <= 0) {
1920            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1921        }
1922
1923        mContext = context;
1924        mFactoryTest = factoryTest;
1925        mOnlyCore = onlyCore;
1926        mMetrics = new DisplayMetrics();
1927        mSettings = new Settings(mPackages);
1928        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1929                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1930        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1931                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1932        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1933                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1934        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1935                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1936        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1937                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1938        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1939                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1940
1941        String separateProcesses = SystemProperties.get("debug.separate_processes");
1942        if (separateProcesses != null && separateProcesses.length() > 0) {
1943            if ("*".equals(separateProcesses)) {
1944                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1945                mSeparateProcesses = null;
1946                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1947            } else {
1948                mDefParseFlags = 0;
1949                mSeparateProcesses = separateProcesses.split(",");
1950                Slog.w(TAG, "Running with debug.separate_processes: "
1951                        + separateProcesses);
1952            }
1953        } else {
1954            mDefParseFlags = 0;
1955            mSeparateProcesses = null;
1956        }
1957
1958        mInstaller = installer;
1959        mPackageDexOptimizer = new PackageDexOptimizer(this);
1960        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1961
1962        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1963                FgThread.get().getLooper());
1964
1965        getDefaultDisplayMetrics(context, mMetrics);
1966
1967        SystemConfig systemConfig = SystemConfig.getInstance();
1968        mGlobalGids = systemConfig.getGlobalGids();
1969        mSystemPermissions = systemConfig.getSystemPermissions();
1970        mAvailableFeatures = systemConfig.getAvailableFeatures();
1971
1972        synchronized (mInstallLock) {
1973        // writer
1974        synchronized (mPackages) {
1975            mHandlerThread = new ServiceThread(TAG,
1976                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1977            mHandlerThread.start();
1978            mHandler = new PackageHandler(mHandlerThread.getLooper());
1979            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1980
1981            File dataDir = Environment.getDataDirectory();
1982            mAppDataDir = new File(dataDir, "data");
1983            mAppInstallDir = new File(dataDir, "app");
1984            mAppLib32InstallDir = new File(dataDir, "app-lib");
1985            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1986            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1987            mUserAppDataDir = new File(dataDir, "user");
1988            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1989
1990            sUserManager = new UserManagerService(context, this, mPackages);
1991
1992            // Propagate permission configuration in to package manager.
1993            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1994                    = systemConfig.getPermissions();
1995            for (int i=0; i<permConfig.size(); i++) {
1996                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1997                BasePermission bp = mSettings.mPermissions.get(perm.name);
1998                if (bp == null) {
1999                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2000                    mSettings.mPermissions.put(perm.name, bp);
2001                }
2002                if (perm.gids != null) {
2003                    bp.setGids(perm.gids, perm.perUser);
2004                }
2005            }
2006
2007            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2008            for (int i=0; i<libConfig.size(); i++) {
2009                mSharedLibraries.put(libConfig.keyAt(i),
2010                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2011            }
2012
2013            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2014
2015            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2016
2017            String customResolverActivity = Resources.getSystem().getString(
2018                    R.string.config_customResolverActivity);
2019            if (TextUtils.isEmpty(customResolverActivity)) {
2020                customResolverActivity = null;
2021            } else {
2022                mCustomResolverComponentName = ComponentName.unflattenFromString(
2023                        customResolverActivity);
2024            }
2025
2026            long startTime = SystemClock.uptimeMillis();
2027
2028            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2029                    startTime);
2030
2031            // Set flag to monitor and not change apk file paths when
2032            // scanning install directories.
2033            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2034
2035            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2036            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2037
2038            if (bootClassPath == null) {
2039                Slog.w(TAG, "No BOOTCLASSPATH found!");
2040            }
2041
2042            if (systemServerClassPath == null) {
2043                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2044            }
2045
2046            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2047            final String[] dexCodeInstructionSets =
2048                    getDexCodeInstructionSets(
2049                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2050
2051            /**
2052             * Ensure all external libraries have had dexopt run on them.
2053             */
2054            if (mSharedLibraries.size() > 0) {
2055                // NOTE: For now, we're compiling these system "shared libraries"
2056                // (and framework jars) into all available architectures. It's possible
2057                // to compile them only when we come across an app that uses them (there's
2058                // already logic for that in scanPackageLI) but that adds some complexity.
2059                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2060                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2061                        final String lib = libEntry.path;
2062                        if (lib == null) {
2063                            continue;
2064                        }
2065
2066                        try {
2067                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2068                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2069                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2070                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2071                            }
2072                        } catch (FileNotFoundException e) {
2073                            Slog.w(TAG, "Library not found: " + lib);
2074                        } catch (IOException e) {
2075                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2076                                    + e.getMessage());
2077                        }
2078                    }
2079                }
2080            }
2081
2082            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2083
2084            final VersionInfo ver = mSettings.getInternalVersion();
2085            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2086            // when upgrading from pre-M, promote system app permissions from install to runtime
2087            mPromoteSystemApps =
2088                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2089
2090            // save off the names of pre-existing system packages prior to scanning; we don't
2091            // want to automatically grant runtime permissions for new system apps
2092            if (mPromoteSystemApps) {
2093                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2094                while (pkgSettingIter.hasNext()) {
2095                    PackageSetting ps = pkgSettingIter.next();
2096                    if (isSystemApp(ps)) {
2097                        mExistingSystemPackages.add(ps.name);
2098                    }
2099                }
2100            }
2101
2102            // Collect vendor overlay packages.
2103            // (Do this before scanning any apps.)
2104            // For security and version matching reason, only consider
2105            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2106            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2107            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2108                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2109
2110            // Find base frameworks (resource packages without code).
2111            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2112                    | PackageParser.PARSE_IS_SYSTEM_DIR
2113                    | PackageParser.PARSE_IS_PRIVILEGED,
2114                    scanFlags | SCAN_NO_DEX, 0);
2115
2116            // Collected privileged system packages.
2117            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2118            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2119                    | PackageParser.PARSE_IS_SYSTEM_DIR
2120                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2121
2122            // Collect ordinary system packages.
2123            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2124            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2125                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2126
2127            // Collect all vendor packages.
2128            File vendorAppDir = new File("/vendor/app");
2129            try {
2130                vendorAppDir = vendorAppDir.getCanonicalFile();
2131            } catch (IOException e) {
2132                // failed to look up canonical path, continue with original one
2133            }
2134            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2135                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2136
2137            // Collect all OEM packages.
2138            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2139            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2140                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2141
2142            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2143            mInstaller.moveFiles();
2144
2145            // Prune any system packages that no longer exist.
2146            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2147            if (!mOnlyCore) {
2148                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2149                while (psit.hasNext()) {
2150                    PackageSetting ps = psit.next();
2151
2152                    /*
2153                     * If this is not a system app, it can't be a
2154                     * disable system app.
2155                     */
2156                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2157                        continue;
2158                    }
2159
2160                    /*
2161                     * If the package is scanned, it's not erased.
2162                     */
2163                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2164                    if (scannedPkg != null) {
2165                        /*
2166                         * If the system app is both scanned and in the
2167                         * disabled packages list, then it must have been
2168                         * added via OTA. Remove it from the currently
2169                         * scanned package so the previously user-installed
2170                         * application can be scanned.
2171                         */
2172                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2173                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2174                                    + ps.name + "; removing system app.  Last known codePath="
2175                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2176                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2177                                    + scannedPkg.mVersionCode);
2178                            removePackageLI(ps, true);
2179                            mExpectingBetter.put(ps.name, ps.codePath);
2180                        }
2181
2182                        continue;
2183                    }
2184
2185                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2186                        psit.remove();
2187                        logCriticalInfo(Log.WARN, "System package " + ps.name
2188                                + " no longer exists; wiping its data");
2189                        removeDataDirsLI(null, ps.name);
2190                    } else {
2191                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2192                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2193                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2194                        }
2195                    }
2196                }
2197            }
2198
2199            //look for any incomplete package installations
2200            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2201            //clean up list
2202            for(int i = 0; i < deletePkgsList.size(); i++) {
2203                //clean up here
2204                cleanupInstallFailedPackage(deletePkgsList.get(i));
2205            }
2206            //delete tmp files
2207            deleteTempPackageFiles();
2208
2209            // Remove any shared userIDs that have no associated packages
2210            mSettings.pruneSharedUsersLPw();
2211
2212            if (!mOnlyCore) {
2213                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2214                        SystemClock.uptimeMillis());
2215                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2216
2217                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2218                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2219
2220                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2221                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2222
2223                /**
2224                 * Remove disable package settings for any updated system
2225                 * apps that were removed via an OTA. If they're not a
2226                 * previously-updated app, remove them completely.
2227                 * Otherwise, just revoke their system-level permissions.
2228                 */
2229                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2230                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2231                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2232
2233                    String msg;
2234                    if (deletedPkg == null) {
2235                        msg = "Updated system package " + deletedAppName
2236                                + " no longer exists; wiping its data";
2237                        removeDataDirsLI(null, deletedAppName);
2238                    } else {
2239                        msg = "Updated system app + " + deletedAppName
2240                                + " no longer present; removing system privileges for "
2241                                + deletedAppName;
2242
2243                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2244
2245                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2246                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2247                    }
2248                    logCriticalInfo(Log.WARN, msg);
2249                }
2250
2251                /**
2252                 * Make sure all system apps that we expected to appear on
2253                 * the userdata partition actually showed up. If they never
2254                 * appeared, crawl back and revive the system version.
2255                 */
2256                for (int i = 0; i < mExpectingBetter.size(); i++) {
2257                    final String packageName = mExpectingBetter.keyAt(i);
2258                    if (!mPackages.containsKey(packageName)) {
2259                        final File scanFile = mExpectingBetter.valueAt(i);
2260
2261                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2262                                + " but never showed up; reverting to system");
2263
2264                        final int reparseFlags;
2265                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2266                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2267                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2268                                    | PackageParser.PARSE_IS_PRIVILEGED;
2269                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2270                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2271                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2272                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2273                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2274                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2275                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2276                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2277                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2278                        } else {
2279                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2280                            continue;
2281                        }
2282
2283                        mSettings.enableSystemPackageLPw(packageName);
2284
2285                        try {
2286                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2287                        } catch (PackageManagerException e) {
2288                            Slog.e(TAG, "Failed to parse original system package: "
2289                                    + e.getMessage());
2290                        }
2291                    }
2292                }
2293            }
2294            mExpectingBetter.clear();
2295
2296            // Now that we know all of the shared libraries, update all clients to have
2297            // the correct library paths.
2298            updateAllSharedLibrariesLPw();
2299
2300            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2301                // NOTE: We ignore potential failures here during a system scan (like
2302                // the rest of the commands above) because there's precious little we
2303                // can do about it. A settings error is reported, though.
2304                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2305                        false /* boot complete */);
2306            }
2307
2308            // Now that we know all the packages we are keeping,
2309            // read and update their last usage times.
2310            mPackageUsage.readLP();
2311
2312            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2313                    SystemClock.uptimeMillis());
2314            Slog.i(TAG, "Time to scan packages: "
2315                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2316                    + " seconds");
2317
2318            // If the platform SDK has changed since the last time we booted,
2319            // we need to re-grant app permission to catch any new ones that
2320            // appear.  This is really a hack, and means that apps can in some
2321            // cases get permissions that the user didn't initially explicitly
2322            // allow...  it would be nice to have some better way to handle
2323            // this situation.
2324            int updateFlags = UPDATE_PERMISSIONS_ALL;
2325            if (ver.sdkVersion != mSdkVersion) {
2326                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2327                        + mSdkVersion + "; regranting permissions for internal storage");
2328                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2329            }
2330            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2331            ver.sdkVersion = mSdkVersion;
2332
2333            // If this is the first boot or an update from pre-M, and it is a normal
2334            // boot, then we need to initialize the default preferred apps across
2335            // all defined users.
2336            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2337                for (UserInfo user : sUserManager.getUsers(true)) {
2338                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2339                    applyFactoryDefaultBrowserLPw(user.id);
2340                    primeDomainVerificationsLPw(user.id);
2341                }
2342            }
2343
2344            // If this is first boot after an OTA, and a normal boot, then
2345            // we need to clear code cache directories.
2346            if (mIsUpgrade && !onlyCore) {
2347                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2348                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2349                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2350                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2351                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2352                    }
2353                }
2354                ver.fingerprint = Build.FINGERPRINT;
2355            }
2356
2357            checkDefaultBrowser();
2358
2359            // clear only after permissions and other defaults have been updated
2360            mExistingSystemPackages.clear();
2361            mPromoteSystemApps = false;
2362
2363            // All the changes are done during package scanning.
2364            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2365
2366            // can downgrade to reader
2367            mSettings.writeLPr();
2368
2369            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2370                    SystemClock.uptimeMillis());
2371
2372            mRequiredVerifierPackage = getRequiredVerifierLPr();
2373            mRequiredInstallerPackage = getRequiredInstallerLPr();
2374
2375            mInstallerService = new PackageInstallerService(context, this);
2376
2377            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2378            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2379                    mIntentFilterVerifierComponent);
2380
2381            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2382            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2383            // both the installer and resolver must be present to enable ephemeral
2384            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2385                if (DEBUG_EPHEMERAL) {
2386                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2387                            + " installer:" + ephemeralInstallerComponent);
2388                }
2389                mEphemeralResolverComponent = ephemeralResolverComponent;
2390                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2391                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2392                mEphemeralResolverConnection =
2393                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2394            } else {
2395                if (DEBUG_EPHEMERAL) {
2396                    final String missingComponent =
2397                            (ephemeralResolverComponent == null)
2398                            ? (ephemeralInstallerComponent == null)
2399                                    ? "resolver and installer"
2400                                    : "resolver"
2401                            : "installer";
2402                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2403                }
2404                mEphemeralResolverComponent = null;
2405                mEphemeralInstallerComponent = null;
2406                mEphemeralResolverConnection = null;
2407            }
2408        } // synchronized (mPackages)
2409        } // synchronized (mInstallLock)
2410
2411        // Now after opening every single application zip, make sure they
2412        // are all flushed.  Not really needed, but keeps things nice and
2413        // tidy.
2414        Runtime.getRuntime().gc();
2415
2416        // The initial scanning above does many calls into installd while
2417        // holding the mPackages lock, but we're mostly interested in yelling
2418        // once we have a booted system.
2419        mInstaller.setWarnIfHeld(mPackages);
2420
2421        // Expose private service for system components to use.
2422        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2423    }
2424
2425    @Override
2426    public boolean isFirstBoot() {
2427        return !mRestoredSettings;
2428    }
2429
2430    @Override
2431    public boolean isOnlyCoreApps() {
2432        return mOnlyCore;
2433    }
2434
2435    @Override
2436    public boolean isUpgrade() {
2437        return mIsUpgrade;
2438    }
2439
2440    private String getRequiredVerifierLPr() {
2441        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2442        // We only care about verifier that's installed under system user.
2443        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2444                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2445
2446        String requiredVerifier = null;
2447
2448        final int N = receivers.size();
2449        for (int i = 0; i < N; i++) {
2450            final ResolveInfo info = receivers.get(i);
2451
2452            if (info.activityInfo == null) {
2453                continue;
2454            }
2455
2456            final String packageName = info.activityInfo.packageName;
2457
2458            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2459                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2460                continue;
2461            }
2462
2463            if (requiredVerifier != null) {
2464                throw new RuntimeException("There can be only one required verifier");
2465            }
2466
2467            requiredVerifier = packageName;
2468        }
2469
2470        return requiredVerifier;
2471    }
2472
2473    private String getRequiredInstallerLPr() {
2474        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2475        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2476        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2477
2478        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2479                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2480
2481        String requiredInstaller = null;
2482
2483        final int N = installers.size();
2484        for (int i = 0; i < N; i++) {
2485            final ResolveInfo info = installers.get(i);
2486            final String packageName = info.activityInfo.packageName;
2487
2488            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2489                continue;
2490            }
2491
2492            if (requiredInstaller != null) {
2493                throw new RuntimeException("There must be one required installer");
2494            }
2495
2496            requiredInstaller = packageName;
2497        }
2498
2499        if (requiredInstaller == null) {
2500            throw new RuntimeException("There must be one required installer");
2501        }
2502
2503        return requiredInstaller;
2504    }
2505
2506    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2507        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2508        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2509                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2510
2511        ComponentName verifierComponentName = null;
2512
2513        int priority = -1000;
2514        final int N = receivers.size();
2515        for (int i = 0; i < N; i++) {
2516            final ResolveInfo info = receivers.get(i);
2517
2518            if (info.activityInfo == null) {
2519                continue;
2520            }
2521
2522            final String packageName = info.activityInfo.packageName;
2523
2524            final PackageSetting ps = mSettings.mPackages.get(packageName);
2525            if (ps == null) {
2526                continue;
2527            }
2528
2529            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2530                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2531                continue;
2532            }
2533
2534            // Select the IntentFilterVerifier with the highest priority
2535            if (priority < info.priority) {
2536                priority = info.priority;
2537                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2538                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2539                        + verifierComponentName + " with priority: " + info.priority);
2540            }
2541        }
2542
2543        return verifierComponentName;
2544    }
2545
2546    private ComponentName getEphemeralResolverLPr() {
2547        final String[] packageArray =
2548                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2549        if (packageArray.length == 0) {
2550            if (DEBUG_EPHEMERAL) {
2551                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2552            }
2553            return null;
2554        }
2555
2556        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2557        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2558                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2559
2560        final int N = resolvers.size();
2561        if (N == 0) {
2562            if (DEBUG_EPHEMERAL) {
2563                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2564            }
2565            return null;
2566        }
2567
2568        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2569        for (int i = 0; i < N; i++) {
2570            final ResolveInfo info = resolvers.get(i);
2571
2572            if (info.serviceInfo == null) {
2573                continue;
2574            }
2575
2576            final String packageName = info.serviceInfo.packageName;
2577            if (!possiblePackages.contains(packageName)) {
2578                if (DEBUG_EPHEMERAL) {
2579                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2580                            + " pkg: " + packageName + ", info:" + info);
2581                }
2582                continue;
2583            }
2584
2585            if (DEBUG_EPHEMERAL) {
2586                Slog.v(TAG, "Ephemeral resolver found;"
2587                        + " pkg: " + packageName + ", info:" + info);
2588            }
2589            return new ComponentName(packageName, info.serviceInfo.name);
2590        }
2591        if (DEBUG_EPHEMERAL) {
2592            Slog.v(TAG, "Ephemeral resolver NOT found");
2593        }
2594        return null;
2595    }
2596
2597    private ComponentName getEphemeralInstallerLPr() {
2598        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2599        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2600        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2601        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2602                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2603
2604        ComponentName ephemeralInstaller = null;
2605
2606        final int N = installers.size();
2607        for (int i = 0; i < N; i++) {
2608            final ResolveInfo info = installers.get(i);
2609            final String packageName = info.activityInfo.packageName;
2610
2611            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2612                if (DEBUG_EPHEMERAL) {
2613                    Slog.d(TAG, "Ephemeral installer is not system app;"
2614                            + " pkg: " + packageName + ", info:" + info);
2615                }
2616                continue;
2617            }
2618
2619            if (ephemeralInstaller != null) {
2620                throw new RuntimeException("There must only be one ephemeral installer");
2621            }
2622
2623            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2624        }
2625
2626        return ephemeralInstaller;
2627    }
2628
2629    private void primeDomainVerificationsLPw(int userId) {
2630        if (DEBUG_DOMAIN_VERIFICATION) {
2631            Slog.d(TAG, "Priming domain verifications in user " + userId);
2632        }
2633
2634        SystemConfig systemConfig = SystemConfig.getInstance();
2635        ArraySet<String> packages = systemConfig.getLinkedApps();
2636        ArraySet<String> domains = new ArraySet<String>();
2637
2638        for (String packageName : packages) {
2639            PackageParser.Package pkg = mPackages.get(packageName);
2640            if (pkg != null) {
2641                if (!pkg.isSystemApp()) {
2642                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2643                    continue;
2644                }
2645
2646                domains.clear();
2647                for (PackageParser.Activity a : pkg.activities) {
2648                    for (ActivityIntentInfo filter : a.intents) {
2649                        if (hasValidDomains(filter)) {
2650                            domains.addAll(filter.getHostsList());
2651                        }
2652                    }
2653                }
2654
2655                if (domains.size() > 0) {
2656                    if (DEBUG_DOMAIN_VERIFICATION) {
2657                        Slog.v(TAG, "      + " + packageName);
2658                    }
2659                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2660                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2661                    // and then 'always' in the per-user state actually used for intent resolution.
2662                    final IntentFilterVerificationInfo ivi;
2663                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2664                            new ArrayList<String>(domains));
2665                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2666                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2667                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2668                } else {
2669                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2670                            + "' does not handle web links");
2671                }
2672            } else {
2673                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2674            }
2675        }
2676
2677        scheduleWritePackageRestrictionsLocked(userId);
2678        scheduleWriteSettingsLocked();
2679    }
2680
2681    private void applyFactoryDefaultBrowserLPw(int userId) {
2682        // The default browser app's package name is stored in a string resource,
2683        // with a product-specific overlay used for vendor customization.
2684        String browserPkg = mContext.getResources().getString(
2685                com.android.internal.R.string.default_browser);
2686        if (!TextUtils.isEmpty(browserPkg)) {
2687            // non-empty string => required to be a known package
2688            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2689            if (ps == null) {
2690                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2691                browserPkg = null;
2692            } else {
2693                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2694            }
2695        }
2696
2697        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2698        // default.  If there's more than one, just leave everything alone.
2699        if (browserPkg == null) {
2700            calculateDefaultBrowserLPw(userId);
2701        }
2702    }
2703
2704    private void calculateDefaultBrowserLPw(int userId) {
2705        List<String> allBrowsers = resolveAllBrowserApps(userId);
2706        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2707        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2708    }
2709
2710    private List<String> resolveAllBrowserApps(int userId) {
2711        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2712        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2713                PackageManager.MATCH_ALL, userId);
2714
2715        final int count = list.size();
2716        List<String> result = new ArrayList<String>(count);
2717        for (int i=0; i<count; i++) {
2718            ResolveInfo info = list.get(i);
2719            if (info.activityInfo == null
2720                    || !info.handleAllWebDataURI
2721                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2722                    || result.contains(info.activityInfo.packageName)) {
2723                continue;
2724            }
2725            result.add(info.activityInfo.packageName);
2726        }
2727
2728        return result;
2729    }
2730
2731    private boolean packageIsBrowser(String packageName, int userId) {
2732        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2733                PackageManager.MATCH_ALL, userId);
2734        final int N = list.size();
2735        for (int i = 0; i < N; i++) {
2736            ResolveInfo info = list.get(i);
2737            if (packageName.equals(info.activityInfo.packageName)) {
2738                return true;
2739            }
2740        }
2741        return false;
2742    }
2743
2744    private void checkDefaultBrowser() {
2745        final int myUserId = UserHandle.myUserId();
2746        final String packageName = getDefaultBrowserPackageName(myUserId);
2747        if (packageName != null) {
2748            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2749            if (info == null) {
2750                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2751                synchronized (mPackages) {
2752                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2753                }
2754            }
2755        }
2756    }
2757
2758    @Override
2759    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2760            throws RemoteException {
2761        try {
2762            return super.onTransact(code, data, reply, flags);
2763        } catch (RuntimeException e) {
2764            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2765                Slog.wtf(TAG, "Package Manager Crash", e);
2766            }
2767            throw e;
2768        }
2769    }
2770
2771    void cleanupInstallFailedPackage(PackageSetting ps) {
2772        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2773
2774        removeDataDirsLI(ps.volumeUuid, ps.name);
2775        if (ps.codePath != null) {
2776            if (ps.codePath.isDirectory()) {
2777                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2778            } else {
2779                ps.codePath.delete();
2780            }
2781        }
2782        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2783            if (ps.resourcePath.isDirectory()) {
2784                FileUtils.deleteContents(ps.resourcePath);
2785            }
2786            ps.resourcePath.delete();
2787        }
2788        mSettings.removePackageLPw(ps.name);
2789    }
2790
2791    static int[] appendInts(int[] cur, int[] add) {
2792        if (add == null) return cur;
2793        if (cur == null) return add;
2794        final int N = add.length;
2795        for (int i=0; i<N; i++) {
2796            cur = appendInt(cur, add[i]);
2797        }
2798        return cur;
2799    }
2800
2801    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2802        if (!sUserManager.exists(userId)) return null;
2803        final PackageSetting ps = (PackageSetting) p.mExtras;
2804        if (ps == null) {
2805            return null;
2806        }
2807
2808        final PermissionsState permissionsState = ps.getPermissionsState();
2809
2810        final int[] gids = permissionsState.computeGids(userId);
2811        final Set<String> permissions = permissionsState.getPermissions(userId);
2812        final PackageUserState state = ps.readUserState(userId);
2813
2814        return PackageParser.generatePackageInfo(p, gids, flags,
2815                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2816    }
2817
2818    @Override
2819    public void checkPackageStartable(String packageName, int userId) {
2820        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2821
2822        synchronized (mPackages) {
2823            final PackageSetting ps = mSettings.mPackages.get(packageName);
2824            if (ps == null) {
2825                throw new SecurityException("Package " + packageName + " was not found!");
2826            }
2827
2828            if (ps.frozen) {
2829                throw new SecurityException("Package " + packageName + " is currently frozen!");
2830            }
2831
2832            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2833                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2834                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2835            }
2836        }
2837    }
2838
2839    @Override
2840    public boolean isPackageAvailable(String packageName, int userId) {
2841        if (!sUserManager.exists(userId)) return false;
2842        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2843        synchronized (mPackages) {
2844            PackageParser.Package p = mPackages.get(packageName);
2845            if (p != null) {
2846                final PackageSetting ps = (PackageSetting) p.mExtras;
2847                if (ps != null) {
2848                    final PackageUserState state = ps.readUserState(userId);
2849                    if (state != null) {
2850                        return PackageParser.isAvailable(state);
2851                    }
2852                }
2853            }
2854        }
2855        return false;
2856    }
2857
2858    @Override
2859    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2860        if (!sUserManager.exists(userId)) return null;
2861        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2862        // reader
2863        synchronized (mPackages) {
2864            PackageParser.Package p = mPackages.get(packageName);
2865            if (DEBUG_PACKAGE_INFO)
2866                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2867            if (p != null) {
2868                return generatePackageInfo(p, flags, userId);
2869            }
2870            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2871                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2872            }
2873        }
2874        return null;
2875    }
2876
2877    @Override
2878    public String[] currentToCanonicalPackageNames(String[] names) {
2879        String[] out = new String[names.length];
2880        // reader
2881        synchronized (mPackages) {
2882            for (int i=names.length-1; i>=0; i--) {
2883                PackageSetting ps = mSettings.mPackages.get(names[i]);
2884                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2885            }
2886        }
2887        return out;
2888    }
2889
2890    @Override
2891    public String[] canonicalToCurrentPackageNames(String[] names) {
2892        String[] out = new String[names.length];
2893        // reader
2894        synchronized (mPackages) {
2895            for (int i=names.length-1; i>=0; i--) {
2896                String cur = mSettings.mRenamedPackages.get(names[i]);
2897                out[i] = cur != null ? cur : names[i];
2898            }
2899        }
2900        return out;
2901    }
2902
2903    @Override
2904    public int getPackageUid(String packageName, int userId) {
2905        return getPackageUidEtc(packageName, 0, userId);
2906    }
2907
2908    @Override
2909    public int getPackageUidEtc(String packageName, int flags, int userId) {
2910        if (!sUserManager.exists(userId)) return -1;
2911        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2912
2913        // reader
2914        synchronized (mPackages) {
2915            final PackageParser.Package p = mPackages.get(packageName);
2916            if (p != null) {
2917                return UserHandle.getUid(userId, p.applicationInfo.uid);
2918            }
2919            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2920                final PackageSetting ps = mSettings.mPackages.get(packageName);
2921                if (ps != null) {
2922                    return UserHandle.getUid(userId, ps.appId);
2923                }
2924            }
2925        }
2926
2927        return -1;
2928    }
2929
2930    @Override
2931    public int[] getPackageGids(String packageName, int userId) {
2932        return getPackageGidsEtc(packageName, 0, userId);
2933    }
2934
2935    @Override
2936    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2937        if (!sUserManager.exists(userId)) {
2938            return null;
2939        }
2940
2941        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2942                "getPackageGids");
2943
2944        // reader
2945        synchronized (mPackages) {
2946            final PackageParser.Package p = mPackages.get(packageName);
2947            if (p != null) {
2948                PackageSetting ps = (PackageSetting) p.mExtras;
2949                return ps.getPermissionsState().computeGids(userId);
2950            }
2951            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2952                final PackageSetting ps = mSettings.mPackages.get(packageName);
2953                if (ps != null) {
2954                    return ps.getPermissionsState().computeGids(userId);
2955                }
2956            }
2957        }
2958
2959        return null;
2960    }
2961
2962    static PermissionInfo generatePermissionInfo(
2963            BasePermission bp, int flags) {
2964        if (bp.perm != null) {
2965            return PackageParser.generatePermissionInfo(bp.perm, flags);
2966        }
2967        PermissionInfo pi = new PermissionInfo();
2968        pi.name = bp.name;
2969        pi.packageName = bp.sourcePackage;
2970        pi.nonLocalizedLabel = bp.name;
2971        pi.protectionLevel = bp.protectionLevel;
2972        return pi;
2973    }
2974
2975    @Override
2976    public PermissionInfo getPermissionInfo(String name, int flags) {
2977        // reader
2978        synchronized (mPackages) {
2979            final BasePermission p = mSettings.mPermissions.get(name);
2980            if (p != null) {
2981                return generatePermissionInfo(p, flags);
2982            }
2983            return null;
2984        }
2985    }
2986
2987    @Override
2988    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2989        // reader
2990        synchronized (mPackages) {
2991            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2992            for (BasePermission p : mSettings.mPermissions.values()) {
2993                if (group == null) {
2994                    if (p.perm == null || p.perm.info.group == null) {
2995                        out.add(generatePermissionInfo(p, flags));
2996                    }
2997                } else {
2998                    if (p.perm != null && group.equals(p.perm.info.group)) {
2999                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3000                    }
3001                }
3002            }
3003
3004            if (out.size() > 0) {
3005                return out;
3006            }
3007            return mPermissionGroups.containsKey(group) ? out : null;
3008        }
3009    }
3010
3011    @Override
3012    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3013        // reader
3014        synchronized (mPackages) {
3015            return PackageParser.generatePermissionGroupInfo(
3016                    mPermissionGroups.get(name), flags);
3017        }
3018    }
3019
3020    @Override
3021    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3022        // reader
3023        synchronized (mPackages) {
3024            final int N = mPermissionGroups.size();
3025            ArrayList<PermissionGroupInfo> out
3026                    = new ArrayList<PermissionGroupInfo>(N);
3027            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3028                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3029            }
3030            return out;
3031        }
3032    }
3033
3034    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3035            int userId) {
3036        if (!sUserManager.exists(userId)) return null;
3037        PackageSetting ps = mSettings.mPackages.get(packageName);
3038        if (ps != null) {
3039            if (ps.pkg == null) {
3040                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3041                        flags, userId);
3042                if (pInfo != null) {
3043                    return pInfo.applicationInfo;
3044                }
3045                return null;
3046            }
3047            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3048                    ps.readUserState(userId), userId);
3049        }
3050        return null;
3051    }
3052
3053    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3054            int userId) {
3055        if (!sUserManager.exists(userId)) return null;
3056        PackageSetting ps = mSettings.mPackages.get(packageName);
3057        if (ps != null) {
3058            PackageParser.Package pkg = ps.pkg;
3059            if (pkg == null) {
3060                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3061                    return null;
3062                }
3063                // Only data remains, so we aren't worried about code paths
3064                pkg = new PackageParser.Package(packageName);
3065                pkg.applicationInfo.packageName = packageName;
3066                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3067                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3068                pkg.applicationInfo.uid = ps.appId;
3069                pkg.applicationInfo.initForUser(userId);
3070                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3071                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3072            }
3073            return generatePackageInfo(pkg, flags, userId);
3074        }
3075        return null;
3076    }
3077
3078    @Override
3079    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3080        if (!sUserManager.exists(userId)) return null;
3081        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3082        // writer
3083        synchronized (mPackages) {
3084            PackageParser.Package p = mPackages.get(packageName);
3085            if (DEBUG_PACKAGE_INFO) Log.v(
3086                    TAG, "getApplicationInfo " + packageName
3087                    + ": " + p);
3088            if (p != null) {
3089                PackageSetting ps = mSettings.mPackages.get(packageName);
3090                if (ps == null) return null;
3091                // Note: isEnabledLP() does not apply here - always return info
3092                return PackageParser.generateApplicationInfo(
3093                        p, flags, ps.readUserState(userId), userId);
3094            }
3095            if ("android".equals(packageName)||"system".equals(packageName)) {
3096                return mAndroidApplication;
3097            }
3098            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3099                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3100            }
3101        }
3102        return null;
3103    }
3104
3105    @Override
3106    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3107            final IPackageDataObserver observer) {
3108        mContext.enforceCallingOrSelfPermission(
3109                android.Manifest.permission.CLEAR_APP_CACHE, null);
3110        // Queue up an async operation since clearing cache may take a little while.
3111        mHandler.post(new Runnable() {
3112            public void run() {
3113                mHandler.removeCallbacks(this);
3114                int retCode = -1;
3115                synchronized (mInstallLock) {
3116                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3117                    if (retCode < 0) {
3118                        Slog.w(TAG, "Couldn't clear application caches");
3119                    }
3120                }
3121                if (observer != null) {
3122                    try {
3123                        observer.onRemoveCompleted(null, (retCode >= 0));
3124                    } catch (RemoteException e) {
3125                        Slog.w(TAG, "RemoveException when invoking call back");
3126                    }
3127                }
3128            }
3129        });
3130    }
3131
3132    @Override
3133    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3134            final IntentSender pi) {
3135        mContext.enforceCallingOrSelfPermission(
3136                android.Manifest.permission.CLEAR_APP_CACHE, null);
3137        // Queue up an async operation since clearing cache may take a little while.
3138        mHandler.post(new Runnable() {
3139            public void run() {
3140                mHandler.removeCallbacks(this);
3141                int retCode = -1;
3142                synchronized (mInstallLock) {
3143                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3144                    if (retCode < 0) {
3145                        Slog.w(TAG, "Couldn't clear application caches");
3146                    }
3147                }
3148                if(pi != null) {
3149                    try {
3150                        // Callback via pending intent
3151                        int code = (retCode >= 0) ? 1 : 0;
3152                        pi.sendIntent(null, code, null,
3153                                null, null);
3154                    } catch (SendIntentException e1) {
3155                        Slog.i(TAG, "Failed to send pending intent");
3156                    }
3157                }
3158            }
3159        });
3160    }
3161
3162    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3163        synchronized (mInstallLock) {
3164            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3165                throw new IOException("Failed to free enough space");
3166            }
3167        }
3168    }
3169
3170    /**
3171     * Return if the user key is currently unlocked.
3172     */
3173    private boolean isUserKeyUnlocked(int userId) {
3174        if (StorageManager.isFileBasedEncryptionEnabled()) {
3175            final IMountService mount = IMountService.Stub
3176                    .asInterface(ServiceManager.getService("mount"));
3177            if (mount == null) {
3178                Slog.w(TAG, "Early during boot, assuming locked");
3179                return false;
3180            }
3181            final long token = Binder.clearCallingIdentity();
3182            try {
3183                return mount.isUserKeyUnlocked(userId);
3184            } catch (RemoteException e) {
3185                throw e.rethrowAsRuntimeException();
3186            } finally {
3187                Binder.restoreCallingIdentity(token);
3188            }
3189        } else {
3190            return true;
3191        }
3192    }
3193
3194    /**
3195     * Augment the given flags depending on current user running state. This is
3196     * purposefully done before acquiring {@link #mPackages} lock.
3197     */
3198    private int augmentFlagsForUser(int flags, int userId) {
3199        if (!isUserKeyUnlocked(userId)) {
3200            flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3201        }
3202        return flags;
3203    }
3204
3205    @Override
3206    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3207        if (!sUserManager.exists(userId)) return null;
3208        flags = augmentFlagsForUser(flags, userId);
3209        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3210        synchronized (mPackages) {
3211            PackageParser.Activity a = mActivities.mActivities.get(component);
3212
3213            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3214            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3215                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3216                if (ps == null) return null;
3217                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3218                        userId);
3219            }
3220            if (mResolveComponentName.equals(component)) {
3221                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3222                        new PackageUserState(), userId);
3223            }
3224        }
3225        return null;
3226    }
3227
3228    @Override
3229    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3230            String resolvedType) {
3231        synchronized (mPackages) {
3232            if (component.equals(mResolveComponentName)) {
3233                // The resolver supports EVERYTHING!
3234                return true;
3235            }
3236            PackageParser.Activity a = mActivities.mActivities.get(component);
3237            if (a == null) {
3238                return false;
3239            }
3240            for (int i=0; i<a.intents.size(); i++) {
3241                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3242                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3243                    return true;
3244                }
3245            }
3246            return false;
3247        }
3248    }
3249
3250    @Override
3251    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3252        if (!sUserManager.exists(userId)) return null;
3253        flags = augmentFlagsForUser(flags, userId);
3254        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3255        synchronized (mPackages) {
3256            PackageParser.Activity a = mReceivers.mActivities.get(component);
3257            if (DEBUG_PACKAGE_INFO) Log.v(
3258                TAG, "getReceiverInfo " + component + ": " + a);
3259            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3260                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3261                if (ps == null) return null;
3262                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3263                        userId);
3264            }
3265        }
3266        return null;
3267    }
3268
3269    @Override
3270    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3271        if (!sUserManager.exists(userId)) return null;
3272        flags = augmentFlagsForUser(flags, userId);
3273        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3274        synchronized (mPackages) {
3275            PackageParser.Service s = mServices.mServices.get(component);
3276            if (DEBUG_PACKAGE_INFO) Log.v(
3277                TAG, "getServiceInfo " + component + ": " + s);
3278            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3279                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3280                if (ps == null) return null;
3281                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3282                        userId);
3283            }
3284        }
3285        return null;
3286    }
3287
3288    @Override
3289    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3290        if (!sUserManager.exists(userId)) return null;
3291        flags = augmentFlagsForUser(flags, userId);
3292        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3293        synchronized (mPackages) {
3294            PackageParser.Provider p = mProviders.mProviders.get(component);
3295            if (DEBUG_PACKAGE_INFO) Log.v(
3296                TAG, "getProviderInfo " + component + ": " + p);
3297            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3298                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3299                if (ps == null) return null;
3300                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3301                        userId);
3302            }
3303        }
3304        return null;
3305    }
3306
3307    @Override
3308    public String[] getSystemSharedLibraryNames() {
3309        Set<String> libSet;
3310        synchronized (mPackages) {
3311            libSet = mSharedLibraries.keySet();
3312            int size = libSet.size();
3313            if (size > 0) {
3314                String[] libs = new String[size];
3315                libSet.toArray(libs);
3316                return libs;
3317            }
3318        }
3319        return null;
3320    }
3321
3322    /**
3323     * @hide
3324     */
3325    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3326        synchronized (mPackages) {
3327            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3328            if (lib != null && lib.apk != null) {
3329                return mPackages.get(lib.apk);
3330            }
3331        }
3332        return null;
3333    }
3334
3335    @Override
3336    public FeatureInfo[] getSystemAvailableFeatures() {
3337        Collection<FeatureInfo> featSet;
3338        synchronized (mPackages) {
3339            featSet = mAvailableFeatures.values();
3340            int size = featSet.size();
3341            if (size > 0) {
3342                FeatureInfo[] features = new FeatureInfo[size+1];
3343                featSet.toArray(features);
3344                FeatureInfo fi = new FeatureInfo();
3345                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3346                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3347                features[size] = fi;
3348                return features;
3349            }
3350        }
3351        return null;
3352    }
3353
3354    @Override
3355    public boolean hasSystemFeature(String name) {
3356        synchronized (mPackages) {
3357            return mAvailableFeatures.containsKey(name);
3358        }
3359    }
3360
3361    private void checkValidCaller(int uid, int userId) {
3362        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3363            return;
3364
3365        throw new SecurityException("Caller uid=" + uid
3366                + " is not privileged to communicate with user=" + userId);
3367    }
3368
3369    @Override
3370    public int checkPermission(String permName, String pkgName, int userId) {
3371        if (!sUserManager.exists(userId)) {
3372            return PackageManager.PERMISSION_DENIED;
3373        }
3374
3375        synchronized (mPackages) {
3376            final PackageParser.Package p = mPackages.get(pkgName);
3377            if (p != null && p.mExtras != null) {
3378                final PackageSetting ps = (PackageSetting) p.mExtras;
3379                final PermissionsState permissionsState = ps.getPermissionsState();
3380                if (permissionsState.hasPermission(permName, userId)) {
3381                    return PackageManager.PERMISSION_GRANTED;
3382                }
3383                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3384                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3385                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3386                    return PackageManager.PERMISSION_GRANTED;
3387                }
3388            }
3389        }
3390
3391        return PackageManager.PERMISSION_DENIED;
3392    }
3393
3394    @Override
3395    public int checkUidPermission(String permName, int uid) {
3396        final int userId = UserHandle.getUserId(uid);
3397
3398        if (!sUserManager.exists(userId)) {
3399            return PackageManager.PERMISSION_DENIED;
3400        }
3401
3402        synchronized (mPackages) {
3403            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3404            if (obj != null) {
3405                final SettingBase ps = (SettingBase) obj;
3406                final PermissionsState permissionsState = ps.getPermissionsState();
3407                if (permissionsState.hasPermission(permName, userId)) {
3408                    return PackageManager.PERMISSION_GRANTED;
3409                }
3410                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3411                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3412                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3413                    return PackageManager.PERMISSION_GRANTED;
3414                }
3415            } else {
3416                ArraySet<String> perms = mSystemPermissions.get(uid);
3417                if (perms != null) {
3418                    if (perms.contains(permName)) {
3419                        return PackageManager.PERMISSION_GRANTED;
3420                    }
3421                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3422                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3423                        return PackageManager.PERMISSION_GRANTED;
3424                    }
3425                }
3426            }
3427        }
3428
3429        return PackageManager.PERMISSION_DENIED;
3430    }
3431
3432    @Override
3433    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3434        if (UserHandle.getCallingUserId() != userId) {
3435            mContext.enforceCallingPermission(
3436                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3437                    "isPermissionRevokedByPolicy for user " + userId);
3438        }
3439
3440        if (checkPermission(permission, packageName, userId)
3441                == PackageManager.PERMISSION_GRANTED) {
3442            return false;
3443        }
3444
3445        final long identity = Binder.clearCallingIdentity();
3446        try {
3447            final int flags = getPermissionFlags(permission, packageName, userId);
3448            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3449        } finally {
3450            Binder.restoreCallingIdentity(identity);
3451        }
3452    }
3453
3454    @Override
3455    public String getPermissionControllerPackageName() {
3456        synchronized (mPackages) {
3457            return mRequiredInstallerPackage;
3458        }
3459    }
3460
3461    /**
3462     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3463     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3464     * @param checkShell TODO(yamasani):
3465     * @param message the message to log on security exception
3466     */
3467    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3468            boolean checkShell, String message) {
3469        if (userId < 0) {
3470            throw new IllegalArgumentException("Invalid userId " + userId);
3471        }
3472        if (checkShell) {
3473            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3474        }
3475        if (userId == UserHandle.getUserId(callingUid)) return;
3476        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3477            if (requireFullPermission) {
3478                mContext.enforceCallingOrSelfPermission(
3479                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3480            } else {
3481                try {
3482                    mContext.enforceCallingOrSelfPermission(
3483                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3484                } catch (SecurityException se) {
3485                    mContext.enforceCallingOrSelfPermission(
3486                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3487                }
3488            }
3489        }
3490    }
3491
3492    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3493        if (callingUid == Process.SHELL_UID) {
3494            if (userHandle >= 0
3495                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3496                throw new SecurityException("Shell does not have permission to access user "
3497                        + userHandle);
3498            } else if (userHandle < 0) {
3499                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3500                        + Debug.getCallers(3));
3501            }
3502        }
3503    }
3504
3505    private BasePermission findPermissionTreeLP(String permName) {
3506        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3507            if (permName.startsWith(bp.name) &&
3508                    permName.length() > bp.name.length() &&
3509                    permName.charAt(bp.name.length()) == '.') {
3510                return bp;
3511            }
3512        }
3513        return null;
3514    }
3515
3516    private BasePermission checkPermissionTreeLP(String permName) {
3517        if (permName != null) {
3518            BasePermission bp = findPermissionTreeLP(permName);
3519            if (bp != null) {
3520                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3521                    return bp;
3522                }
3523                throw new SecurityException("Calling uid "
3524                        + Binder.getCallingUid()
3525                        + " is not allowed to add to permission tree "
3526                        + bp.name + " owned by uid " + bp.uid);
3527            }
3528        }
3529        throw new SecurityException("No permission tree found for " + permName);
3530    }
3531
3532    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3533        if (s1 == null) {
3534            return s2 == null;
3535        }
3536        if (s2 == null) {
3537            return false;
3538        }
3539        if (s1.getClass() != s2.getClass()) {
3540            return false;
3541        }
3542        return s1.equals(s2);
3543    }
3544
3545    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3546        if (pi1.icon != pi2.icon) return false;
3547        if (pi1.logo != pi2.logo) return false;
3548        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3549        if (!compareStrings(pi1.name, pi2.name)) return false;
3550        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3551        // We'll take care of setting this one.
3552        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3553        // These are not currently stored in settings.
3554        //if (!compareStrings(pi1.group, pi2.group)) return false;
3555        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3556        //if (pi1.labelRes != pi2.labelRes) return false;
3557        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3558        return true;
3559    }
3560
3561    int permissionInfoFootprint(PermissionInfo info) {
3562        int size = info.name.length();
3563        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3564        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3565        return size;
3566    }
3567
3568    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3569        int size = 0;
3570        for (BasePermission perm : mSettings.mPermissions.values()) {
3571            if (perm.uid == tree.uid) {
3572                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3573            }
3574        }
3575        return size;
3576    }
3577
3578    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3579        // We calculate the max size of permissions defined by this uid and throw
3580        // if that plus the size of 'info' would exceed our stated maximum.
3581        if (tree.uid != Process.SYSTEM_UID) {
3582            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3583            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3584                throw new SecurityException("Permission tree size cap exceeded");
3585            }
3586        }
3587    }
3588
3589    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3590        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3591            throw new SecurityException("Label must be specified in permission");
3592        }
3593        BasePermission tree = checkPermissionTreeLP(info.name);
3594        BasePermission bp = mSettings.mPermissions.get(info.name);
3595        boolean added = bp == null;
3596        boolean changed = true;
3597        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3598        if (added) {
3599            enforcePermissionCapLocked(info, tree);
3600            bp = new BasePermission(info.name, tree.sourcePackage,
3601                    BasePermission.TYPE_DYNAMIC);
3602        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3603            throw new SecurityException(
3604                    "Not allowed to modify non-dynamic permission "
3605                    + info.name);
3606        } else {
3607            if (bp.protectionLevel == fixedLevel
3608                    && bp.perm.owner.equals(tree.perm.owner)
3609                    && bp.uid == tree.uid
3610                    && comparePermissionInfos(bp.perm.info, info)) {
3611                changed = false;
3612            }
3613        }
3614        bp.protectionLevel = fixedLevel;
3615        info = new PermissionInfo(info);
3616        info.protectionLevel = fixedLevel;
3617        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3618        bp.perm.info.packageName = tree.perm.info.packageName;
3619        bp.uid = tree.uid;
3620        if (added) {
3621            mSettings.mPermissions.put(info.name, bp);
3622        }
3623        if (changed) {
3624            if (!async) {
3625                mSettings.writeLPr();
3626            } else {
3627                scheduleWriteSettingsLocked();
3628            }
3629        }
3630        return added;
3631    }
3632
3633    @Override
3634    public boolean addPermission(PermissionInfo info) {
3635        synchronized (mPackages) {
3636            return addPermissionLocked(info, false);
3637        }
3638    }
3639
3640    @Override
3641    public boolean addPermissionAsync(PermissionInfo info) {
3642        synchronized (mPackages) {
3643            return addPermissionLocked(info, true);
3644        }
3645    }
3646
3647    @Override
3648    public void removePermission(String name) {
3649        synchronized (mPackages) {
3650            checkPermissionTreeLP(name);
3651            BasePermission bp = mSettings.mPermissions.get(name);
3652            if (bp != null) {
3653                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3654                    throw new SecurityException(
3655                            "Not allowed to modify non-dynamic permission "
3656                            + name);
3657                }
3658                mSettings.mPermissions.remove(name);
3659                mSettings.writeLPr();
3660            }
3661        }
3662    }
3663
3664    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3665            BasePermission bp) {
3666        int index = pkg.requestedPermissions.indexOf(bp.name);
3667        if (index == -1) {
3668            throw new SecurityException("Package " + pkg.packageName
3669                    + " has not requested permission " + bp.name);
3670        }
3671        if (!bp.isRuntime() && !bp.isDevelopment()) {
3672            throw new SecurityException("Permission " + bp.name
3673                    + " is not a changeable permission type");
3674        }
3675    }
3676
3677    @Override
3678    public void grantRuntimePermission(String packageName, String name, final int userId) {
3679        if (!sUserManager.exists(userId)) {
3680            Log.e(TAG, "No such user:" + userId);
3681            return;
3682        }
3683
3684        mContext.enforceCallingOrSelfPermission(
3685                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3686                "grantRuntimePermission");
3687
3688        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3689                "grantRuntimePermission");
3690
3691        final int uid;
3692        final SettingBase sb;
3693
3694        synchronized (mPackages) {
3695            final PackageParser.Package pkg = mPackages.get(packageName);
3696            if (pkg == null) {
3697                throw new IllegalArgumentException("Unknown package: " + packageName);
3698            }
3699
3700            final BasePermission bp = mSettings.mPermissions.get(name);
3701            if (bp == null) {
3702                throw new IllegalArgumentException("Unknown permission: " + name);
3703            }
3704
3705            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3706
3707            // If a permission review is required for legacy apps we represent
3708            // their permissions as always granted runtime ones since we need
3709            // to keep the review required permission flag per user while an
3710            // install permission's state is shared across all users.
3711            if (Build.PERMISSIONS_REVIEW_REQUIRED
3712                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3713                    && bp.isRuntime()) {
3714                return;
3715            }
3716
3717            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3718            sb = (SettingBase) pkg.mExtras;
3719            if (sb == null) {
3720                throw new IllegalArgumentException("Unknown package: " + packageName);
3721            }
3722
3723            final PermissionsState permissionsState = sb.getPermissionsState();
3724
3725            final int flags = permissionsState.getPermissionFlags(name, userId);
3726            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3727                throw new SecurityException("Cannot grant system fixed permission: "
3728                        + name + " for package: " + packageName);
3729            }
3730
3731            if (bp.isDevelopment()) {
3732                // Development permissions must be handled specially, since they are not
3733                // normal runtime permissions.  For now they apply to all users.
3734                if (permissionsState.grantInstallPermission(bp) !=
3735                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3736                    scheduleWriteSettingsLocked();
3737                }
3738                return;
3739            }
3740
3741            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3742                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3743                return;
3744            }
3745
3746            final int result = permissionsState.grantRuntimePermission(bp, userId);
3747            switch (result) {
3748                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3749                    return;
3750                }
3751
3752                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3753                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3754                    mHandler.post(new Runnable() {
3755                        @Override
3756                        public void run() {
3757                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3758                        }
3759                    });
3760                }
3761                break;
3762            }
3763
3764            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3765
3766            // Not critical if that is lost - app has to request again.
3767            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3768        }
3769
3770        // Only need to do this if user is initialized. Otherwise it's a new user
3771        // and there are no processes running as the user yet and there's no need
3772        // to make an expensive call to remount processes for the changed permissions.
3773        if (READ_EXTERNAL_STORAGE.equals(name)
3774                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3775            final long token = Binder.clearCallingIdentity();
3776            try {
3777                if (sUserManager.isInitialized(userId)) {
3778                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3779                            MountServiceInternal.class);
3780                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3781                }
3782            } finally {
3783                Binder.restoreCallingIdentity(token);
3784            }
3785        }
3786    }
3787
3788    @Override
3789    public void revokeRuntimePermission(String packageName, String name, int userId) {
3790        if (!sUserManager.exists(userId)) {
3791            Log.e(TAG, "No such user:" + userId);
3792            return;
3793        }
3794
3795        mContext.enforceCallingOrSelfPermission(
3796                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3797                "revokeRuntimePermission");
3798
3799        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3800                "revokeRuntimePermission");
3801
3802        final int appId;
3803
3804        synchronized (mPackages) {
3805            final PackageParser.Package pkg = mPackages.get(packageName);
3806            if (pkg == null) {
3807                throw new IllegalArgumentException("Unknown package: " + packageName);
3808            }
3809
3810            final BasePermission bp = mSettings.mPermissions.get(name);
3811            if (bp == null) {
3812                throw new IllegalArgumentException("Unknown permission: " + name);
3813            }
3814
3815            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3816
3817            // If a permission review is required for legacy apps we represent
3818            // their permissions as always granted runtime ones since we need
3819            // to keep the review required permission flag per user while an
3820            // install permission's state is shared across all users.
3821            if (Build.PERMISSIONS_REVIEW_REQUIRED
3822                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3823                    && bp.isRuntime()) {
3824                return;
3825            }
3826
3827            SettingBase sb = (SettingBase) pkg.mExtras;
3828            if (sb == null) {
3829                throw new IllegalArgumentException("Unknown package: " + packageName);
3830            }
3831
3832            final PermissionsState permissionsState = sb.getPermissionsState();
3833
3834            final int flags = permissionsState.getPermissionFlags(name, userId);
3835            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3836                throw new SecurityException("Cannot revoke system fixed permission: "
3837                        + name + " for package: " + packageName);
3838            }
3839
3840            if (bp.isDevelopment()) {
3841                // Development permissions must be handled specially, since they are not
3842                // normal runtime permissions.  For now they apply to all users.
3843                if (permissionsState.revokeInstallPermission(bp) !=
3844                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3845                    scheduleWriteSettingsLocked();
3846                }
3847                return;
3848            }
3849
3850            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3851                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3852                return;
3853            }
3854
3855            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3856
3857            // Critical, after this call app should never have the permission.
3858            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3859
3860            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3861        }
3862
3863        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3864    }
3865
3866    @Override
3867    public void resetRuntimePermissions() {
3868        mContext.enforceCallingOrSelfPermission(
3869                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3870                "revokeRuntimePermission");
3871
3872        int callingUid = Binder.getCallingUid();
3873        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3874            mContext.enforceCallingOrSelfPermission(
3875                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3876                    "resetRuntimePermissions");
3877        }
3878
3879        synchronized (mPackages) {
3880            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3881            for (int userId : UserManagerService.getInstance().getUserIds()) {
3882                final int packageCount = mPackages.size();
3883                for (int i = 0; i < packageCount; i++) {
3884                    PackageParser.Package pkg = mPackages.valueAt(i);
3885                    if (!(pkg.mExtras instanceof PackageSetting)) {
3886                        continue;
3887                    }
3888                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3889                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3890                }
3891            }
3892        }
3893    }
3894
3895    @Override
3896    public int getPermissionFlags(String name, String packageName, int userId) {
3897        if (!sUserManager.exists(userId)) {
3898            return 0;
3899        }
3900
3901        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3902
3903        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3904                "getPermissionFlags");
3905
3906        synchronized (mPackages) {
3907            final PackageParser.Package pkg = mPackages.get(packageName);
3908            if (pkg == null) {
3909                throw new IllegalArgumentException("Unknown package: " + packageName);
3910            }
3911
3912            final BasePermission bp = mSettings.mPermissions.get(name);
3913            if (bp == null) {
3914                throw new IllegalArgumentException("Unknown permission: " + name);
3915            }
3916
3917            SettingBase sb = (SettingBase) pkg.mExtras;
3918            if (sb == null) {
3919                throw new IllegalArgumentException("Unknown package: " + packageName);
3920            }
3921
3922            PermissionsState permissionsState = sb.getPermissionsState();
3923            return permissionsState.getPermissionFlags(name, userId);
3924        }
3925    }
3926
3927    @Override
3928    public void updatePermissionFlags(String name, String packageName, int flagMask,
3929            int flagValues, int userId) {
3930        if (!sUserManager.exists(userId)) {
3931            return;
3932        }
3933
3934        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3935
3936        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3937                "updatePermissionFlags");
3938
3939        // Only the system can change these flags and nothing else.
3940        if (getCallingUid() != Process.SYSTEM_UID) {
3941            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3942            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3943            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3944            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3945            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3946        }
3947
3948        synchronized (mPackages) {
3949            final PackageParser.Package pkg = mPackages.get(packageName);
3950            if (pkg == null) {
3951                throw new IllegalArgumentException("Unknown package: " + packageName);
3952            }
3953
3954            final BasePermission bp = mSettings.mPermissions.get(name);
3955            if (bp == null) {
3956                throw new IllegalArgumentException("Unknown permission: " + name);
3957            }
3958
3959            SettingBase sb = (SettingBase) pkg.mExtras;
3960            if (sb == null) {
3961                throw new IllegalArgumentException("Unknown package: " + packageName);
3962            }
3963
3964            PermissionsState permissionsState = sb.getPermissionsState();
3965
3966            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3967
3968            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3969                // Install and runtime permissions are stored in different places,
3970                // so figure out what permission changed and persist the change.
3971                if (permissionsState.getInstallPermissionState(name) != null) {
3972                    scheduleWriteSettingsLocked();
3973                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3974                        || hadState) {
3975                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3976                }
3977            }
3978        }
3979    }
3980
3981    /**
3982     * Update the permission flags for all packages and runtime permissions of a user in order
3983     * to allow device or profile owner to remove POLICY_FIXED.
3984     */
3985    @Override
3986    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3987        if (!sUserManager.exists(userId)) {
3988            return;
3989        }
3990
3991        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3992
3993        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3994                "updatePermissionFlagsForAllApps");
3995
3996        // Only the system can change system fixed flags.
3997        if (getCallingUid() != Process.SYSTEM_UID) {
3998            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3999            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4000        }
4001
4002        synchronized (mPackages) {
4003            boolean changed = false;
4004            final int packageCount = mPackages.size();
4005            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4006                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4007                SettingBase sb = (SettingBase) pkg.mExtras;
4008                if (sb == null) {
4009                    continue;
4010                }
4011                PermissionsState permissionsState = sb.getPermissionsState();
4012                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4013                        userId, flagMask, flagValues);
4014            }
4015            if (changed) {
4016                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4017            }
4018        }
4019    }
4020
4021    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4022        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4023                != PackageManager.PERMISSION_GRANTED
4024            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4025                != PackageManager.PERMISSION_GRANTED) {
4026            throw new SecurityException(message + " requires "
4027                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4028                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4029        }
4030    }
4031
4032    @Override
4033    public boolean shouldShowRequestPermissionRationale(String permissionName,
4034            String packageName, int userId) {
4035        if (UserHandle.getCallingUserId() != userId) {
4036            mContext.enforceCallingPermission(
4037                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4038                    "canShowRequestPermissionRationale for user " + userId);
4039        }
4040
4041        final int uid = getPackageUid(packageName, userId);
4042        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4043            return false;
4044        }
4045
4046        if (checkPermission(permissionName, packageName, userId)
4047                == PackageManager.PERMISSION_GRANTED) {
4048            return false;
4049        }
4050
4051        final int flags;
4052
4053        final long identity = Binder.clearCallingIdentity();
4054        try {
4055            flags = getPermissionFlags(permissionName,
4056                    packageName, userId);
4057        } finally {
4058            Binder.restoreCallingIdentity(identity);
4059        }
4060
4061        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4062                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4063                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4064
4065        if ((flags & fixedFlags) != 0) {
4066            return false;
4067        }
4068
4069        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4070    }
4071
4072    @Override
4073    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4074        mContext.enforceCallingOrSelfPermission(
4075                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4076                "addOnPermissionsChangeListener");
4077
4078        synchronized (mPackages) {
4079            mOnPermissionChangeListeners.addListenerLocked(listener);
4080        }
4081    }
4082
4083    @Override
4084    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4085        synchronized (mPackages) {
4086            mOnPermissionChangeListeners.removeListenerLocked(listener);
4087        }
4088    }
4089
4090    @Override
4091    public boolean isProtectedBroadcast(String actionName) {
4092        synchronized (mPackages) {
4093            if (mProtectedBroadcasts.contains(actionName)) {
4094                return true;
4095            } else if (actionName != null
4096                    && actionName.startsWith("android.net.netmon.lingerExpired")) {
4097                // TODO: remove this terrible hack
4098                return true;
4099            }
4100        }
4101        return false;
4102    }
4103
4104    @Override
4105    public int checkSignatures(String pkg1, String pkg2) {
4106        synchronized (mPackages) {
4107            final PackageParser.Package p1 = mPackages.get(pkg1);
4108            final PackageParser.Package p2 = mPackages.get(pkg2);
4109            if (p1 == null || p1.mExtras == null
4110                    || p2 == null || p2.mExtras == null) {
4111                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4112            }
4113            return compareSignatures(p1.mSignatures, p2.mSignatures);
4114        }
4115    }
4116
4117    @Override
4118    public int checkUidSignatures(int uid1, int uid2) {
4119        // Map to base uids.
4120        uid1 = UserHandle.getAppId(uid1);
4121        uid2 = UserHandle.getAppId(uid2);
4122        // reader
4123        synchronized (mPackages) {
4124            Signature[] s1;
4125            Signature[] s2;
4126            Object obj = mSettings.getUserIdLPr(uid1);
4127            if (obj != null) {
4128                if (obj instanceof SharedUserSetting) {
4129                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4130                } else if (obj instanceof PackageSetting) {
4131                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4132                } else {
4133                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4134                }
4135            } else {
4136                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4137            }
4138            obj = mSettings.getUserIdLPr(uid2);
4139            if (obj != null) {
4140                if (obj instanceof SharedUserSetting) {
4141                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4142                } else if (obj instanceof PackageSetting) {
4143                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4144                } else {
4145                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4146                }
4147            } else {
4148                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4149            }
4150            return compareSignatures(s1, s2);
4151        }
4152    }
4153
4154    private void killUid(int appId, int userId, String reason) {
4155        final long identity = Binder.clearCallingIdentity();
4156        try {
4157            IActivityManager am = ActivityManagerNative.getDefault();
4158            if (am != null) {
4159                try {
4160                    am.killUid(appId, userId, reason);
4161                } catch (RemoteException e) {
4162                    /* ignore - same process */
4163                }
4164            }
4165        } finally {
4166            Binder.restoreCallingIdentity(identity);
4167        }
4168    }
4169
4170    /**
4171     * Compares two sets of signatures. Returns:
4172     * <br />
4173     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4174     * <br />
4175     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4176     * <br />
4177     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4178     * <br />
4179     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4180     * <br />
4181     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4182     */
4183    static int compareSignatures(Signature[] s1, Signature[] s2) {
4184        if (s1 == null) {
4185            return s2 == null
4186                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4187                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4188        }
4189
4190        if (s2 == null) {
4191            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4192        }
4193
4194        if (s1.length != s2.length) {
4195            return PackageManager.SIGNATURE_NO_MATCH;
4196        }
4197
4198        // Since both signature sets are of size 1, we can compare without HashSets.
4199        if (s1.length == 1) {
4200            return s1[0].equals(s2[0]) ?
4201                    PackageManager.SIGNATURE_MATCH :
4202                    PackageManager.SIGNATURE_NO_MATCH;
4203        }
4204
4205        ArraySet<Signature> set1 = new ArraySet<Signature>();
4206        for (Signature sig : s1) {
4207            set1.add(sig);
4208        }
4209        ArraySet<Signature> set2 = new ArraySet<Signature>();
4210        for (Signature sig : s2) {
4211            set2.add(sig);
4212        }
4213        // Make sure s2 contains all signatures in s1.
4214        if (set1.equals(set2)) {
4215            return PackageManager.SIGNATURE_MATCH;
4216        }
4217        return PackageManager.SIGNATURE_NO_MATCH;
4218    }
4219
4220    /**
4221     * If the database version for this type of package (internal storage or
4222     * external storage) is less than the version where package signatures
4223     * were updated, return true.
4224     */
4225    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4226        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4227        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4228    }
4229
4230    /**
4231     * Used for backward compatibility to make sure any packages with
4232     * certificate chains get upgraded to the new style. {@code existingSigs}
4233     * will be in the old format (since they were stored on disk from before the
4234     * system upgrade) and {@code scannedSigs} will be in the newer format.
4235     */
4236    private int compareSignaturesCompat(PackageSignatures existingSigs,
4237            PackageParser.Package scannedPkg) {
4238        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4239            return PackageManager.SIGNATURE_NO_MATCH;
4240        }
4241
4242        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4243        for (Signature sig : existingSigs.mSignatures) {
4244            existingSet.add(sig);
4245        }
4246        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4247        for (Signature sig : scannedPkg.mSignatures) {
4248            try {
4249                Signature[] chainSignatures = sig.getChainSignatures();
4250                for (Signature chainSig : chainSignatures) {
4251                    scannedCompatSet.add(chainSig);
4252                }
4253            } catch (CertificateEncodingException e) {
4254                scannedCompatSet.add(sig);
4255            }
4256        }
4257        /*
4258         * Make sure the expanded scanned set contains all signatures in the
4259         * existing one.
4260         */
4261        if (scannedCompatSet.equals(existingSet)) {
4262            // Migrate the old signatures to the new scheme.
4263            existingSigs.assignSignatures(scannedPkg.mSignatures);
4264            // The new KeySets will be re-added later in the scanning process.
4265            synchronized (mPackages) {
4266                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4267            }
4268            return PackageManager.SIGNATURE_MATCH;
4269        }
4270        return PackageManager.SIGNATURE_NO_MATCH;
4271    }
4272
4273    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4274        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4275        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4276    }
4277
4278    private int compareSignaturesRecover(PackageSignatures existingSigs,
4279            PackageParser.Package scannedPkg) {
4280        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4281            return PackageManager.SIGNATURE_NO_MATCH;
4282        }
4283
4284        String msg = null;
4285        try {
4286            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4287                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4288                        + scannedPkg.packageName);
4289                return PackageManager.SIGNATURE_MATCH;
4290            }
4291        } catch (CertificateException e) {
4292            msg = e.getMessage();
4293        }
4294
4295        logCriticalInfo(Log.INFO,
4296                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4297        return PackageManager.SIGNATURE_NO_MATCH;
4298    }
4299
4300    @Override
4301    public String[] getPackagesForUid(int uid) {
4302        uid = UserHandle.getAppId(uid);
4303        // reader
4304        synchronized (mPackages) {
4305            Object obj = mSettings.getUserIdLPr(uid);
4306            if (obj instanceof SharedUserSetting) {
4307                final SharedUserSetting sus = (SharedUserSetting) obj;
4308                final int N = sus.packages.size();
4309                final String[] res = new String[N];
4310                final Iterator<PackageSetting> it = sus.packages.iterator();
4311                int i = 0;
4312                while (it.hasNext()) {
4313                    res[i++] = it.next().name;
4314                }
4315                return res;
4316            } else if (obj instanceof PackageSetting) {
4317                final PackageSetting ps = (PackageSetting) obj;
4318                return new String[] { ps.name };
4319            }
4320        }
4321        return null;
4322    }
4323
4324    @Override
4325    public String getNameForUid(int uid) {
4326        // reader
4327        synchronized (mPackages) {
4328            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4329            if (obj instanceof SharedUserSetting) {
4330                final SharedUserSetting sus = (SharedUserSetting) obj;
4331                return sus.name + ":" + sus.userId;
4332            } else if (obj instanceof PackageSetting) {
4333                final PackageSetting ps = (PackageSetting) obj;
4334                return ps.name;
4335            }
4336        }
4337        return null;
4338    }
4339
4340    @Override
4341    public int getUidForSharedUser(String sharedUserName) {
4342        if(sharedUserName == null) {
4343            return -1;
4344        }
4345        // reader
4346        synchronized (mPackages) {
4347            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4348            if (suid == null) {
4349                return -1;
4350            }
4351            return suid.userId;
4352        }
4353    }
4354
4355    @Override
4356    public int getFlagsForUid(int uid) {
4357        synchronized (mPackages) {
4358            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4359            if (obj instanceof SharedUserSetting) {
4360                final SharedUserSetting sus = (SharedUserSetting) obj;
4361                return sus.pkgFlags;
4362            } else if (obj instanceof PackageSetting) {
4363                final PackageSetting ps = (PackageSetting) obj;
4364                return ps.pkgFlags;
4365            }
4366        }
4367        return 0;
4368    }
4369
4370    @Override
4371    public int getPrivateFlagsForUid(int uid) {
4372        synchronized (mPackages) {
4373            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4374            if (obj instanceof SharedUserSetting) {
4375                final SharedUserSetting sus = (SharedUserSetting) obj;
4376                return sus.pkgPrivateFlags;
4377            } else if (obj instanceof PackageSetting) {
4378                final PackageSetting ps = (PackageSetting) obj;
4379                return ps.pkgPrivateFlags;
4380            }
4381        }
4382        return 0;
4383    }
4384
4385    @Override
4386    public boolean isUidPrivileged(int uid) {
4387        uid = UserHandle.getAppId(uid);
4388        // reader
4389        synchronized (mPackages) {
4390            Object obj = mSettings.getUserIdLPr(uid);
4391            if (obj instanceof SharedUserSetting) {
4392                final SharedUserSetting sus = (SharedUserSetting) obj;
4393                final Iterator<PackageSetting> it = sus.packages.iterator();
4394                while (it.hasNext()) {
4395                    if (it.next().isPrivileged()) {
4396                        return true;
4397                    }
4398                }
4399            } else if (obj instanceof PackageSetting) {
4400                final PackageSetting ps = (PackageSetting) obj;
4401                return ps.isPrivileged();
4402            }
4403        }
4404        return false;
4405    }
4406
4407    @Override
4408    public String[] getAppOpPermissionPackages(String permissionName) {
4409        synchronized (mPackages) {
4410            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4411            if (pkgs == null) {
4412                return null;
4413            }
4414            return pkgs.toArray(new String[pkgs.size()]);
4415        }
4416    }
4417
4418    @Override
4419    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4420            int flags, int userId) {
4421        if (!sUserManager.exists(userId)) return null;
4422        flags = augmentFlagsForUser(flags, userId);
4423        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4424        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4425        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4426    }
4427
4428    @Override
4429    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4430            IntentFilter filter, int match, ComponentName activity) {
4431        final int userId = UserHandle.getCallingUserId();
4432        if (DEBUG_PREFERRED) {
4433            Log.v(TAG, "setLastChosenActivity intent=" + intent
4434                + " resolvedType=" + resolvedType
4435                + " flags=" + flags
4436                + " filter=" + filter
4437                + " match=" + match
4438                + " activity=" + activity);
4439            filter.dump(new PrintStreamPrinter(System.out), "    ");
4440        }
4441        intent.setComponent(null);
4442        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4443        // Find any earlier preferred or last chosen entries and nuke them
4444        findPreferredActivity(intent, resolvedType,
4445                flags, query, 0, false, true, false, userId);
4446        // Add the new activity as the last chosen for this filter
4447        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4448                "Setting last chosen");
4449    }
4450
4451    @Override
4452    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4453        final int userId = UserHandle.getCallingUserId();
4454        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4455        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4456        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4457                false, false, false, userId);
4458    }
4459
4460    private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) {
4461        MessageDigest digest = null;
4462        try {
4463            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4464        } catch (NoSuchAlgorithmException e) {
4465            // If we can't create a digest, ignore ephemeral apps.
4466            return false;
4467        }
4468
4469        final byte[] hostBytes = intent.getData().getHost().getBytes();
4470        final byte[] digestBytes = digest.digest(hostBytes);
4471        int shaPrefix =
4472                digestBytes[0] << 24
4473                | digestBytes[1] << 16
4474                | digestBytes[2] << 8
4475                | digestBytes[3] << 0;
4476        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4477                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4478        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4479            // No hash prefix match; there are no ephemeral apps for this domain.
4480            return false;
4481        }
4482        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4483            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4484            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4485                continue;
4486            }
4487            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4488            // No filters; this should never happen.
4489            if (filters.isEmpty()) {
4490                continue;
4491            }
4492            // We have a domain match; resolve the filters to see if anything matches.
4493            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4494            for (int j = filters.size() - 1; j >= 0; --j) {
4495                ephemeralResolver.addFilter(filters.get(j));
4496            }
4497            List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent(
4498                    intent, resolvedType, false /*defaultOnly*/, userId);
4499            return !ephemeralResolveList.isEmpty();
4500        }
4501        // Hash or filter mis-match; no ephemeral apps for this domain.
4502        return false;
4503    }
4504
4505    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4506            int flags, List<ResolveInfo> query, int userId) {
4507        final boolean isWebUri = hasWebURI(intent);
4508        // Check whether or not an ephemeral app exists to handle the URI.
4509        if (isWebUri && mEphemeralResolverConnection != null) {
4510            // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution.
4511            boolean hasAlwaysHandler = false;
4512            synchronized (mPackages) {
4513                final int count = query.size();
4514                for (int n=0; n<count; n++) {
4515                    ResolveInfo info = query.get(n);
4516                    String packageName = info.activityInfo.packageName;
4517                    PackageSetting ps = mSettings.mPackages.get(packageName);
4518                    if (ps != null) {
4519                        // Try to get the status from User settings first
4520                        long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4521                        int status = (int) (packedStatus >> 32);
4522                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4523                                || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4524                            hasAlwaysHandler = true;
4525                            break;
4526                        }
4527                    }
4528                }
4529            }
4530
4531            // Only consider installing an ephemeral app if there isn't already a verified handler.
4532            // We've determined that there's an ephemeral app available for the URI, ignore any
4533            // ResolveInfo's and just return the ephemeral installer
4534            if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) {
4535                if (DEBUG_EPHEMERAL) {
4536                    Slog.v(TAG, "Resolving to the ephemeral installer");
4537                }
4538                // ditch the result and return a ResolveInfo to launch the ephemeral installer
4539                ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo);
4540                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4541                // make a deep copy of the applicationInfo
4542                ri.activityInfo.applicationInfo = new ApplicationInfo(
4543                        ri.activityInfo.applicationInfo);
4544                if (userId != 0) {
4545                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4546                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4547                }
4548                return ri;
4549            }
4550        }
4551        if (query != null) {
4552            final int N = query.size();
4553            if (N == 1) {
4554                return query.get(0);
4555            } else if (N > 1) {
4556                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4557                // If there is more than one activity with the same priority,
4558                // then let the user decide between them.
4559                ResolveInfo r0 = query.get(0);
4560                ResolveInfo r1 = query.get(1);
4561                if (DEBUG_INTENT_MATCHING || debug) {
4562                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4563                            + r1.activityInfo.name + "=" + r1.priority);
4564                }
4565                // If the first activity has a higher priority, or a different
4566                // default, then it is always desireable to pick it.
4567                if (r0.priority != r1.priority
4568                        || r0.preferredOrder != r1.preferredOrder
4569                        || r0.isDefault != r1.isDefault) {
4570                    return query.get(0);
4571                }
4572                // If we have saved a preference for a preferred activity for
4573                // this Intent, use that.
4574                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4575                        flags, query, r0.priority, true, false, debug, userId);
4576                if (ri != null) {
4577                    return ri;
4578                }
4579                ri = new ResolveInfo(mResolveInfo);
4580                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4581                ri.activityInfo.applicationInfo = new ApplicationInfo(
4582                        ri.activityInfo.applicationInfo);
4583                if (userId != 0) {
4584                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4585                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4586                }
4587                // Make sure that the resolver is displayable in car mode
4588                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4589                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4590                return ri;
4591            }
4592        }
4593        return null;
4594    }
4595
4596    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4597            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4598        final int N = query.size();
4599        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4600                .get(userId);
4601        // Get the list of persistent preferred activities that handle the intent
4602        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4603        List<PersistentPreferredActivity> pprefs = ppir != null
4604                ? ppir.queryIntent(intent, resolvedType,
4605                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4606                : null;
4607        if (pprefs != null && pprefs.size() > 0) {
4608            final int M = pprefs.size();
4609            for (int i=0; i<M; i++) {
4610                final PersistentPreferredActivity ppa = pprefs.get(i);
4611                if (DEBUG_PREFERRED || debug) {
4612                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4613                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4614                            + "\n  component=" + ppa.mComponent);
4615                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4616                }
4617                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4618                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4619                if (DEBUG_PREFERRED || debug) {
4620                    Slog.v(TAG, "Found persistent preferred activity:");
4621                    if (ai != null) {
4622                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4623                    } else {
4624                        Slog.v(TAG, "  null");
4625                    }
4626                }
4627                if (ai == null) {
4628                    // This previously registered persistent preferred activity
4629                    // component is no longer known. Ignore it and do NOT remove it.
4630                    continue;
4631                }
4632                for (int j=0; j<N; j++) {
4633                    final ResolveInfo ri = query.get(j);
4634                    if (!ri.activityInfo.applicationInfo.packageName
4635                            .equals(ai.applicationInfo.packageName)) {
4636                        continue;
4637                    }
4638                    if (!ri.activityInfo.name.equals(ai.name)) {
4639                        continue;
4640                    }
4641                    //  Found a persistent preference that can handle the intent.
4642                    if (DEBUG_PREFERRED || debug) {
4643                        Slog.v(TAG, "Returning persistent preferred activity: " +
4644                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4645                    }
4646                    return ri;
4647                }
4648            }
4649        }
4650        return null;
4651    }
4652
4653    // TODO: handle preferred activities missing while user has amnesia
4654    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4655            List<ResolveInfo> query, int priority, boolean always,
4656            boolean removeMatches, boolean debug, int userId) {
4657        if (!sUserManager.exists(userId)) return null;
4658        flags = augmentFlagsForUser(flags, userId);
4659        // writer
4660        synchronized (mPackages) {
4661            if (intent.getSelector() != null) {
4662                intent = intent.getSelector();
4663            }
4664            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4665
4666            // Try to find a matching persistent preferred activity.
4667            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4668                    debug, userId);
4669
4670            // If a persistent preferred activity matched, use it.
4671            if (pri != null) {
4672                return pri;
4673            }
4674
4675            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4676            // Get the list of preferred activities that handle the intent
4677            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4678            List<PreferredActivity> prefs = pir != null
4679                    ? pir.queryIntent(intent, resolvedType,
4680                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4681                    : null;
4682            if (prefs != null && prefs.size() > 0) {
4683                boolean changed = false;
4684                try {
4685                    // First figure out how good the original match set is.
4686                    // We will only allow preferred activities that came
4687                    // from the same match quality.
4688                    int match = 0;
4689
4690                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4691
4692                    final int N = query.size();
4693                    for (int j=0; j<N; j++) {
4694                        final ResolveInfo ri = query.get(j);
4695                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4696                                + ": 0x" + Integer.toHexString(match));
4697                        if (ri.match > match) {
4698                            match = ri.match;
4699                        }
4700                    }
4701
4702                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4703                            + Integer.toHexString(match));
4704
4705                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4706                    final int M = prefs.size();
4707                    for (int i=0; i<M; i++) {
4708                        final PreferredActivity pa = prefs.get(i);
4709                        if (DEBUG_PREFERRED || debug) {
4710                            Slog.v(TAG, "Checking PreferredActivity ds="
4711                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4712                                    + "\n  component=" + pa.mPref.mComponent);
4713                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4714                        }
4715                        if (pa.mPref.mMatch != match) {
4716                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4717                                    + Integer.toHexString(pa.mPref.mMatch));
4718                            continue;
4719                        }
4720                        // If it's not an "always" type preferred activity and that's what we're
4721                        // looking for, skip it.
4722                        if (always && !pa.mPref.mAlways) {
4723                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4724                            continue;
4725                        }
4726                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4727                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4728                        if (DEBUG_PREFERRED || debug) {
4729                            Slog.v(TAG, "Found preferred activity:");
4730                            if (ai != null) {
4731                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4732                            } else {
4733                                Slog.v(TAG, "  null");
4734                            }
4735                        }
4736                        if (ai == null) {
4737                            // This previously registered preferred activity
4738                            // component is no longer known.  Most likely an update
4739                            // to the app was installed and in the new version this
4740                            // component no longer exists.  Clean it up by removing
4741                            // it from the preferred activities list, and skip it.
4742                            Slog.w(TAG, "Removing dangling preferred activity: "
4743                                    + pa.mPref.mComponent);
4744                            pir.removeFilter(pa);
4745                            changed = true;
4746                            continue;
4747                        }
4748                        for (int j=0; j<N; j++) {
4749                            final ResolveInfo ri = query.get(j);
4750                            if (!ri.activityInfo.applicationInfo.packageName
4751                                    .equals(ai.applicationInfo.packageName)) {
4752                                continue;
4753                            }
4754                            if (!ri.activityInfo.name.equals(ai.name)) {
4755                                continue;
4756                            }
4757
4758                            if (removeMatches) {
4759                                pir.removeFilter(pa);
4760                                changed = true;
4761                                if (DEBUG_PREFERRED) {
4762                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4763                                }
4764                                break;
4765                            }
4766
4767                            // Okay we found a previously set preferred or last chosen app.
4768                            // If the result set is different from when this
4769                            // was created, we need to clear it and re-ask the
4770                            // user their preference, if we're looking for an "always" type entry.
4771                            if (always && !pa.mPref.sameSet(query)) {
4772                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4773                                        + intent + " type " + resolvedType);
4774                                if (DEBUG_PREFERRED) {
4775                                    Slog.v(TAG, "Removing preferred activity since set changed "
4776                                            + pa.mPref.mComponent);
4777                                }
4778                                pir.removeFilter(pa);
4779                                // Re-add the filter as a "last chosen" entry (!always)
4780                                PreferredActivity lastChosen = new PreferredActivity(
4781                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4782                                pir.addFilter(lastChosen);
4783                                changed = true;
4784                                return null;
4785                            }
4786
4787                            // Yay! Either the set matched or we're looking for the last chosen
4788                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4789                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4790                            return ri;
4791                        }
4792                    }
4793                } finally {
4794                    if (changed) {
4795                        if (DEBUG_PREFERRED) {
4796                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4797                        }
4798                        scheduleWritePackageRestrictionsLocked(userId);
4799                    }
4800                }
4801            }
4802        }
4803        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4804        return null;
4805    }
4806
4807    /*
4808     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4809     */
4810    @Override
4811    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4812            int targetUserId) {
4813        mContext.enforceCallingOrSelfPermission(
4814                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4815        List<CrossProfileIntentFilter> matches =
4816                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4817        if (matches != null) {
4818            int size = matches.size();
4819            for (int i = 0; i < size; i++) {
4820                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4821            }
4822        }
4823        if (hasWebURI(intent)) {
4824            // cross-profile app linking works only towards the parent.
4825            final UserInfo parent = getProfileParent(sourceUserId);
4826            synchronized(mPackages) {
4827                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4828                        intent, resolvedType, 0, sourceUserId, parent.id);
4829                return xpDomainInfo != null;
4830            }
4831        }
4832        return false;
4833    }
4834
4835    private UserInfo getProfileParent(int userId) {
4836        final long identity = Binder.clearCallingIdentity();
4837        try {
4838            return sUserManager.getProfileParent(userId);
4839        } finally {
4840            Binder.restoreCallingIdentity(identity);
4841        }
4842    }
4843
4844    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4845            String resolvedType, int userId) {
4846        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4847        if (resolver != null) {
4848            return resolver.queryIntent(intent, resolvedType, false, userId);
4849        }
4850        return null;
4851    }
4852
4853    @Override
4854    public List<ResolveInfo> queryIntentActivities(Intent intent,
4855            String resolvedType, int flags, int userId) {
4856        if (!sUserManager.exists(userId)) return Collections.emptyList();
4857        flags = augmentFlagsForUser(flags, userId);
4858        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4859        ComponentName comp = intent.getComponent();
4860        if (comp == null) {
4861            if (intent.getSelector() != null) {
4862                intent = intent.getSelector();
4863                comp = intent.getComponent();
4864            }
4865        }
4866
4867        if (comp != null) {
4868            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4869            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4870            if (ai != null) {
4871                final ResolveInfo ri = new ResolveInfo();
4872                ri.activityInfo = ai;
4873                list.add(ri);
4874            }
4875            return list;
4876        }
4877
4878        // reader
4879        synchronized (mPackages) {
4880            final String pkgName = intent.getPackage();
4881            if (pkgName == null) {
4882                List<CrossProfileIntentFilter> matchingFilters =
4883                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4884                // Check for results that need to skip the current profile.
4885                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4886                        resolvedType, flags, userId);
4887                if (xpResolveInfo != null) {
4888                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4889                    result.add(xpResolveInfo);
4890                    return filterIfNotSystemUser(result, userId);
4891                }
4892
4893                // Check for results in the current profile.
4894                List<ResolveInfo> result = mActivities.queryIntent(
4895                        intent, resolvedType, flags, userId);
4896                result = filterIfNotSystemUser(result, userId);
4897
4898                // Check for cross profile results.
4899                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4900                xpResolveInfo = queryCrossProfileIntents(
4901                        matchingFilters, intent, resolvedType, flags, userId,
4902                        hasNonNegativePriorityResult);
4903                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4904                    boolean isVisibleToUser = filterIfNotSystemUser(
4905                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4906                    if (isVisibleToUser) {
4907                        result.add(xpResolveInfo);
4908                        Collections.sort(result, mResolvePrioritySorter);
4909                    }
4910                }
4911                if (hasWebURI(intent)) {
4912                    CrossProfileDomainInfo xpDomainInfo = null;
4913                    final UserInfo parent = getProfileParent(userId);
4914                    if (parent != null) {
4915                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4916                                flags, userId, parent.id);
4917                    }
4918                    if (xpDomainInfo != null) {
4919                        if (xpResolveInfo != null) {
4920                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4921                            // in the result.
4922                            result.remove(xpResolveInfo);
4923                        }
4924                        if (result.size() == 0) {
4925                            result.add(xpDomainInfo.resolveInfo);
4926                            return result;
4927                        }
4928                    } else if (result.size() <= 1) {
4929                        return result;
4930                    }
4931                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4932                            xpDomainInfo, userId);
4933                    Collections.sort(result, mResolvePrioritySorter);
4934                }
4935                return result;
4936            }
4937            final PackageParser.Package pkg = mPackages.get(pkgName);
4938            if (pkg != null) {
4939                return filterIfNotSystemUser(
4940                        mActivities.queryIntentForPackage(
4941                                intent, resolvedType, flags, pkg.activities, userId),
4942                        userId);
4943            }
4944            return new ArrayList<ResolveInfo>();
4945        }
4946    }
4947
4948    private static class CrossProfileDomainInfo {
4949        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4950        ResolveInfo resolveInfo;
4951        /* Best domain verification status of the activities found in the other profile */
4952        int bestDomainVerificationStatus;
4953    }
4954
4955    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4956            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4957        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4958                sourceUserId)) {
4959            return null;
4960        }
4961        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4962                resolvedType, flags, parentUserId);
4963
4964        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4965            return null;
4966        }
4967        CrossProfileDomainInfo result = null;
4968        int size = resultTargetUser.size();
4969        for (int i = 0; i < size; i++) {
4970            ResolveInfo riTargetUser = resultTargetUser.get(i);
4971            // Intent filter verification is only for filters that specify a host. So don't return
4972            // those that handle all web uris.
4973            if (riTargetUser.handleAllWebDataURI) {
4974                continue;
4975            }
4976            String packageName = riTargetUser.activityInfo.packageName;
4977            PackageSetting ps = mSettings.mPackages.get(packageName);
4978            if (ps == null) {
4979                continue;
4980            }
4981            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4982            int status = (int)(verificationState >> 32);
4983            if (result == null) {
4984                result = new CrossProfileDomainInfo();
4985                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4986                        sourceUserId, parentUserId);
4987                result.bestDomainVerificationStatus = status;
4988            } else {
4989                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4990                        result.bestDomainVerificationStatus);
4991            }
4992        }
4993        // Don't consider matches with status NEVER across profiles.
4994        if (result != null && result.bestDomainVerificationStatus
4995                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4996            return null;
4997        }
4998        return result;
4999    }
5000
5001    /**
5002     * Verification statuses are ordered from the worse to the best, except for
5003     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5004     */
5005    private int bestDomainVerificationStatus(int status1, int status2) {
5006        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5007            return status2;
5008        }
5009        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5010            return status1;
5011        }
5012        return (int) MathUtils.max(status1, status2);
5013    }
5014
5015    private boolean isUserEnabled(int userId) {
5016        long callingId = Binder.clearCallingIdentity();
5017        try {
5018            UserInfo userInfo = sUserManager.getUserInfo(userId);
5019            return userInfo != null && userInfo.isEnabled();
5020        } finally {
5021            Binder.restoreCallingIdentity(callingId);
5022        }
5023    }
5024
5025    /**
5026     * Filter out activities with systemUserOnly flag set, when current user is not System.
5027     *
5028     * @return filtered list
5029     */
5030    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5031        if (userId == UserHandle.USER_SYSTEM) {
5032            return resolveInfos;
5033        }
5034        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5035            ResolveInfo info = resolveInfos.get(i);
5036            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5037                resolveInfos.remove(i);
5038            }
5039        }
5040        return resolveInfos;
5041    }
5042
5043    /**
5044     * @param resolveInfos list of resolve infos in descending priority order
5045     * @return if the list contains a resolve info with non-negative priority
5046     */
5047    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5048        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5049    }
5050
5051    private static boolean hasWebURI(Intent intent) {
5052        if (intent.getData() == null) {
5053            return false;
5054        }
5055        final String scheme = intent.getScheme();
5056        if (TextUtils.isEmpty(scheme)) {
5057            return false;
5058        }
5059        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5060    }
5061
5062    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5063            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5064            int userId) {
5065        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5066
5067        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5068            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5069                    candidates.size());
5070        }
5071
5072        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5073        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5074        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5075        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5076        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5077        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5078
5079        synchronized (mPackages) {
5080            final int count = candidates.size();
5081            // First, try to use linked apps. Partition the candidates into four lists:
5082            // one for the final results, one for the "do not use ever", one for "undefined status"
5083            // and finally one for "browser app type".
5084            for (int n=0; n<count; n++) {
5085                ResolveInfo info = candidates.get(n);
5086                String packageName = info.activityInfo.packageName;
5087                PackageSetting ps = mSettings.mPackages.get(packageName);
5088                if (ps != null) {
5089                    // Add to the special match all list (Browser use case)
5090                    if (info.handleAllWebDataURI) {
5091                        matchAllList.add(info);
5092                        continue;
5093                    }
5094                    // Try to get the status from User settings first
5095                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5096                    int status = (int)(packedStatus >> 32);
5097                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5098                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5099                        if (DEBUG_DOMAIN_VERIFICATION) {
5100                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5101                                    + " : linkgen=" + linkGeneration);
5102                        }
5103                        // Use link-enabled generation as preferredOrder, i.e.
5104                        // prefer newly-enabled over earlier-enabled.
5105                        info.preferredOrder = linkGeneration;
5106                        alwaysList.add(info);
5107                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5108                        if (DEBUG_DOMAIN_VERIFICATION) {
5109                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5110                        }
5111                        neverList.add(info);
5112                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5113                        if (DEBUG_DOMAIN_VERIFICATION) {
5114                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5115                        }
5116                        alwaysAskList.add(info);
5117                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5118                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5119                        if (DEBUG_DOMAIN_VERIFICATION) {
5120                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5121                        }
5122                        undefinedList.add(info);
5123                    }
5124                }
5125            }
5126
5127            // We'll want to include browser possibilities in a few cases
5128            boolean includeBrowser = false;
5129
5130            // First try to add the "always" resolution(s) for the current user, if any
5131            if (alwaysList.size() > 0) {
5132                result.addAll(alwaysList);
5133            } else {
5134                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5135                result.addAll(undefinedList);
5136                // Maybe add one for the other profile.
5137                if (xpDomainInfo != null && (
5138                        xpDomainInfo.bestDomainVerificationStatus
5139                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5140                    result.add(xpDomainInfo.resolveInfo);
5141                }
5142                includeBrowser = true;
5143            }
5144
5145            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5146            // If there were 'always' entries their preferred order has been set, so we also
5147            // back that off to make the alternatives equivalent
5148            if (alwaysAskList.size() > 0) {
5149                for (ResolveInfo i : result) {
5150                    i.preferredOrder = 0;
5151                }
5152                result.addAll(alwaysAskList);
5153                includeBrowser = true;
5154            }
5155
5156            if (includeBrowser) {
5157                // Also add browsers (all of them or only the default one)
5158                if (DEBUG_DOMAIN_VERIFICATION) {
5159                    Slog.v(TAG, "   ...including browsers in candidate set");
5160                }
5161                if ((matchFlags & MATCH_ALL) != 0) {
5162                    result.addAll(matchAllList);
5163                } else {
5164                    // Browser/generic handling case.  If there's a default browser, go straight
5165                    // to that (but only if there is no other higher-priority match).
5166                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5167                    int maxMatchPrio = 0;
5168                    ResolveInfo defaultBrowserMatch = null;
5169                    final int numCandidates = matchAllList.size();
5170                    for (int n = 0; n < numCandidates; n++) {
5171                        ResolveInfo info = matchAllList.get(n);
5172                        // track the highest overall match priority...
5173                        if (info.priority > maxMatchPrio) {
5174                            maxMatchPrio = info.priority;
5175                        }
5176                        // ...and the highest-priority default browser match
5177                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5178                            if (defaultBrowserMatch == null
5179                                    || (defaultBrowserMatch.priority < info.priority)) {
5180                                if (debug) {
5181                                    Slog.v(TAG, "Considering default browser match " + info);
5182                                }
5183                                defaultBrowserMatch = info;
5184                            }
5185                        }
5186                    }
5187                    if (defaultBrowserMatch != null
5188                            && defaultBrowserMatch.priority >= maxMatchPrio
5189                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5190                    {
5191                        if (debug) {
5192                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5193                        }
5194                        result.add(defaultBrowserMatch);
5195                    } else {
5196                        result.addAll(matchAllList);
5197                    }
5198                }
5199
5200                // If there is nothing selected, add all candidates and remove the ones that the user
5201                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5202                if (result.size() == 0) {
5203                    result.addAll(candidates);
5204                    result.removeAll(neverList);
5205                }
5206            }
5207        }
5208        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5209            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5210                    result.size());
5211            for (ResolveInfo info : result) {
5212                Slog.v(TAG, "  + " + info.activityInfo);
5213            }
5214        }
5215        return result;
5216    }
5217
5218    // Returns a packed value as a long:
5219    //
5220    // high 'int'-sized word: link status: undefined/ask/never/always.
5221    // low 'int'-sized word: relative priority among 'always' results.
5222    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5223        long result = ps.getDomainVerificationStatusForUser(userId);
5224        // if none available, get the master status
5225        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5226            if (ps.getIntentFilterVerificationInfo() != null) {
5227                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5228            }
5229        }
5230        return result;
5231    }
5232
5233    private ResolveInfo querySkipCurrentProfileIntents(
5234            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5235            int flags, int sourceUserId) {
5236        if (matchingFilters != null) {
5237            int size = matchingFilters.size();
5238            for (int i = 0; i < size; i ++) {
5239                CrossProfileIntentFilter filter = matchingFilters.get(i);
5240                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5241                    // Checking if there are activities in the target user that can handle the
5242                    // intent.
5243                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5244                            resolvedType, flags, sourceUserId);
5245                    if (resolveInfo != null) {
5246                        return resolveInfo;
5247                    }
5248                }
5249            }
5250        }
5251        return null;
5252    }
5253
5254    // Return matching ResolveInfo in target user if any.
5255    private ResolveInfo queryCrossProfileIntents(
5256            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5257            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5258        if (matchingFilters != null) {
5259            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5260            // match the same intent. For performance reasons, it is better not to
5261            // run queryIntent twice for the same userId
5262            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5263            int size = matchingFilters.size();
5264            for (int i = 0; i < size; i++) {
5265                CrossProfileIntentFilter filter = matchingFilters.get(i);
5266                int targetUserId = filter.getTargetUserId();
5267                boolean skipCurrentProfile =
5268                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5269                boolean skipCurrentProfileIfNoMatchFound =
5270                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5271                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5272                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
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) return resolveInfo;
5278                    alreadyTriedUserIds.put(targetUserId, true);
5279                }
5280            }
5281        }
5282        return null;
5283    }
5284
5285    /**
5286     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5287     * will forward the intent to the filter's target user.
5288     * Otherwise, returns null.
5289     */
5290    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5291            String resolvedType, int flags, int sourceUserId) {
5292        int targetUserId = filter.getTargetUserId();
5293        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5294                resolvedType, flags, targetUserId);
5295        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5296                && isUserEnabled(targetUserId)) {
5297            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5298        }
5299        return null;
5300    }
5301
5302    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5303            int sourceUserId, int targetUserId) {
5304        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5305        long ident = Binder.clearCallingIdentity();
5306        boolean targetIsProfile;
5307        try {
5308            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5309        } finally {
5310            Binder.restoreCallingIdentity(ident);
5311        }
5312        String className;
5313        if (targetIsProfile) {
5314            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5315        } else {
5316            className = FORWARD_INTENT_TO_PARENT;
5317        }
5318        ComponentName forwardingActivityComponentName = new ComponentName(
5319                mAndroidApplication.packageName, className);
5320        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5321                sourceUserId);
5322        if (!targetIsProfile) {
5323            forwardingActivityInfo.showUserIcon = targetUserId;
5324            forwardingResolveInfo.noResourceId = true;
5325        }
5326        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5327        forwardingResolveInfo.priority = 0;
5328        forwardingResolveInfo.preferredOrder = 0;
5329        forwardingResolveInfo.match = 0;
5330        forwardingResolveInfo.isDefault = true;
5331        forwardingResolveInfo.filter = filter;
5332        forwardingResolveInfo.targetUserId = targetUserId;
5333        return forwardingResolveInfo;
5334    }
5335
5336    @Override
5337    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5338            Intent[] specifics, String[] specificTypes, Intent intent,
5339            String resolvedType, int flags, int userId) {
5340        if (!sUserManager.exists(userId)) return Collections.emptyList();
5341        flags = augmentFlagsForUser(flags, userId);
5342        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5343                false, "query intent activity options");
5344        final String resultsAction = intent.getAction();
5345
5346        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5347                | PackageManager.GET_RESOLVED_FILTER, userId);
5348
5349        if (DEBUG_INTENT_MATCHING) {
5350            Log.v(TAG, "Query " + intent + ": " + results);
5351        }
5352
5353        int specificsPos = 0;
5354        int N;
5355
5356        // todo: note that the algorithm used here is O(N^2).  This
5357        // isn't a problem in our current environment, but if we start running
5358        // into situations where we have more than 5 or 10 matches then this
5359        // should probably be changed to something smarter...
5360
5361        // First we go through and resolve each of the specific items
5362        // that were supplied, taking care of removing any corresponding
5363        // duplicate items in the generic resolve list.
5364        if (specifics != null) {
5365            for (int i=0; i<specifics.length; i++) {
5366                final Intent sintent = specifics[i];
5367                if (sintent == null) {
5368                    continue;
5369                }
5370
5371                if (DEBUG_INTENT_MATCHING) {
5372                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5373                }
5374
5375                String action = sintent.getAction();
5376                if (resultsAction != null && resultsAction.equals(action)) {
5377                    // If this action was explicitly requested, then don't
5378                    // remove things that have it.
5379                    action = null;
5380                }
5381
5382                ResolveInfo ri = null;
5383                ActivityInfo ai = null;
5384
5385                ComponentName comp = sintent.getComponent();
5386                if (comp == null) {
5387                    ri = resolveIntent(
5388                        sintent,
5389                        specificTypes != null ? specificTypes[i] : null,
5390                            flags, userId);
5391                    if (ri == null) {
5392                        continue;
5393                    }
5394                    if (ri == mResolveInfo) {
5395                        // ACK!  Must do something better with this.
5396                    }
5397                    ai = ri.activityInfo;
5398                    comp = new ComponentName(ai.applicationInfo.packageName,
5399                            ai.name);
5400                } else {
5401                    ai = getActivityInfo(comp, flags, userId);
5402                    if (ai == null) {
5403                        continue;
5404                    }
5405                }
5406
5407                // Look for any generic query activities that are duplicates
5408                // of this specific one, and remove them from the results.
5409                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5410                N = results.size();
5411                int j;
5412                for (j=specificsPos; j<N; j++) {
5413                    ResolveInfo sri = results.get(j);
5414                    if ((sri.activityInfo.name.equals(comp.getClassName())
5415                            && sri.activityInfo.applicationInfo.packageName.equals(
5416                                    comp.getPackageName()))
5417                        || (action != null && sri.filter.matchAction(action))) {
5418                        results.remove(j);
5419                        if (DEBUG_INTENT_MATCHING) Log.v(
5420                            TAG, "Removing duplicate item from " + j
5421                            + " due to specific " + specificsPos);
5422                        if (ri == null) {
5423                            ri = sri;
5424                        }
5425                        j--;
5426                        N--;
5427                    }
5428                }
5429
5430                // Add this specific item to its proper place.
5431                if (ri == null) {
5432                    ri = new ResolveInfo();
5433                    ri.activityInfo = ai;
5434                }
5435                results.add(specificsPos, ri);
5436                ri.specificIndex = i;
5437                specificsPos++;
5438            }
5439        }
5440
5441        // Now we go through the remaining generic results and remove any
5442        // duplicate actions that are found here.
5443        N = results.size();
5444        for (int i=specificsPos; i<N-1; i++) {
5445            final ResolveInfo rii = results.get(i);
5446            if (rii.filter == null) {
5447                continue;
5448            }
5449
5450            // Iterate over all of the actions of this result's intent
5451            // filter...  typically this should be just one.
5452            final Iterator<String> it = rii.filter.actionsIterator();
5453            if (it == null) {
5454                continue;
5455            }
5456            while (it.hasNext()) {
5457                final String action = it.next();
5458                if (resultsAction != null && resultsAction.equals(action)) {
5459                    // If this action was explicitly requested, then don't
5460                    // remove things that have it.
5461                    continue;
5462                }
5463                for (int j=i+1; j<N; j++) {
5464                    final ResolveInfo rij = results.get(j);
5465                    if (rij.filter != null && rij.filter.hasAction(action)) {
5466                        results.remove(j);
5467                        if (DEBUG_INTENT_MATCHING) Log.v(
5468                            TAG, "Removing duplicate item from " + j
5469                            + " due to action " + action + " at " + i);
5470                        j--;
5471                        N--;
5472                    }
5473                }
5474            }
5475
5476            // If the caller didn't request filter information, drop it now
5477            // so we don't have to marshall/unmarshall it.
5478            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5479                rii.filter = null;
5480            }
5481        }
5482
5483        // Filter out the caller activity if so requested.
5484        if (caller != null) {
5485            N = results.size();
5486            for (int i=0; i<N; i++) {
5487                ActivityInfo ainfo = results.get(i).activityInfo;
5488                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5489                        && caller.getClassName().equals(ainfo.name)) {
5490                    results.remove(i);
5491                    break;
5492                }
5493            }
5494        }
5495
5496        // If the caller didn't request filter information,
5497        // drop them now so we don't have to
5498        // marshall/unmarshall it.
5499        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5500            N = results.size();
5501            for (int i=0; i<N; i++) {
5502                results.get(i).filter = null;
5503            }
5504        }
5505
5506        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5507        return results;
5508    }
5509
5510    @Override
5511    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5512            int userId) {
5513        if (!sUserManager.exists(userId)) return Collections.emptyList();
5514        flags = augmentFlagsForUser(flags, userId);
5515        ComponentName comp = intent.getComponent();
5516        if (comp == null) {
5517            if (intent.getSelector() != null) {
5518                intent = intent.getSelector();
5519                comp = intent.getComponent();
5520            }
5521        }
5522        if (comp != null) {
5523            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5524            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5525            if (ai != null) {
5526                ResolveInfo ri = new ResolveInfo();
5527                ri.activityInfo = ai;
5528                list.add(ri);
5529            }
5530            return list;
5531        }
5532
5533        // reader
5534        synchronized (mPackages) {
5535            String pkgName = intent.getPackage();
5536            if (pkgName == null) {
5537                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5538            }
5539            final PackageParser.Package pkg = mPackages.get(pkgName);
5540            if (pkg != null) {
5541                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5542                        userId);
5543            }
5544            return null;
5545        }
5546    }
5547
5548    @Override
5549    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5550        if (!sUserManager.exists(userId)) return null;
5551        flags = augmentFlagsForUser(flags, userId);
5552        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5553        if (query != null) {
5554            if (query.size() >= 1) {
5555                // If there is more than one service with the same priority,
5556                // just arbitrarily pick the first one.
5557                return query.get(0);
5558            }
5559        }
5560        return null;
5561    }
5562
5563    @Override
5564    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5565            int userId) {
5566        if (!sUserManager.exists(userId)) return Collections.emptyList();
5567        flags = augmentFlagsForUser(flags, userId);
5568        ComponentName comp = intent.getComponent();
5569        if (comp == null) {
5570            if (intent.getSelector() != null) {
5571                intent = intent.getSelector();
5572                comp = intent.getComponent();
5573            }
5574        }
5575        if (comp != null) {
5576            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5577            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5578            if (si != null) {
5579                final ResolveInfo ri = new ResolveInfo();
5580                ri.serviceInfo = si;
5581                list.add(ri);
5582            }
5583            return list;
5584        }
5585
5586        // reader
5587        synchronized (mPackages) {
5588            String pkgName = intent.getPackage();
5589            if (pkgName == null) {
5590                return mServices.queryIntent(intent, resolvedType, flags, userId);
5591            }
5592            final PackageParser.Package pkg = mPackages.get(pkgName);
5593            if (pkg != null) {
5594                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5595                        userId);
5596            }
5597            return null;
5598        }
5599    }
5600
5601    @Override
5602    public List<ResolveInfo> queryIntentContentProviders(
5603            Intent intent, String resolvedType, int flags, int userId) {
5604        if (!sUserManager.exists(userId)) return Collections.emptyList();
5605        flags = augmentFlagsForUser(flags, userId);
5606        ComponentName comp = intent.getComponent();
5607        if (comp == null) {
5608            if (intent.getSelector() != null) {
5609                intent = intent.getSelector();
5610                comp = intent.getComponent();
5611            }
5612        }
5613        if (comp != null) {
5614            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5615            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5616            if (pi != null) {
5617                final ResolveInfo ri = new ResolveInfo();
5618                ri.providerInfo = pi;
5619                list.add(ri);
5620            }
5621            return list;
5622        }
5623
5624        // reader
5625        synchronized (mPackages) {
5626            String pkgName = intent.getPackage();
5627            if (pkgName == null) {
5628                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5629            }
5630            final PackageParser.Package pkg = mPackages.get(pkgName);
5631            if (pkg != null) {
5632                return mProviders.queryIntentForPackage(
5633                        intent, resolvedType, flags, pkg.providers, userId);
5634            }
5635            return null;
5636        }
5637    }
5638
5639    @Override
5640    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5641        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5642
5643        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5644
5645        // writer
5646        synchronized (mPackages) {
5647            ArrayList<PackageInfo> list;
5648            if (listUninstalled) {
5649                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5650                for (PackageSetting ps : mSettings.mPackages.values()) {
5651                    PackageInfo pi;
5652                    if (ps.pkg != null) {
5653                        pi = generatePackageInfo(ps.pkg, flags, userId);
5654                    } else {
5655                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5656                    }
5657                    if (pi != null) {
5658                        list.add(pi);
5659                    }
5660                }
5661            } else {
5662                list = new ArrayList<PackageInfo>(mPackages.size());
5663                for (PackageParser.Package p : mPackages.values()) {
5664                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5665                    if (pi != null) {
5666                        list.add(pi);
5667                    }
5668                }
5669            }
5670
5671            return new ParceledListSlice<PackageInfo>(list);
5672        }
5673    }
5674
5675    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5676            String[] permissions, boolean[] tmp, int flags, int userId) {
5677        int numMatch = 0;
5678        final PermissionsState permissionsState = ps.getPermissionsState();
5679        for (int i=0; i<permissions.length; i++) {
5680            final String permission = permissions[i];
5681            if (permissionsState.hasPermission(permission, userId)) {
5682                tmp[i] = true;
5683                numMatch++;
5684            } else {
5685                tmp[i] = false;
5686            }
5687        }
5688        if (numMatch == 0) {
5689            return;
5690        }
5691        PackageInfo pi;
5692        if (ps.pkg != null) {
5693            pi = generatePackageInfo(ps.pkg, flags, userId);
5694        } else {
5695            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5696        }
5697        // The above might return null in cases of uninstalled apps or install-state
5698        // skew across users/profiles.
5699        if (pi != null) {
5700            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5701                if (numMatch == permissions.length) {
5702                    pi.requestedPermissions = permissions;
5703                } else {
5704                    pi.requestedPermissions = new String[numMatch];
5705                    numMatch = 0;
5706                    for (int i=0; i<permissions.length; i++) {
5707                        if (tmp[i]) {
5708                            pi.requestedPermissions[numMatch] = permissions[i];
5709                            numMatch++;
5710                        }
5711                    }
5712                }
5713            }
5714            list.add(pi);
5715        }
5716    }
5717
5718    @Override
5719    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5720            String[] permissions, int flags, int userId) {
5721        if (!sUserManager.exists(userId)) return null;
5722        flags = augmentFlagsForUser(flags, userId);
5723        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5724
5725        // writer
5726        synchronized (mPackages) {
5727            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5728            boolean[] tmpBools = new boolean[permissions.length];
5729            if (listUninstalled) {
5730                for (PackageSetting ps : mSettings.mPackages.values()) {
5731                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5732                }
5733            } else {
5734                for (PackageParser.Package pkg : mPackages.values()) {
5735                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5736                    if (ps != null) {
5737                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5738                                userId);
5739                    }
5740                }
5741            }
5742
5743            return new ParceledListSlice<PackageInfo>(list);
5744        }
5745    }
5746
5747    @Override
5748    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5749        if (!sUserManager.exists(userId)) return null;
5750        flags = augmentFlagsForUser(flags, userId);
5751        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5752
5753        // writer
5754        synchronized (mPackages) {
5755            ArrayList<ApplicationInfo> list;
5756            if (listUninstalled) {
5757                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5758                for (PackageSetting ps : mSettings.mPackages.values()) {
5759                    ApplicationInfo ai;
5760                    if (ps.pkg != null) {
5761                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5762                                ps.readUserState(userId), userId);
5763                    } else {
5764                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5765                    }
5766                    if (ai != null) {
5767                        list.add(ai);
5768                    }
5769                }
5770            } else {
5771                list = new ArrayList<ApplicationInfo>(mPackages.size());
5772                for (PackageParser.Package p : mPackages.values()) {
5773                    if (p.mExtras != null) {
5774                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5775                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5776                        if (ai != null) {
5777                            list.add(ai);
5778                        }
5779                    }
5780                }
5781            }
5782
5783            return new ParceledListSlice<ApplicationInfo>(list);
5784        }
5785    }
5786
5787    public List<ApplicationInfo> getPersistentApplications(int flags) {
5788        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5789
5790        // reader
5791        synchronized (mPackages) {
5792            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5793            final int userId = UserHandle.getCallingUserId();
5794            while (i.hasNext()) {
5795                final PackageParser.Package p = i.next();
5796                if (p.applicationInfo != null
5797                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5798                        && (!mSafeMode || isSystemApp(p))) {
5799                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5800                    if (ps != null) {
5801                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5802                                ps.readUserState(userId), userId);
5803                        if (ai != null) {
5804                            finalList.add(ai);
5805                        }
5806                    }
5807                }
5808            }
5809        }
5810
5811        return finalList;
5812    }
5813
5814    @Override
5815    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5816        if (!sUserManager.exists(userId)) return null;
5817        flags = augmentFlagsForUser(flags, userId);
5818        // reader
5819        synchronized (mPackages) {
5820            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5821            PackageSetting ps = provider != null
5822                    ? mSettings.mPackages.get(provider.owner.packageName)
5823                    : null;
5824            return ps != null
5825                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5826                    && (!mSafeMode || (provider.info.applicationInfo.flags
5827                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5828                    ? PackageParser.generateProviderInfo(provider, flags,
5829                            ps.readUserState(userId), userId)
5830                    : null;
5831        }
5832    }
5833
5834    /**
5835     * @deprecated
5836     */
5837    @Deprecated
5838    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5839        // reader
5840        synchronized (mPackages) {
5841            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5842                    .entrySet().iterator();
5843            final int userId = UserHandle.getCallingUserId();
5844            while (i.hasNext()) {
5845                Map.Entry<String, PackageParser.Provider> entry = i.next();
5846                PackageParser.Provider p = entry.getValue();
5847                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5848
5849                if (ps != null && p.syncable
5850                        && (!mSafeMode || (p.info.applicationInfo.flags
5851                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5852                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5853                            ps.readUserState(userId), userId);
5854                    if (info != null) {
5855                        outNames.add(entry.getKey());
5856                        outInfo.add(info);
5857                    }
5858                }
5859            }
5860        }
5861    }
5862
5863    @Override
5864    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5865            int uid, int flags) {
5866        final int userId = processName != null ? UserHandle.getUserId(uid)
5867                : UserHandle.getCallingUserId();
5868        if (!sUserManager.exists(userId)) return null;
5869        flags = augmentFlagsForUser(flags, userId);
5870
5871        ArrayList<ProviderInfo> finalList = null;
5872        // reader
5873        synchronized (mPackages) {
5874            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5875            while (i.hasNext()) {
5876                final PackageParser.Provider p = i.next();
5877                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5878                if (ps != null && p.info.authority != null
5879                        && (processName == null
5880                                || (p.info.processName.equals(processName)
5881                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5882                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5883                        && (!mSafeMode
5884                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5885                    if (finalList == null) {
5886                        finalList = new ArrayList<ProviderInfo>(3);
5887                    }
5888                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5889                            ps.readUserState(userId), userId);
5890                    if (info != null) {
5891                        finalList.add(info);
5892                    }
5893                }
5894            }
5895        }
5896
5897        if (finalList != null) {
5898            Collections.sort(finalList, mProviderInitOrderSorter);
5899            return new ParceledListSlice<ProviderInfo>(finalList);
5900        }
5901
5902        return null;
5903    }
5904
5905    @Override
5906    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5907            int flags) {
5908        // reader
5909        synchronized (mPackages) {
5910            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5911            return PackageParser.generateInstrumentationInfo(i, flags);
5912        }
5913    }
5914
5915    @Override
5916    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5917            int flags) {
5918        ArrayList<InstrumentationInfo> finalList =
5919            new ArrayList<InstrumentationInfo>();
5920
5921        // reader
5922        synchronized (mPackages) {
5923            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5924            while (i.hasNext()) {
5925                final PackageParser.Instrumentation p = i.next();
5926                if (targetPackage == null
5927                        || targetPackage.equals(p.info.targetPackage)) {
5928                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5929                            flags);
5930                    if (ii != null) {
5931                        finalList.add(ii);
5932                    }
5933                }
5934            }
5935        }
5936
5937        return finalList;
5938    }
5939
5940    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5941        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5942        if (overlays == null) {
5943            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5944            return;
5945        }
5946        for (PackageParser.Package opkg : overlays.values()) {
5947            // Not much to do if idmap fails: we already logged the error
5948            // and we certainly don't want to abort installation of pkg simply
5949            // because an overlay didn't fit properly. For these reasons,
5950            // ignore the return value of createIdmapForPackagePairLI.
5951            createIdmapForPackagePairLI(pkg, opkg);
5952        }
5953    }
5954
5955    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5956            PackageParser.Package opkg) {
5957        if (!opkg.mTrustedOverlay) {
5958            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5959                    opkg.baseCodePath + ": overlay not trusted");
5960            return false;
5961        }
5962        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5963        if (overlaySet == null) {
5964            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5965                    opkg.baseCodePath + " but target package has no known overlays");
5966            return false;
5967        }
5968        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5969        // TODO: generate idmap for split APKs
5970        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5971            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5972                    + opkg.baseCodePath);
5973            return false;
5974        }
5975        PackageParser.Package[] overlayArray =
5976            overlaySet.values().toArray(new PackageParser.Package[0]);
5977        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5978            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5979                return p1.mOverlayPriority - p2.mOverlayPriority;
5980            }
5981        };
5982        Arrays.sort(overlayArray, cmp);
5983
5984        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5985        int i = 0;
5986        for (PackageParser.Package p : overlayArray) {
5987            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5988        }
5989        return true;
5990    }
5991
5992    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5993        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5994        try {
5995            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5996        } finally {
5997            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5998        }
5999    }
6000
6001    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6002        final File[] files = dir.listFiles();
6003        if (ArrayUtils.isEmpty(files)) {
6004            Log.d(TAG, "No files in app dir " + dir);
6005            return;
6006        }
6007
6008        if (DEBUG_PACKAGE_SCANNING) {
6009            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6010                    + " flags=0x" + Integer.toHexString(parseFlags));
6011        }
6012
6013        for (File file : files) {
6014            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6015                    && !PackageInstallerService.isStageName(file.getName());
6016            if (!isPackage) {
6017                // Ignore entries which are not packages
6018                continue;
6019            }
6020            try {
6021                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6022                        scanFlags, currentTime, null);
6023            } catch (PackageManagerException e) {
6024                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6025
6026                // Delete invalid userdata apps
6027                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6028                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6029                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6030                    if (file.isDirectory()) {
6031                        mInstaller.rmPackageDir(file.getAbsolutePath());
6032                    } else {
6033                        file.delete();
6034                    }
6035                }
6036            }
6037        }
6038    }
6039
6040    private static File getSettingsProblemFile() {
6041        File dataDir = Environment.getDataDirectory();
6042        File systemDir = new File(dataDir, "system");
6043        File fname = new File(systemDir, "uiderrors.txt");
6044        return fname;
6045    }
6046
6047    static void reportSettingsProblem(int priority, String msg) {
6048        logCriticalInfo(priority, msg);
6049    }
6050
6051    static void logCriticalInfo(int priority, String msg) {
6052        Slog.println(priority, TAG, msg);
6053        EventLogTags.writePmCriticalInfo(msg);
6054        try {
6055            File fname = getSettingsProblemFile();
6056            FileOutputStream out = new FileOutputStream(fname, true);
6057            PrintWriter pw = new FastPrintWriter(out);
6058            SimpleDateFormat formatter = new SimpleDateFormat();
6059            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6060            pw.println(dateString + ": " + msg);
6061            pw.close();
6062            FileUtils.setPermissions(
6063                    fname.toString(),
6064                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6065                    -1, -1);
6066        } catch (java.io.IOException e) {
6067        }
6068    }
6069
6070    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6071            PackageParser.Package pkg, File srcFile, int parseFlags)
6072            throws PackageManagerException {
6073        if (ps != null
6074                && ps.codePath.equals(srcFile)
6075                && ps.timeStamp == srcFile.lastModified()
6076                && !isCompatSignatureUpdateNeeded(pkg)
6077                && !isRecoverSignatureUpdateNeeded(pkg)) {
6078            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6079            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6080            ArraySet<PublicKey> signingKs;
6081            synchronized (mPackages) {
6082                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6083            }
6084            if (ps.signatures.mSignatures != null
6085                    && ps.signatures.mSignatures.length != 0
6086                    && signingKs != null) {
6087                // Optimization: reuse the existing cached certificates
6088                // if the package appears to be unchanged.
6089                pkg.mSignatures = ps.signatures.mSignatures;
6090                pkg.mSigningKeys = signingKs;
6091                return;
6092            }
6093
6094            Slog.w(TAG, "PackageSetting for " + ps.name
6095                    + " is missing signatures.  Collecting certs again to recover them.");
6096        } else {
6097            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6098        }
6099
6100        try {
6101            pp.collectCertificates(pkg, parseFlags);
6102            pp.collectManifestDigest(pkg);
6103        } catch (PackageParserException e) {
6104            throw PackageManagerException.from(e);
6105        }
6106    }
6107
6108    /**
6109     *  Traces a package scan.
6110     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6111     */
6112    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6113            long currentTime, UserHandle user) throws PackageManagerException {
6114        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6115        try {
6116            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6117        } finally {
6118            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6119        }
6120    }
6121
6122    /**
6123     *  Scans a package and returns the newly parsed package.
6124     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6125     */
6126    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6127            long currentTime, UserHandle user) throws PackageManagerException {
6128        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6129        parseFlags |= mDefParseFlags;
6130        PackageParser pp = new PackageParser();
6131        pp.setSeparateProcesses(mSeparateProcesses);
6132        pp.setOnlyCoreApps(mOnlyCore);
6133        pp.setDisplayMetrics(mMetrics);
6134
6135        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6136            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6137        }
6138
6139        final PackageParser.Package pkg;
6140        try {
6141            pkg = pp.parsePackage(scanFile, parseFlags);
6142        } catch (PackageParserException e) {
6143            throw PackageManagerException.from(e);
6144        }
6145
6146        PackageSetting ps = null;
6147        PackageSetting updatedPkg;
6148        // reader
6149        synchronized (mPackages) {
6150            // Look to see if we already know about this package.
6151            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6152            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6153                // This package has been renamed to its original name.  Let's
6154                // use that.
6155                ps = mSettings.peekPackageLPr(oldName);
6156            }
6157            // If there was no original package, see one for the real package name.
6158            if (ps == null) {
6159                ps = mSettings.peekPackageLPr(pkg.packageName);
6160            }
6161            // Check to see if this package could be hiding/updating a system
6162            // package.  Must look for it either under the original or real
6163            // package name depending on our state.
6164            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6165            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6166        }
6167        boolean updatedPkgBetter = false;
6168        // First check if this is a system package that may involve an update
6169        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6170            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6171            // it needs to drop FLAG_PRIVILEGED.
6172            if (locationIsPrivileged(scanFile)) {
6173                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6174            } else {
6175                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6176            }
6177
6178            if (ps != null && !ps.codePath.equals(scanFile)) {
6179                // The path has changed from what was last scanned...  check the
6180                // version of the new path against what we have stored to determine
6181                // what to do.
6182                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6183                if (pkg.mVersionCode <= ps.versionCode) {
6184                    // The system package has been updated and the code path does not match
6185                    // Ignore entry. Skip it.
6186                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6187                            + " ignored: updated version " + ps.versionCode
6188                            + " better than this " + pkg.mVersionCode);
6189                    if (!updatedPkg.codePath.equals(scanFile)) {
6190                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6191                                + ps.name + " changing from " + updatedPkg.codePathString
6192                                + " to " + scanFile);
6193                        updatedPkg.codePath = scanFile;
6194                        updatedPkg.codePathString = scanFile.toString();
6195                        updatedPkg.resourcePath = scanFile;
6196                        updatedPkg.resourcePathString = scanFile.toString();
6197                    }
6198                    updatedPkg.pkg = pkg;
6199                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6200                            "Package " + ps.name + " at " + scanFile
6201                                    + " ignored: updated version " + ps.versionCode
6202                                    + " better than this " + pkg.mVersionCode);
6203                } else {
6204                    // The current app on the system partition is better than
6205                    // what we have updated to on the data partition; switch
6206                    // back to the system partition version.
6207                    // At this point, its safely assumed that package installation for
6208                    // apps in system partition will go through. If not there won't be a working
6209                    // version of the app
6210                    // writer
6211                    synchronized (mPackages) {
6212                        // Just remove the loaded entries from package lists.
6213                        mPackages.remove(ps.name);
6214                    }
6215
6216                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6217                            + " reverting from " + ps.codePathString
6218                            + ": new version " + pkg.mVersionCode
6219                            + " better than installed " + ps.versionCode);
6220
6221                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6222                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6223                    synchronized (mInstallLock) {
6224                        args.cleanUpResourcesLI();
6225                    }
6226                    synchronized (mPackages) {
6227                        mSettings.enableSystemPackageLPw(ps.name);
6228                    }
6229                    updatedPkgBetter = true;
6230                }
6231            }
6232        }
6233
6234        if (updatedPkg != null) {
6235            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6236            // initially
6237            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6238
6239            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6240            // flag set initially
6241            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6242                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6243            }
6244        }
6245
6246        // Verify certificates against what was last scanned
6247        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6248
6249        /*
6250         * A new system app appeared, but we already had a non-system one of the
6251         * same name installed earlier.
6252         */
6253        boolean shouldHideSystemApp = false;
6254        if (updatedPkg == null && ps != null
6255                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6256            /*
6257             * Check to make sure the signatures match first. If they don't,
6258             * wipe the installed application and its data.
6259             */
6260            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6261                    != PackageManager.SIGNATURE_MATCH) {
6262                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6263                        + " signatures don't match existing userdata copy; removing");
6264                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6265                ps = null;
6266            } else {
6267                /*
6268                 * If the newly-added system app is an older version than the
6269                 * already installed version, hide it. It will be scanned later
6270                 * and re-added like an update.
6271                 */
6272                if (pkg.mVersionCode <= ps.versionCode) {
6273                    shouldHideSystemApp = true;
6274                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6275                            + " but new version " + pkg.mVersionCode + " better than installed "
6276                            + ps.versionCode + "; hiding system");
6277                } else {
6278                    /*
6279                     * The newly found system app is a newer version that the
6280                     * one previously installed. Simply remove the
6281                     * already-installed application and replace it with our own
6282                     * while keeping the application data.
6283                     */
6284                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6285                            + " reverting from " + ps.codePathString + ": new version "
6286                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6287                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6288                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6289                    synchronized (mInstallLock) {
6290                        args.cleanUpResourcesLI();
6291                    }
6292                }
6293            }
6294        }
6295
6296        // The apk is forward locked (not public) if its code and resources
6297        // are kept in different files. (except for app in either system or
6298        // vendor path).
6299        // TODO grab this value from PackageSettings
6300        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6301            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6302                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6303            }
6304        }
6305
6306        // TODO: extend to support forward-locked splits
6307        String resourcePath = null;
6308        String baseResourcePath = null;
6309        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6310            if (ps != null && ps.resourcePathString != null) {
6311                resourcePath = ps.resourcePathString;
6312                baseResourcePath = ps.resourcePathString;
6313            } else {
6314                // Should not happen at all. Just log an error.
6315                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6316            }
6317        } else {
6318            resourcePath = pkg.codePath;
6319            baseResourcePath = pkg.baseCodePath;
6320        }
6321
6322        // Set application objects path explicitly.
6323        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6324        pkg.applicationInfo.setCodePath(pkg.codePath);
6325        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6326        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6327        pkg.applicationInfo.setResourcePath(resourcePath);
6328        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6329        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6330
6331        // Note that we invoke the following method only if we are about to unpack an application
6332        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6333                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6334
6335        /*
6336         * If the system app should be overridden by a previously installed
6337         * data, hide the system app now and let the /data/app scan pick it up
6338         * again.
6339         */
6340        if (shouldHideSystemApp) {
6341            synchronized (mPackages) {
6342                mSettings.disableSystemPackageLPw(pkg.packageName);
6343            }
6344        }
6345
6346        return scannedPkg;
6347    }
6348
6349    private static String fixProcessName(String defProcessName,
6350            String processName, int uid) {
6351        if (processName == null) {
6352            return defProcessName;
6353        }
6354        return processName;
6355    }
6356
6357    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6358            throws PackageManagerException {
6359        if (pkgSetting.signatures.mSignatures != null) {
6360            // Already existing package. Make sure signatures match
6361            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6362                    == PackageManager.SIGNATURE_MATCH;
6363            if (!match) {
6364                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6365                        == PackageManager.SIGNATURE_MATCH;
6366            }
6367            if (!match) {
6368                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6369                        == PackageManager.SIGNATURE_MATCH;
6370            }
6371            if (!match) {
6372                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6373                        + pkg.packageName + " signatures do not match the "
6374                        + "previously installed version; ignoring!");
6375            }
6376        }
6377
6378        // Check for shared user signatures
6379        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6380            // Already existing package. Make sure signatures match
6381            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6382                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6383            if (!match) {
6384                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6385                        == PackageManager.SIGNATURE_MATCH;
6386            }
6387            if (!match) {
6388                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6389                        == PackageManager.SIGNATURE_MATCH;
6390            }
6391            if (!match) {
6392                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6393                        "Package " + pkg.packageName
6394                        + " has no signatures that match those in shared user "
6395                        + pkgSetting.sharedUser.name + "; ignoring!");
6396            }
6397        }
6398    }
6399
6400    /**
6401     * Enforces that only the system UID or root's UID can call a method exposed
6402     * via Binder.
6403     *
6404     * @param message used as message if SecurityException is thrown
6405     * @throws SecurityException if the caller is not system or root
6406     */
6407    private static final void enforceSystemOrRoot(String message) {
6408        final int uid = Binder.getCallingUid();
6409        if (uid != Process.SYSTEM_UID && uid != 0) {
6410            throw new SecurityException(message);
6411        }
6412    }
6413
6414    @Override
6415    public void performFstrimIfNeeded() {
6416        enforceSystemOrRoot("Only the system can request fstrim");
6417
6418        // Before everything else, see whether we need to fstrim.
6419        try {
6420            IMountService ms = PackageHelper.getMountService();
6421            if (ms != null) {
6422                final boolean isUpgrade = isUpgrade();
6423                boolean doTrim = isUpgrade;
6424                if (doTrim) {
6425                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6426                } else {
6427                    final long interval = android.provider.Settings.Global.getLong(
6428                            mContext.getContentResolver(),
6429                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6430                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6431                    if (interval > 0) {
6432                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6433                        if (timeSinceLast > interval) {
6434                            doTrim = true;
6435                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6436                                    + "; running immediately");
6437                        }
6438                    }
6439                }
6440                if (doTrim) {
6441                    if (!isFirstBoot()) {
6442                        try {
6443                            ActivityManagerNative.getDefault().showBootMessage(
6444                                    mContext.getResources().getString(
6445                                            R.string.android_upgrading_fstrim), true);
6446                        } catch (RemoteException e) {
6447                        }
6448                    }
6449                    ms.runMaintenance();
6450                }
6451            } else {
6452                Slog.e(TAG, "Mount service unavailable!");
6453            }
6454        } catch (RemoteException e) {
6455            // Can't happen; MountService is local
6456        }
6457    }
6458
6459    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6460        List<ResolveInfo> ris = null;
6461        try {
6462            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6463                    intent, null, 0, userId);
6464        } catch (RemoteException e) {
6465        }
6466        ArraySet<String> pkgNames = new ArraySet<String>();
6467        if (ris != null) {
6468            for (ResolveInfo ri : ris) {
6469                pkgNames.add(ri.activityInfo.packageName);
6470            }
6471        }
6472        return pkgNames;
6473    }
6474
6475    @Override
6476    public void notifyPackageUse(String packageName) {
6477        synchronized (mPackages) {
6478            PackageParser.Package p = mPackages.get(packageName);
6479            if (p == null) {
6480                return;
6481            }
6482            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6483        }
6484    }
6485
6486    @Override
6487    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6488        return performDexOptTraced(packageName, instructionSet);
6489    }
6490
6491    public boolean performDexOpt(String packageName, String instructionSet) {
6492        return performDexOptTraced(packageName, instructionSet);
6493    }
6494
6495    private boolean performDexOptTraced(String packageName, String instructionSet) {
6496        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6497        try {
6498            return performDexOptInternal(packageName, instructionSet);
6499        } finally {
6500            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6501        }
6502    }
6503
6504    private boolean performDexOptInternal(String packageName, String instructionSet) {
6505        PackageParser.Package p;
6506        final String targetInstructionSet;
6507        synchronized (mPackages) {
6508            p = mPackages.get(packageName);
6509            if (p == null) {
6510                return false;
6511            }
6512            mPackageUsage.write(false);
6513
6514            targetInstructionSet = instructionSet != null ? instructionSet :
6515                    getPrimaryInstructionSet(p.applicationInfo);
6516            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6517                return false;
6518            }
6519        }
6520        long callingId = Binder.clearCallingIdentity();
6521        try {
6522            synchronized (mInstallLock) {
6523                final String[] instructionSets = new String[] { targetInstructionSet };
6524                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6525                        true /* inclDependencies */);
6526                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6527            }
6528        } finally {
6529            Binder.restoreCallingIdentity(callingId);
6530        }
6531    }
6532
6533    public ArraySet<String> getPackagesThatNeedDexOpt() {
6534        ArraySet<String> pkgs = null;
6535        synchronized (mPackages) {
6536            for (PackageParser.Package p : mPackages.values()) {
6537                if (DEBUG_DEXOPT) {
6538                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6539                }
6540                if (!p.mDexOptPerformed.isEmpty()) {
6541                    continue;
6542                }
6543                if (pkgs == null) {
6544                    pkgs = new ArraySet<String>();
6545                }
6546                pkgs.add(p.packageName);
6547            }
6548        }
6549        return pkgs;
6550    }
6551
6552    public void shutdown() {
6553        mPackageUsage.write(true);
6554    }
6555
6556    @Override
6557    public void forceDexOpt(String packageName) {
6558        enforceSystemOrRoot("forceDexOpt");
6559
6560        PackageParser.Package pkg;
6561        synchronized (mPackages) {
6562            pkg = mPackages.get(packageName);
6563            if (pkg == null) {
6564                throw new IllegalArgumentException("Missing package: " + packageName);
6565            }
6566        }
6567
6568        synchronized (mInstallLock) {
6569            final String[] instructionSets = new String[] {
6570                    getPrimaryInstructionSet(pkg.applicationInfo) };
6571
6572            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6573
6574            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6575                    true /* inclDependencies */);
6576
6577            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6578            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6579                throw new IllegalStateException("Failed to dexopt: " + res);
6580            }
6581        }
6582    }
6583
6584    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6585        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6586            Slog.w(TAG, "Unable to update from " + oldPkg.name
6587                    + " to " + newPkg.packageName
6588                    + ": old package not in system partition");
6589            return false;
6590        } else if (mPackages.get(oldPkg.name) != null) {
6591            Slog.w(TAG, "Unable to update from " + oldPkg.name
6592                    + " to " + newPkg.packageName
6593                    + ": old package still exists");
6594            return false;
6595        }
6596        return true;
6597    }
6598
6599    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6600            throws PackageManagerException {
6601        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6602        if (res != 0) {
6603            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6604                    "Failed to install " + packageName + ": " + res);
6605        }
6606
6607        final int[] users = sUserManager.getUserIds();
6608        for (int user : users) {
6609            if (user != 0) {
6610                res = mInstaller.createUserData(volumeUuid, packageName,
6611                        UserHandle.getUid(user, uid), user, seinfo);
6612                if (res != 0) {
6613                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6614                            "Failed to createUserData " + packageName + ": " + res);
6615                }
6616            }
6617        }
6618    }
6619
6620    private int removeDataDirsLI(String volumeUuid, String packageName) {
6621        int[] users = sUserManager.getUserIds();
6622        int res = 0;
6623        for (int user : users) {
6624            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6625            if (resInner < 0) {
6626                res = resInner;
6627            }
6628        }
6629
6630        return res;
6631    }
6632
6633    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6634        int[] users = sUserManager.getUserIds();
6635        int res = 0;
6636        for (int user : users) {
6637            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6638            if (resInner < 0) {
6639                res = resInner;
6640            }
6641        }
6642        return res;
6643    }
6644
6645    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6646            PackageParser.Package changingLib) {
6647        if (file.path != null) {
6648            usesLibraryFiles.add(file.path);
6649            return;
6650        }
6651        PackageParser.Package p = mPackages.get(file.apk);
6652        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6653            // If we are doing this while in the middle of updating a library apk,
6654            // then we need to make sure to use that new apk for determining the
6655            // dependencies here.  (We haven't yet finished committing the new apk
6656            // to the package manager state.)
6657            if (p == null || p.packageName.equals(changingLib.packageName)) {
6658                p = changingLib;
6659            }
6660        }
6661        if (p != null) {
6662            usesLibraryFiles.addAll(p.getAllCodePaths());
6663        }
6664    }
6665
6666    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6667            PackageParser.Package changingLib) throws PackageManagerException {
6668        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6669            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6670            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6671            for (int i=0; i<N; i++) {
6672                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6673                if (file == null) {
6674                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6675                            "Package " + pkg.packageName + " requires unavailable shared library "
6676                            + pkg.usesLibraries.get(i) + "; failing!");
6677                }
6678                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6679            }
6680            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6681            for (int i=0; i<N; i++) {
6682                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6683                if (file == null) {
6684                    Slog.w(TAG, "Package " + pkg.packageName
6685                            + " desires unavailable shared library "
6686                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6687                } else {
6688                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6689                }
6690            }
6691            N = usesLibraryFiles.size();
6692            if (N > 0) {
6693                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6694            } else {
6695                pkg.usesLibraryFiles = null;
6696            }
6697        }
6698    }
6699
6700    private static boolean hasString(List<String> list, List<String> which) {
6701        if (list == null) {
6702            return false;
6703        }
6704        for (int i=list.size()-1; i>=0; i--) {
6705            for (int j=which.size()-1; j>=0; j--) {
6706                if (which.get(j).equals(list.get(i))) {
6707                    return true;
6708                }
6709            }
6710        }
6711        return false;
6712    }
6713
6714    private void updateAllSharedLibrariesLPw() {
6715        for (PackageParser.Package pkg : mPackages.values()) {
6716            try {
6717                updateSharedLibrariesLPw(pkg, null);
6718            } catch (PackageManagerException e) {
6719                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6720            }
6721        }
6722    }
6723
6724    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6725            PackageParser.Package changingPkg) {
6726        ArrayList<PackageParser.Package> res = null;
6727        for (PackageParser.Package pkg : mPackages.values()) {
6728            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6729                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6730                if (res == null) {
6731                    res = new ArrayList<PackageParser.Package>();
6732                }
6733                res.add(pkg);
6734                try {
6735                    updateSharedLibrariesLPw(pkg, changingPkg);
6736                } catch (PackageManagerException e) {
6737                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6738                }
6739            }
6740        }
6741        return res;
6742    }
6743
6744    /**
6745     * Derive the value of the {@code cpuAbiOverride} based on the provided
6746     * value and an optional stored value from the package settings.
6747     */
6748    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6749        String cpuAbiOverride = null;
6750
6751        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6752            cpuAbiOverride = null;
6753        } else if (abiOverride != null) {
6754            cpuAbiOverride = abiOverride;
6755        } else if (settings != null) {
6756            cpuAbiOverride = settings.cpuAbiOverrideString;
6757        }
6758
6759        return cpuAbiOverride;
6760    }
6761
6762    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6763            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6764        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6765        try {
6766            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6767        } finally {
6768            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6769        }
6770    }
6771
6772    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6773            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6774        boolean success = false;
6775        try {
6776            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6777                    currentTime, user);
6778            success = true;
6779            return res;
6780        } finally {
6781            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6782                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6783            }
6784        }
6785    }
6786
6787    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6788            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6789        final File scanFile = new File(pkg.codePath);
6790        if (pkg.applicationInfo.getCodePath() == null ||
6791                pkg.applicationInfo.getResourcePath() == null) {
6792            // Bail out. The resource and code paths haven't been set.
6793            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6794                    "Code and resource paths haven't been set correctly");
6795        }
6796
6797        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6798            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6799        } else {
6800            // Only allow system apps to be flagged as core apps.
6801            pkg.coreApp = false;
6802        }
6803
6804        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6805            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6806        }
6807
6808        if (mCustomResolverComponentName != null &&
6809                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6810            setUpCustomResolverActivity(pkg);
6811        }
6812
6813        if (pkg.packageName.equals("android")) {
6814            synchronized (mPackages) {
6815                if (mAndroidApplication != null) {
6816                    Slog.w(TAG, "*************************************************");
6817                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6818                    Slog.w(TAG, " file=" + scanFile);
6819                    Slog.w(TAG, "*************************************************");
6820                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6821                            "Core android package being redefined.  Skipping.");
6822                }
6823
6824                // Set up information for our fall-back user intent resolution activity.
6825                mPlatformPackage = pkg;
6826                pkg.mVersionCode = mSdkVersion;
6827                mAndroidApplication = pkg.applicationInfo;
6828
6829                if (!mResolverReplaced) {
6830                    mResolveActivity.applicationInfo = mAndroidApplication;
6831                    mResolveActivity.name = ResolverActivity.class.getName();
6832                    mResolveActivity.packageName = mAndroidApplication.packageName;
6833                    mResolveActivity.processName = "system:ui";
6834                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6835                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6836                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6837                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6838                    mResolveActivity.exported = true;
6839                    mResolveActivity.enabled = true;
6840                    mResolveInfo.activityInfo = mResolveActivity;
6841                    mResolveInfo.priority = 0;
6842                    mResolveInfo.preferredOrder = 0;
6843                    mResolveInfo.match = 0;
6844                    mResolveComponentName = new ComponentName(
6845                            mAndroidApplication.packageName, mResolveActivity.name);
6846                }
6847            }
6848        }
6849
6850        if (DEBUG_PACKAGE_SCANNING) {
6851            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6852                Log.d(TAG, "Scanning package " + pkg.packageName);
6853        }
6854
6855        if (mPackages.containsKey(pkg.packageName)
6856                || mSharedLibraries.containsKey(pkg.packageName)) {
6857            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6858                    "Application package " + pkg.packageName
6859                    + " already installed.  Skipping duplicate.");
6860        }
6861
6862        // If we're only installing presumed-existing packages, require that the
6863        // scanned APK is both already known and at the path previously established
6864        // for it.  Previously unknown packages we pick up normally, but if we have an
6865        // a priori expectation about this package's install presence, enforce it.
6866        // With a singular exception for new system packages. When an OTA contains
6867        // a new system package, we allow the codepath to change from a system location
6868        // to the user-installed location. If we don't allow this change, any newer,
6869        // user-installed version of the application will be ignored.
6870        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6871            if (mExpectingBetter.containsKey(pkg.packageName)) {
6872                logCriticalInfo(Log.WARN,
6873                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6874            } else {
6875                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6876                if (known != null) {
6877                    if (DEBUG_PACKAGE_SCANNING) {
6878                        Log.d(TAG, "Examining " + pkg.codePath
6879                                + " and requiring known paths " + known.codePathString
6880                                + " & " + known.resourcePathString);
6881                    }
6882                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6883                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6884                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6885                                "Application package " + pkg.packageName
6886                                + " found at " + pkg.applicationInfo.getCodePath()
6887                                + " but expected at " + known.codePathString + "; ignoring.");
6888                    }
6889                }
6890            }
6891        }
6892
6893        // Initialize package source and resource directories
6894        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6895        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6896
6897        SharedUserSetting suid = null;
6898        PackageSetting pkgSetting = null;
6899
6900        if (!isSystemApp(pkg)) {
6901            // Only system apps can use these features.
6902            pkg.mOriginalPackages = null;
6903            pkg.mRealPackage = null;
6904            pkg.mAdoptPermissions = null;
6905        }
6906
6907        // writer
6908        synchronized (mPackages) {
6909            if (pkg.mSharedUserId != null) {
6910                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6911                if (suid == null) {
6912                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6913                            "Creating application package " + pkg.packageName
6914                            + " for shared user failed");
6915                }
6916                if (DEBUG_PACKAGE_SCANNING) {
6917                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6918                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6919                                + "): packages=" + suid.packages);
6920                }
6921            }
6922
6923            // Check if we are renaming from an original package name.
6924            PackageSetting origPackage = null;
6925            String realName = null;
6926            if (pkg.mOriginalPackages != null) {
6927                // This package may need to be renamed to a previously
6928                // installed name.  Let's check on that...
6929                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6930                if (pkg.mOriginalPackages.contains(renamed)) {
6931                    // This package had originally been installed as the
6932                    // original name, and we have already taken care of
6933                    // transitioning to the new one.  Just update the new
6934                    // one to continue using the old name.
6935                    realName = pkg.mRealPackage;
6936                    if (!pkg.packageName.equals(renamed)) {
6937                        // Callers into this function may have already taken
6938                        // care of renaming the package; only do it here if
6939                        // it is not already done.
6940                        pkg.setPackageName(renamed);
6941                    }
6942
6943                } else {
6944                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6945                        if ((origPackage = mSettings.peekPackageLPr(
6946                                pkg.mOriginalPackages.get(i))) != null) {
6947                            // We do have the package already installed under its
6948                            // original name...  should we use it?
6949                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6950                                // New package is not compatible with original.
6951                                origPackage = null;
6952                                continue;
6953                            } else if (origPackage.sharedUser != null) {
6954                                // Make sure uid is compatible between packages.
6955                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6956                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6957                                            + " to " + pkg.packageName + ": old uid "
6958                                            + origPackage.sharedUser.name
6959                                            + " differs from " + pkg.mSharedUserId);
6960                                    origPackage = null;
6961                                    continue;
6962                                }
6963                            } else {
6964                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6965                                        + pkg.packageName + " to old name " + origPackage.name);
6966                            }
6967                            break;
6968                        }
6969                    }
6970                }
6971            }
6972
6973            if (mTransferedPackages.contains(pkg.packageName)) {
6974                Slog.w(TAG, "Package " + pkg.packageName
6975                        + " was transferred to another, but its .apk remains");
6976            }
6977
6978            // Just create the setting, don't add it yet. For already existing packages
6979            // the PkgSetting exists already and doesn't have to be created.
6980            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6981                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6982                    pkg.applicationInfo.primaryCpuAbi,
6983                    pkg.applicationInfo.secondaryCpuAbi,
6984                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6985                    user, false);
6986            if (pkgSetting == null) {
6987                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6988                        "Creating application package " + pkg.packageName + " failed");
6989            }
6990
6991            if (pkgSetting.origPackage != null) {
6992                // If we are first transitioning from an original package,
6993                // fix up the new package's name now.  We need to do this after
6994                // looking up the package under its new name, so getPackageLP
6995                // can take care of fiddling things correctly.
6996                pkg.setPackageName(origPackage.name);
6997
6998                // File a report about this.
6999                String msg = "New package " + pkgSetting.realName
7000                        + " renamed to replace old package " + pkgSetting.name;
7001                reportSettingsProblem(Log.WARN, msg);
7002
7003                // Make a note of it.
7004                mTransferedPackages.add(origPackage.name);
7005
7006                // No longer need to retain this.
7007                pkgSetting.origPackage = null;
7008            }
7009
7010            if (realName != null) {
7011                // Make a note of it.
7012                mTransferedPackages.add(pkg.packageName);
7013            }
7014
7015            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7016                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7017            }
7018
7019            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7020                // Check all shared libraries and map to their actual file path.
7021                // We only do this here for apps not on a system dir, because those
7022                // are the only ones that can fail an install due to this.  We
7023                // will take care of the system apps by updating all of their
7024                // library paths after the scan is done.
7025                updateSharedLibrariesLPw(pkg, null);
7026            }
7027
7028            if (mFoundPolicyFile) {
7029                SELinuxMMAC.assignSeinfoValue(pkg);
7030            }
7031
7032            pkg.applicationInfo.uid = pkgSetting.appId;
7033            pkg.mExtras = pkgSetting;
7034            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7035                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7036                    // We just determined the app is signed correctly, so bring
7037                    // over the latest parsed certs.
7038                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7039                } else {
7040                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7041                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7042                                "Package " + pkg.packageName + " upgrade keys do not match the "
7043                                + "previously installed version");
7044                    } else {
7045                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7046                        String msg = "System package " + pkg.packageName
7047                            + " signature changed; retaining data.";
7048                        reportSettingsProblem(Log.WARN, msg);
7049                    }
7050                }
7051            } else {
7052                try {
7053                    verifySignaturesLP(pkgSetting, pkg);
7054                    // We just determined the app is signed correctly, so bring
7055                    // over the latest parsed certs.
7056                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7057                } catch (PackageManagerException e) {
7058                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7059                        throw e;
7060                    }
7061                    // The signature has changed, but this package is in the system
7062                    // image...  let's recover!
7063                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7064                    // However...  if this package is part of a shared user, but it
7065                    // doesn't match the signature of the shared user, let's fail.
7066                    // What this means is that you can't change the signatures
7067                    // associated with an overall shared user, which doesn't seem all
7068                    // that unreasonable.
7069                    if (pkgSetting.sharedUser != null) {
7070                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7071                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7072                            throw new PackageManagerException(
7073                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7074                                            "Signature mismatch for shared user : "
7075                                            + pkgSetting.sharedUser);
7076                        }
7077                    }
7078                    // File a report about this.
7079                    String msg = "System package " + pkg.packageName
7080                        + " signature changed; retaining data.";
7081                    reportSettingsProblem(Log.WARN, msg);
7082                }
7083            }
7084            // Verify that this new package doesn't have any content providers
7085            // that conflict with existing packages.  Only do this if the
7086            // package isn't already installed, since we don't want to break
7087            // things that are installed.
7088            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7089                final int N = pkg.providers.size();
7090                int i;
7091                for (i=0; i<N; i++) {
7092                    PackageParser.Provider p = pkg.providers.get(i);
7093                    if (p.info.authority != null) {
7094                        String names[] = p.info.authority.split(";");
7095                        for (int j = 0; j < names.length; j++) {
7096                            if (mProvidersByAuthority.containsKey(names[j])) {
7097                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7098                                final String otherPackageName =
7099                                        ((other != null && other.getComponentName() != null) ?
7100                                                other.getComponentName().getPackageName() : "?");
7101                                throw new PackageManagerException(
7102                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7103                                                "Can't install because provider name " + names[j]
7104                                                + " (in package " + pkg.applicationInfo.packageName
7105                                                + ") is already used by " + otherPackageName);
7106                            }
7107                        }
7108                    }
7109                }
7110            }
7111
7112            if (pkg.mAdoptPermissions != null) {
7113                // This package wants to adopt ownership of permissions from
7114                // another package.
7115                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7116                    final String origName = pkg.mAdoptPermissions.get(i);
7117                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7118                    if (orig != null) {
7119                        if (verifyPackageUpdateLPr(orig, pkg)) {
7120                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7121                                    + pkg.packageName);
7122                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7123                        }
7124                    }
7125                }
7126            }
7127        }
7128
7129        final String pkgName = pkg.packageName;
7130
7131        final long scanFileTime = scanFile.lastModified();
7132        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7133        pkg.applicationInfo.processName = fixProcessName(
7134                pkg.applicationInfo.packageName,
7135                pkg.applicationInfo.processName,
7136                pkg.applicationInfo.uid);
7137
7138        if (pkg != mPlatformPackage) {
7139            // This is a normal package, need to make its data directory.
7140            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7141                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7142
7143            boolean uidError = false;
7144            if (dataPath.exists()) {
7145                int currentUid = 0;
7146                try {
7147                    StructStat stat = Os.stat(dataPath.getPath());
7148                    currentUid = stat.st_uid;
7149                } catch (ErrnoException e) {
7150                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7151                }
7152
7153                // If we have mismatched owners for the data path, we have a problem.
7154                if (currentUid != pkg.applicationInfo.uid) {
7155                    boolean recovered = false;
7156                    if (currentUid == 0) {
7157                        // The directory somehow became owned by root.  Wow.
7158                        // This is probably because the system was stopped while
7159                        // installd was in the middle of messing with its libs
7160                        // directory.  Ask installd to fix that.
7161                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7162                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7163                        if (ret >= 0) {
7164                            recovered = true;
7165                            String msg = "Package " + pkg.packageName
7166                                    + " unexpectedly changed to uid 0; recovered to " +
7167                                    + pkg.applicationInfo.uid;
7168                            reportSettingsProblem(Log.WARN, msg);
7169                        }
7170                    }
7171                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7172                            || (scanFlags&SCAN_BOOTING) != 0)) {
7173                        // If this is a system app, we can at least delete its
7174                        // current data so the application will still work.
7175                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7176                        if (ret >= 0) {
7177                            // TODO: Kill the processes first
7178                            // Old data gone!
7179                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7180                                    ? "System package " : "Third party package ";
7181                            String msg = prefix + pkg.packageName
7182                                    + " has changed from uid: "
7183                                    + currentUid + " to "
7184                                    + pkg.applicationInfo.uid + "; old data erased";
7185                            reportSettingsProblem(Log.WARN, msg);
7186                            recovered = true;
7187                        }
7188                        if (!recovered) {
7189                            mHasSystemUidErrors = true;
7190                        }
7191                    } else if (!recovered) {
7192                        // If we allow this install to proceed, we will be broken.
7193                        // Abort, abort!
7194                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7195                                "scanPackageLI");
7196                    }
7197                    if (!recovered) {
7198                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7199                            + pkg.applicationInfo.uid + "/fs_"
7200                            + currentUid;
7201                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7202                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7203                        String msg = "Package " + pkg.packageName
7204                                + " has mismatched uid: "
7205                                + currentUid + " on disk, "
7206                                + pkg.applicationInfo.uid + " in settings";
7207                        // writer
7208                        synchronized (mPackages) {
7209                            mSettings.mReadMessages.append(msg);
7210                            mSettings.mReadMessages.append('\n');
7211                            uidError = true;
7212                            if (!pkgSetting.uidError) {
7213                                reportSettingsProblem(Log.ERROR, msg);
7214                            }
7215                        }
7216                    }
7217                }
7218
7219                // Ensure that directories are prepared
7220                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7221                        pkg.applicationInfo.seinfo);
7222
7223                if (mShouldRestoreconData) {
7224                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7225                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7226                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7227                }
7228            } else {
7229                if (DEBUG_PACKAGE_SCANNING) {
7230                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7231                        Log.v(TAG, "Want this data dir: " + dataPath);
7232                }
7233                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7234                        pkg.applicationInfo.seinfo);
7235            }
7236
7237            // Get all of our default paths setup
7238            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7239
7240            pkgSetting.uidError = uidError;
7241        }
7242
7243        final String path = scanFile.getPath();
7244        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7245
7246        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7247            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7248
7249            // Some system apps still use directory structure for native libraries
7250            // in which case we might end up not detecting abi solely based on apk
7251            // structure. Try to detect abi based on directory structure.
7252            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7253                    pkg.applicationInfo.primaryCpuAbi == null) {
7254                setBundledAppAbisAndRoots(pkg, pkgSetting);
7255                setNativeLibraryPaths(pkg);
7256            }
7257
7258        } else {
7259            if ((scanFlags & SCAN_MOVE) != 0) {
7260                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7261                // but we already have this packages package info in the PackageSetting. We just
7262                // use that and derive the native library path based on the new codepath.
7263                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7264                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7265            }
7266
7267            // Set native library paths again. For moves, the path will be updated based on the
7268            // ABIs we've determined above. For non-moves, the path will be updated based on the
7269            // ABIs we determined during compilation, but the path will depend on the final
7270            // package path (after the rename away from the stage path).
7271            setNativeLibraryPaths(pkg);
7272        }
7273
7274        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7275        final int[] userIds = sUserManager.getUserIds();
7276        synchronized (mInstallLock) {
7277            // Make sure all user data directories are ready to roll; we're okay
7278            // if they already exist
7279            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7280                for (int userId : userIds) {
7281                    if (userId != UserHandle.USER_SYSTEM) {
7282                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7283                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7284                                pkg.applicationInfo.seinfo);
7285                    }
7286                }
7287            }
7288
7289            // Create a native library symlink only if we have native libraries
7290            // and if the native libraries are 32 bit libraries. We do not provide
7291            // this symlink for 64 bit libraries.
7292            if (pkg.applicationInfo.primaryCpuAbi != null &&
7293                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7294                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7295                try {
7296                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7297                    for (int userId : userIds) {
7298                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7299                                nativeLibPath, userId) < 0) {
7300                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7301                                    "Failed linking native library dir (user=" + userId + ")");
7302                        }
7303                    }
7304                } finally {
7305                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7306                }
7307            }
7308        }
7309
7310        // This is a special case for the "system" package, where the ABI is
7311        // dictated by the zygote configuration (and init.rc). We should keep track
7312        // of this ABI so that we can deal with "normal" applications that run under
7313        // the same UID correctly.
7314        if (mPlatformPackage == pkg) {
7315            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7316                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7317        }
7318
7319        // If there's a mismatch between the abi-override in the package setting
7320        // and the abiOverride specified for the install. Warn about this because we
7321        // would've already compiled the app without taking the package setting into
7322        // account.
7323        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7324            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7325                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7326                        " for package: " + pkg.packageName);
7327            }
7328        }
7329
7330        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7331        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7332        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7333
7334        // Copy the derived override back to the parsed package, so that we can
7335        // update the package settings accordingly.
7336        pkg.cpuAbiOverride = cpuAbiOverride;
7337
7338        if (DEBUG_ABI_SELECTION) {
7339            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7340                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7341                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7342        }
7343
7344        // Push the derived path down into PackageSettings so we know what to
7345        // clean up at uninstall time.
7346        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7347
7348        if (DEBUG_ABI_SELECTION) {
7349            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7350                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7351                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7352        }
7353
7354        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7355            // We don't do this here during boot because we can do it all
7356            // at once after scanning all existing packages.
7357            //
7358            // We also do this *before* we perform dexopt on this package, so that
7359            // we can avoid redundant dexopts, and also to make sure we've got the
7360            // code and package path correct.
7361            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7362                    pkg, true /* boot complete */);
7363        }
7364
7365        if (mFactoryTest && pkg.requestedPermissions.contains(
7366                android.Manifest.permission.FACTORY_TEST)) {
7367            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7368        }
7369
7370        ArrayList<PackageParser.Package> clientLibPkgs = null;
7371
7372        // writer
7373        synchronized (mPackages) {
7374            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7375                // Only system apps can add new shared libraries.
7376                if (pkg.libraryNames != null) {
7377                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7378                        String name = pkg.libraryNames.get(i);
7379                        boolean allowed = false;
7380                        if (pkg.isUpdatedSystemApp()) {
7381                            // New library entries can only be added through the
7382                            // system image.  This is important to get rid of a lot
7383                            // of nasty edge cases: for example if we allowed a non-
7384                            // system update of the app to add a library, then uninstalling
7385                            // the update would make the library go away, and assumptions
7386                            // we made such as through app install filtering would now
7387                            // have allowed apps on the device which aren't compatible
7388                            // with it.  Better to just have the restriction here, be
7389                            // conservative, and create many fewer cases that can negatively
7390                            // impact the user experience.
7391                            final PackageSetting sysPs = mSettings
7392                                    .getDisabledSystemPkgLPr(pkg.packageName);
7393                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7394                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7395                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7396                                        allowed = true;
7397                                        break;
7398                                    }
7399                                }
7400                            }
7401                        } else {
7402                            allowed = true;
7403                        }
7404                        if (allowed) {
7405                            if (!mSharedLibraries.containsKey(name)) {
7406                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7407                            } else if (!name.equals(pkg.packageName)) {
7408                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7409                                        + name + " already exists; skipping");
7410                            }
7411                        } else {
7412                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7413                                    + name + " that is not declared on system image; skipping");
7414                        }
7415                    }
7416                    if ((scanFlags & SCAN_BOOTING) == 0) {
7417                        // If we are not booting, we need to update any applications
7418                        // that are clients of our shared library.  If we are booting,
7419                        // this will all be done once the scan is complete.
7420                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7421                    }
7422                }
7423            }
7424        }
7425
7426        // Request the ActivityManager to kill the process(only for existing packages)
7427        // so that we do not end up in a confused state while the user is still using the older
7428        // version of the application while the new one gets installed.
7429        if ((scanFlags & SCAN_REPLACING) != 0) {
7430            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7431
7432            killApplication(pkg.applicationInfo.packageName,
7433                        pkg.applicationInfo.uid, "replace pkg");
7434
7435            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7436        }
7437
7438        // Also need to kill any apps that are dependent on the library.
7439        if (clientLibPkgs != null) {
7440            for (int i=0; i<clientLibPkgs.size(); i++) {
7441                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7442                killApplication(clientPkg.applicationInfo.packageName,
7443                        clientPkg.applicationInfo.uid, "update lib");
7444            }
7445        }
7446
7447        // Make sure we're not adding any bogus keyset info
7448        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7449        ksms.assertScannedPackageValid(pkg);
7450
7451        // writer
7452        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7453
7454        boolean createIdmapFailed = false;
7455        synchronized (mPackages) {
7456            // We don't expect installation to fail beyond this point
7457
7458            // Add the new setting to mSettings
7459            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7460            // Add the new setting to mPackages
7461            mPackages.put(pkg.applicationInfo.packageName, pkg);
7462            // Make sure we don't accidentally delete its data.
7463            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7464            while (iter.hasNext()) {
7465                PackageCleanItem item = iter.next();
7466                if (pkgName.equals(item.packageName)) {
7467                    iter.remove();
7468                }
7469            }
7470
7471            // Take care of first install / last update times.
7472            if (currentTime != 0) {
7473                if (pkgSetting.firstInstallTime == 0) {
7474                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7475                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7476                    pkgSetting.lastUpdateTime = currentTime;
7477                }
7478            } else if (pkgSetting.firstInstallTime == 0) {
7479                // We need *something*.  Take time time stamp of the file.
7480                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7481            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7482                if (scanFileTime != pkgSetting.timeStamp) {
7483                    // A package on the system image has changed; consider this
7484                    // to be an update.
7485                    pkgSetting.lastUpdateTime = scanFileTime;
7486                }
7487            }
7488
7489            // Add the package's KeySets to the global KeySetManagerService
7490            ksms.addScannedPackageLPw(pkg);
7491
7492            int N = pkg.providers.size();
7493            StringBuilder r = null;
7494            int i;
7495            for (i=0; i<N; i++) {
7496                PackageParser.Provider p = pkg.providers.get(i);
7497                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7498                        p.info.processName, pkg.applicationInfo.uid);
7499                mProviders.addProvider(p);
7500                p.syncable = p.info.isSyncable;
7501                if (p.info.authority != null) {
7502                    String names[] = p.info.authority.split(";");
7503                    p.info.authority = null;
7504                    for (int j = 0; j < names.length; j++) {
7505                        if (j == 1 && p.syncable) {
7506                            // We only want the first authority for a provider to possibly be
7507                            // syncable, so if we already added this provider using a different
7508                            // authority clear the syncable flag. We copy the provider before
7509                            // changing it because the mProviders object contains a reference
7510                            // to a provider that we don't want to change.
7511                            // Only do this for the second authority since the resulting provider
7512                            // object can be the same for all future authorities for this provider.
7513                            p = new PackageParser.Provider(p);
7514                            p.syncable = false;
7515                        }
7516                        if (!mProvidersByAuthority.containsKey(names[j])) {
7517                            mProvidersByAuthority.put(names[j], p);
7518                            if (p.info.authority == null) {
7519                                p.info.authority = names[j];
7520                            } else {
7521                                p.info.authority = p.info.authority + ";" + names[j];
7522                            }
7523                            if (DEBUG_PACKAGE_SCANNING) {
7524                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7525                                    Log.d(TAG, "Registered content provider: " + names[j]
7526                                            + ", className = " + p.info.name + ", isSyncable = "
7527                                            + p.info.isSyncable);
7528                            }
7529                        } else {
7530                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7531                            Slog.w(TAG, "Skipping provider name " + names[j] +
7532                                    " (in package " + pkg.applicationInfo.packageName +
7533                                    "): name already used by "
7534                                    + ((other != null && other.getComponentName() != null)
7535                                            ? other.getComponentName().getPackageName() : "?"));
7536                        }
7537                    }
7538                }
7539                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7540                    if (r == null) {
7541                        r = new StringBuilder(256);
7542                    } else {
7543                        r.append(' ');
7544                    }
7545                    r.append(p.info.name);
7546                }
7547            }
7548            if (r != null) {
7549                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7550            }
7551
7552            N = pkg.services.size();
7553            r = null;
7554            for (i=0; i<N; i++) {
7555                PackageParser.Service s = pkg.services.get(i);
7556                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7557                        s.info.processName, pkg.applicationInfo.uid);
7558                mServices.addService(s);
7559                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7560                    if (r == null) {
7561                        r = new StringBuilder(256);
7562                    } else {
7563                        r.append(' ');
7564                    }
7565                    r.append(s.info.name);
7566                }
7567            }
7568            if (r != null) {
7569                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7570            }
7571
7572            N = pkg.receivers.size();
7573            r = null;
7574            for (i=0; i<N; i++) {
7575                PackageParser.Activity a = pkg.receivers.get(i);
7576                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7577                        a.info.processName, pkg.applicationInfo.uid);
7578                mReceivers.addActivity(a, "receiver");
7579                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7580                    if (r == null) {
7581                        r = new StringBuilder(256);
7582                    } else {
7583                        r.append(' ');
7584                    }
7585                    r.append(a.info.name);
7586                }
7587            }
7588            if (r != null) {
7589                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7590            }
7591
7592            N = pkg.activities.size();
7593            r = null;
7594            for (i=0; i<N; i++) {
7595                PackageParser.Activity a = pkg.activities.get(i);
7596                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7597                        a.info.processName, pkg.applicationInfo.uid);
7598                mActivities.addActivity(a, "activity");
7599                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7600                    if (r == null) {
7601                        r = new StringBuilder(256);
7602                    } else {
7603                        r.append(' ');
7604                    }
7605                    r.append(a.info.name);
7606                }
7607            }
7608            if (r != null) {
7609                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7610            }
7611
7612            N = pkg.permissionGroups.size();
7613            r = null;
7614            for (i=0; i<N; i++) {
7615                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7616                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7617                if (cur == null) {
7618                    mPermissionGroups.put(pg.info.name, pg);
7619                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7620                        if (r == null) {
7621                            r = new StringBuilder(256);
7622                        } else {
7623                            r.append(' ');
7624                        }
7625                        r.append(pg.info.name);
7626                    }
7627                } else {
7628                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7629                            + pg.info.packageName + " ignored: original from "
7630                            + cur.info.packageName);
7631                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7632                        if (r == null) {
7633                            r = new StringBuilder(256);
7634                        } else {
7635                            r.append(' ');
7636                        }
7637                        r.append("DUP:");
7638                        r.append(pg.info.name);
7639                    }
7640                }
7641            }
7642            if (r != null) {
7643                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7644            }
7645
7646            N = pkg.permissions.size();
7647            r = null;
7648            for (i=0; i<N; i++) {
7649                PackageParser.Permission p = pkg.permissions.get(i);
7650
7651                // Assume by default that we did not install this permission into the system.
7652                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7653
7654                // Now that permission groups have a special meaning, we ignore permission
7655                // groups for legacy apps to prevent unexpected behavior. In particular,
7656                // permissions for one app being granted to someone just becuase they happen
7657                // to be in a group defined by another app (before this had no implications).
7658                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7659                    p.group = mPermissionGroups.get(p.info.group);
7660                    // Warn for a permission in an unknown group.
7661                    if (p.info.group != null && p.group == null) {
7662                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7663                                + p.info.packageName + " in an unknown group " + p.info.group);
7664                    }
7665                }
7666
7667                ArrayMap<String, BasePermission> permissionMap =
7668                        p.tree ? mSettings.mPermissionTrees
7669                                : mSettings.mPermissions;
7670                BasePermission bp = permissionMap.get(p.info.name);
7671
7672                // Allow system apps to redefine non-system permissions
7673                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7674                    final boolean currentOwnerIsSystem = (bp.perm != null
7675                            && isSystemApp(bp.perm.owner));
7676                    if (isSystemApp(p.owner)) {
7677                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7678                            // It's a built-in permission and no owner, take ownership now
7679                            bp.packageSetting = pkgSetting;
7680                            bp.perm = p;
7681                            bp.uid = pkg.applicationInfo.uid;
7682                            bp.sourcePackage = p.info.packageName;
7683                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7684                        } else if (!currentOwnerIsSystem) {
7685                            String msg = "New decl " + p.owner + " of permission  "
7686                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7687                            reportSettingsProblem(Log.WARN, msg);
7688                            bp = null;
7689                        }
7690                    }
7691                }
7692
7693                if (bp == null) {
7694                    bp = new BasePermission(p.info.name, p.info.packageName,
7695                            BasePermission.TYPE_NORMAL);
7696                    permissionMap.put(p.info.name, bp);
7697                }
7698
7699                if (bp.perm == null) {
7700                    if (bp.sourcePackage == null
7701                            || bp.sourcePackage.equals(p.info.packageName)) {
7702                        BasePermission tree = findPermissionTreeLP(p.info.name);
7703                        if (tree == null
7704                                || tree.sourcePackage.equals(p.info.packageName)) {
7705                            bp.packageSetting = pkgSetting;
7706                            bp.perm = p;
7707                            bp.uid = pkg.applicationInfo.uid;
7708                            bp.sourcePackage = p.info.packageName;
7709                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7710                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7711                                if (r == null) {
7712                                    r = new StringBuilder(256);
7713                                } else {
7714                                    r.append(' ');
7715                                }
7716                                r.append(p.info.name);
7717                            }
7718                        } else {
7719                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7720                                    + p.info.packageName + " ignored: base tree "
7721                                    + tree.name + " is from package "
7722                                    + tree.sourcePackage);
7723                        }
7724                    } else {
7725                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7726                                + p.info.packageName + " ignored: original from "
7727                                + bp.sourcePackage);
7728                    }
7729                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7730                    if (r == null) {
7731                        r = new StringBuilder(256);
7732                    } else {
7733                        r.append(' ');
7734                    }
7735                    r.append("DUP:");
7736                    r.append(p.info.name);
7737                }
7738                if (bp.perm == p) {
7739                    bp.protectionLevel = p.info.protectionLevel;
7740                }
7741            }
7742
7743            if (r != null) {
7744                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7745            }
7746
7747            N = pkg.instrumentation.size();
7748            r = null;
7749            for (i=0; i<N; i++) {
7750                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7751                a.info.packageName = pkg.applicationInfo.packageName;
7752                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7753                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7754                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7755                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7756                a.info.dataDir = pkg.applicationInfo.dataDir;
7757                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7758                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7759
7760                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7761                // need other information about the application, like the ABI and what not ?
7762                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7763                mInstrumentation.put(a.getComponentName(), a);
7764                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7765                    if (r == null) {
7766                        r = new StringBuilder(256);
7767                    } else {
7768                        r.append(' ');
7769                    }
7770                    r.append(a.info.name);
7771                }
7772            }
7773            if (r != null) {
7774                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7775            }
7776
7777            if (pkg.protectedBroadcasts != null) {
7778                N = pkg.protectedBroadcasts.size();
7779                for (i=0; i<N; i++) {
7780                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7781                }
7782            }
7783
7784            pkgSetting.setTimeStamp(scanFileTime);
7785
7786            // Create idmap files for pairs of (packages, overlay packages).
7787            // Note: "android", ie framework-res.apk, is handled by native layers.
7788            if (pkg.mOverlayTarget != null) {
7789                // This is an overlay package.
7790                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7791                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7792                        mOverlays.put(pkg.mOverlayTarget,
7793                                new ArrayMap<String, PackageParser.Package>());
7794                    }
7795                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7796                    map.put(pkg.packageName, pkg);
7797                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7798                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7799                        createIdmapFailed = true;
7800                    }
7801                }
7802            } else if (mOverlays.containsKey(pkg.packageName) &&
7803                    !pkg.packageName.equals("android")) {
7804                // This is a regular package, with one or more known overlay packages.
7805                createIdmapsForPackageLI(pkg);
7806            }
7807        }
7808
7809        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7810
7811        if (createIdmapFailed) {
7812            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7813                    "scanPackageLI failed to createIdmap");
7814        }
7815        return pkg;
7816    }
7817
7818    /**
7819     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7820     * is derived purely on the basis of the contents of {@code scanFile} and
7821     * {@code cpuAbiOverride}.
7822     *
7823     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7824     */
7825    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7826                                 String cpuAbiOverride, boolean extractLibs)
7827            throws PackageManagerException {
7828        // TODO: We can probably be smarter about this stuff. For installed apps,
7829        // we can calculate this information at install time once and for all. For
7830        // system apps, we can probably assume that this information doesn't change
7831        // after the first boot scan. As things stand, we do lots of unnecessary work.
7832
7833        // Give ourselves some initial paths; we'll come back for another
7834        // pass once we've determined ABI below.
7835        setNativeLibraryPaths(pkg);
7836
7837        // We would never need to extract libs for forward-locked and external packages,
7838        // since the container service will do it for us. We shouldn't attempt to
7839        // extract libs from system app when it was not updated.
7840        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7841                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7842            extractLibs = false;
7843        }
7844
7845        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7846        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7847
7848        NativeLibraryHelper.Handle handle = null;
7849        try {
7850            handle = NativeLibraryHelper.Handle.create(pkg);
7851            // TODO(multiArch): This can be null for apps that didn't go through the
7852            // usual installation process. We can calculate it again, like we
7853            // do during install time.
7854            //
7855            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7856            // unnecessary.
7857            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7858
7859            // Null out the abis so that they can be recalculated.
7860            pkg.applicationInfo.primaryCpuAbi = null;
7861            pkg.applicationInfo.secondaryCpuAbi = null;
7862            if (isMultiArch(pkg.applicationInfo)) {
7863                // Warn if we've set an abiOverride for multi-lib packages..
7864                // By definition, we need to copy both 32 and 64 bit libraries for
7865                // such packages.
7866                if (pkg.cpuAbiOverride != null
7867                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7868                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7869                }
7870
7871                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7872                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7873                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7874                    if (extractLibs) {
7875                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7876                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7877                                useIsaSpecificSubdirs);
7878                    } else {
7879                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7880                    }
7881                }
7882
7883                maybeThrowExceptionForMultiArchCopy(
7884                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7885
7886                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7887                    if (extractLibs) {
7888                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7889                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7890                                useIsaSpecificSubdirs);
7891                    } else {
7892                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7893                    }
7894                }
7895
7896                maybeThrowExceptionForMultiArchCopy(
7897                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7898
7899                if (abi64 >= 0) {
7900                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7901                }
7902
7903                if (abi32 >= 0) {
7904                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7905                    if (abi64 >= 0) {
7906                        pkg.applicationInfo.secondaryCpuAbi = abi;
7907                    } else {
7908                        pkg.applicationInfo.primaryCpuAbi = abi;
7909                    }
7910                }
7911            } else {
7912                String[] abiList = (cpuAbiOverride != null) ?
7913                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7914
7915                // Enable gross and lame hacks for apps that are built with old
7916                // SDK tools. We must scan their APKs for renderscript bitcode and
7917                // not launch them if it's present. Don't bother checking on devices
7918                // that don't have 64 bit support.
7919                boolean needsRenderScriptOverride = false;
7920                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7921                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7922                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7923                    needsRenderScriptOverride = true;
7924                }
7925
7926                final int copyRet;
7927                if (extractLibs) {
7928                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7929                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7930                } else {
7931                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7932                }
7933
7934                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7935                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7936                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7937                }
7938
7939                if (copyRet >= 0) {
7940                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7941                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7942                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7943                } else if (needsRenderScriptOverride) {
7944                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7945                }
7946            }
7947        } catch (IOException ioe) {
7948            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7949        } finally {
7950            IoUtils.closeQuietly(handle);
7951        }
7952
7953        // Now that we've calculated the ABIs and determined if it's an internal app,
7954        // we will go ahead and populate the nativeLibraryPath.
7955        setNativeLibraryPaths(pkg);
7956    }
7957
7958    /**
7959     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7960     * i.e, so that all packages can be run inside a single process if required.
7961     *
7962     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7963     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7964     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7965     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7966     * updating a package that belongs to a shared user.
7967     *
7968     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7969     * adds unnecessary complexity.
7970     */
7971    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7972            PackageParser.Package scannedPackage, boolean bootComplete) {
7973        String requiredInstructionSet = null;
7974        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7975            requiredInstructionSet = VMRuntime.getInstructionSet(
7976                     scannedPackage.applicationInfo.primaryCpuAbi);
7977        }
7978
7979        PackageSetting requirer = null;
7980        for (PackageSetting ps : packagesForUser) {
7981            // If packagesForUser contains scannedPackage, we skip it. This will happen
7982            // when scannedPackage is an update of an existing package. Without this check,
7983            // we will never be able to change the ABI of any package belonging to a shared
7984            // user, even if it's compatible with other packages.
7985            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7986                if (ps.primaryCpuAbiString == null) {
7987                    continue;
7988                }
7989
7990                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7991                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7992                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7993                    // this but there's not much we can do.
7994                    String errorMessage = "Instruction set mismatch, "
7995                            + ((requirer == null) ? "[caller]" : requirer)
7996                            + " requires " + requiredInstructionSet + " whereas " + ps
7997                            + " requires " + instructionSet;
7998                    Slog.w(TAG, errorMessage);
7999                }
8000
8001                if (requiredInstructionSet == null) {
8002                    requiredInstructionSet = instructionSet;
8003                    requirer = ps;
8004                }
8005            }
8006        }
8007
8008        if (requiredInstructionSet != null) {
8009            String adjustedAbi;
8010            if (requirer != null) {
8011                // requirer != null implies that either scannedPackage was null or that scannedPackage
8012                // did not require an ABI, in which case we have to adjust scannedPackage to match
8013                // the ABI of the set (which is the same as requirer's ABI)
8014                adjustedAbi = requirer.primaryCpuAbiString;
8015                if (scannedPackage != null) {
8016                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8017                }
8018            } else {
8019                // requirer == null implies that we're updating all ABIs in the set to
8020                // match scannedPackage.
8021                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8022            }
8023
8024            for (PackageSetting ps : packagesForUser) {
8025                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8026                    if (ps.primaryCpuAbiString != null) {
8027                        continue;
8028                    }
8029
8030                    ps.primaryCpuAbiString = adjustedAbi;
8031                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8032                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8033                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8034                        mInstaller.rmdex(ps.codePathString,
8035                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8036                    }
8037                }
8038            }
8039        }
8040    }
8041
8042    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8043        synchronized (mPackages) {
8044            mResolverReplaced = true;
8045            // Set up information for custom user intent resolution activity.
8046            mResolveActivity.applicationInfo = pkg.applicationInfo;
8047            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8048            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8049            mResolveActivity.processName = pkg.applicationInfo.packageName;
8050            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8051            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8052                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8053            mResolveActivity.theme = 0;
8054            mResolveActivity.exported = true;
8055            mResolveActivity.enabled = true;
8056            mResolveInfo.activityInfo = mResolveActivity;
8057            mResolveInfo.priority = 0;
8058            mResolveInfo.preferredOrder = 0;
8059            mResolveInfo.match = 0;
8060            mResolveComponentName = mCustomResolverComponentName;
8061            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8062                    mResolveComponentName);
8063        }
8064    }
8065
8066    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8067        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8068
8069        // Set up information for ephemeral installer activity
8070        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8071        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8072        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8073        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8074        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8075        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8076                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8077        mEphemeralInstallerActivity.theme = 0;
8078        mEphemeralInstallerActivity.exported = true;
8079        mEphemeralInstallerActivity.enabled = true;
8080        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8081        mEphemeralInstallerInfo.priority = 0;
8082        mEphemeralInstallerInfo.preferredOrder = 0;
8083        mEphemeralInstallerInfo.match = 0;
8084
8085        if (DEBUG_EPHEMERAL) {
8086            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8087        }
8088    }
8089
8090    private static String calculateBundledApkRoot(final String codePathString) {
8091        final File codePath = new File(codePathString);
8092        final File codeRoot;
8093        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8094            codeRoot = Environment.getRootDirectory();
8095        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8096            codeRoot = Environment.getOemDirectory();
8097        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8098            codeRoot = Environment.getVendorDirectory();
8099        } else {
8100            // Unrecognized code path; take its top real segment as the apk root:
8101            // e.g. /something/app/blah.apk => /something
8102            try {
8103                File f = codePath.getCanonicalFile();
8104                File parent = f.getParentFile();    // non-null because codePath is a file
8105                File tmp;
8106                while ((tmp = parent.getParentFile()) != null) {
8107                    f = parent;
8108                    parent = tmp;
8109                }
8110                codeRoot = f;
8111                Slog.w(TAG, "Unrecognized code path "
8112                        + codePath + " - using " + codeRoot);
8113            } catch (IOException e) {
8114                // Can't canonicalize the code path -- shenanigans?
8115                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8116                return Environment.getRootDirectory().getPath();
8117            }
8118        }
8119        return codeRoot.getPath();
8120    }
8121
8122    /**
8123     * Derive and set the location of native libraries for the given package,
8124     * which varies depending on where and how the package was installed.
8125     */
8126    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8127        final ApplicationInfo info = pkg.applicationInfo;
8128        final String codePath = pkg.codePath;
8129        final File codeFile = new File(codePath);
8130        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8131        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8132
8133        info.nativeLibraryRootDir = null;
8134        info.nativeLibraryRootRequiresIsa = false;
8135        info.nativeLibraryDir = null;
8136        info.secondaryNativeLibraryDir = null;
8137
8138        if (isApkFile(codeFile)) {
8139            // Monolithic install
8140            if (bundledApp) {
8141                // If "/system/lib64/apkname" exists, assume that is the per-package
8142                // native library directory to use; otherwise use "/system/lib/apkname".
8143                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8144                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8145                        getPrimaryInstructionSet(info));
8146
8147                // This is a bundled system app so choose the path based on the ABI.
8148                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8149                // is just the default path.
8150                final String apkName = deriveCodePathName(codePath);
8151                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8152                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8153                        apkName).getAbsolutePath();
8154
8155                if (info.secondaryCpuAbi != null) {
8156                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8157                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8158                            secondaryLibDir, apkName).getAbsolutePath();
8159                }
8160            } else if (asecApp) {
8161                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8162                        .getAbsolutePath();
8163            } else {
8164                final String apkName = deriveCodePathName(codePath);
8165                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8166                        .getAbsolutePath();
8167            }
8168
8169            info.nativeLibraryRootRequiresIsa = false;
8170            info.nativeLibraryDir = info.nativeLibraryRootDir;
8171        } else {
8172            // Cluster install
8173            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8174            info.nativeLibraryRootRequiresIsa = true;
8175
8176            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8177                    getPrimaryInstructionSet(info)).getAbsolutePath();
8178
8179            if (info.secondaryCpuAbi != null) {
8180                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8181                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8182            }
8183        }
8184    }
8185
8186    /**
8187     * Calculate the abis and roots for a bundled app. These can uniquely
8188     * be determined from the contents of the system partition, i.e whether
8189     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8190     * of this information, and instead assume that the system was built
8191     * sensibly.
8192     */
8193    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8194                                           PackageSetting pkgSetting) {
8195        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8196
8197        // If "/system/lib64/apkname" exists, assume that is the per-package
8198        // native library directory to use; otherwise use "/system/lib/apkname".
8199        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8200        setBundledAppAbi(pkg, apkRoot, apkName);
8201        // pkgSetting might be null during rescan following uninstall of updates
8202        // to a bundled app, so accommodate that possibility.  The settings in
8203        // that case will be established later from the parsed package.
8204        //
8205        // If the settings aren't null, sync them up with what we've just derived.
8206        // note that apkRoot isn't stored in the package settings.
8207        if (pkgSetting != null) {
8208            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8209            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8210        }
8211    }
8212
8213    /**
8214     * Deduces the ABI of a bundled app and sets the relevant fields on the
8215     * parsed pkg object.
8216     *
8217     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8218     *        under which system libraries are installed.
8219     * @param apkName the name of the installed package.
8220     */
8221    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8222        final File codeFile = new File(pkg.codePath);
8223
8224        final boolean has64BitLibs;
8225        final boolean has32BitLibs;
8226        if (isApkFile(codeFile)) {
8227            // Monolithic install
8228            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8229            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8230        } else {
8231            // Cluster install
8232            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8233            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8234                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8235                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8236                has64BitLibs = (new File(rootDir, isa)).exists();
8237            } else {
8238                has64BitLibs = false;
8239            }
8240            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8241                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8242                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8243                has32BitLibs = (new File(rootDir, isa)).exists();
8244            } else {
8245                has32BitLibs = false;
8246            }
8247        }
8248
8249        if (has64BitLibs && !has32BitLibs) {
8250            // The package has 64 bit libs, but not 32 bit libs. Its primary
8251            // ABI should be 64 bit. We can safely assume here that the bundled
8252            // native libraries correspond to the most preferred ABI in the list.
8253
8254            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8255            pkg.applicationInfo.secondaryCpuAbi = null;
8256        } else if (has32BitLibs && !has64BitLibs) {
8257            // The package has 32 bit libs but not 64 bit libs. Its primary
8258            // ABI should be 32 bit.
8259
8260            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8261            pkg.applicationInfo.secondaryCpuAbi = null;
8262        } else if (has32BitLibs && has64BitLibs) {
8263            // The application has both 64 and 32 bit bundled libraries. We check
8264            // here that the app declares multiArch support, and warn if it doesn't.
8265            //
8266            // We will be lenient here and record both ABIs. The primary will be the
8267            // ABI that's higher on the list, i.e, a device that's configured to prefer
8268            // 64 bit apps will see a 64 bit primary ABI,
8269
8270            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8271                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8272            }
8273
8274            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8275                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8276                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8277            } else {
8278                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8279                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8280            }
8281        } else {
8282            pkg.applicationInfo.primaryCpuAbi = null;
8283            pkg.applicationInfo.secondaryCpuAbi = null;
8284        }
8285    }
8286
8287    private void killApplication(String pkgName, int appId, String reason) {
8288        // Request the ActivityManager to kill the process(only for existing packages)
8289        // so that we do not end up in a confused state while the user is still using the older
8290        // version of the application while the new one gets installed.
8291        IActivityManager am = ActivityManagerNative.getDefault();
8292        if (am != null) {
8293            try {
8294                am.killApplicationWithAppId(pkgName, appId, reason);
8295            } catch (RemoteException e) {
8296            }
8297        }
8298    }
8299
8300    void removePackageLI(PackageSetting ps, boolean chatty) {
8301        if (DEBUG_INSTALL) {
8302            if (chatty)
8303                Log.d(TAG, "Removing package " + ps.name);
8304        }
8305
8306        // writer
8307        synchronized (mPackages) {
8308            mPackages.remove(ps.name);
8309            final PackageParser.Package pkg = ps.pkg;
8310            if (pkg != null) {
8311                cleanPackageDataStructuresLILPw(pkg, chatty);
8312            }
8313        }
8314    }
8315
8316    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8317        if (DEBUG_INSTALL) {
8318            if (chatty)
8319                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8320        }
8321
8322        // writer
8323        synchronized (mPackages) {
8324            mPackages.remove(pkg.applicationInfo.packageName);
8325            cleanPackageDataStructuresLILPw(pkg, chatty);
8326        }
8327    }
8328
8329    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8330        int N = pkg.providers.size();
8331        StringBuilder r = null;
8332        int i;
8333        for (i=0; i<N; i++) {
8334            PackageParser.Provider p = pkg.providers.get(i);
8335            mProviders.removeProvider(p);
8336            if (p.info.authority == null) {
8337
8338                /* There was another ContentProvider with this authority when
8339                 * this app was installed so this authority is null,
8340                 * Ignore it as we don't have to unregister the provider.
8341                 */
8342                continue;
8343            }
8344            String names[] = p.info.authority.split(";");
8345            for (int j = 0; j < names.length; j++) {
8346                if (mProvidersByAuthority.get(names[j]) == p) {
8347                    mProvidersByAuthority.remove(names[j]);
8348                    if (DEBUG_REMOVE) {
8349                        if (chatty)
8350                            Log.d(TAG, "Unregistered content provider: " + names[j]
8351                                    + ", className = " + p.info.name + ", isSyncable = "
8352                                    + p.info.isSyncable);
8353                    }
8354                }
8355            }
8356            if (DEBUG_REMOVE && chatty) {
8357                if (r == null) {
8358                    r = new StringBuilder(256);
8359                } else {
8360                    r.append(' ');
8361                }
8362                r.append(p.info.name);
8363            }
8364        }
8365        if (r != null) {
8366            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8367        }
8368
8369        N = pkg.services.size();
8370        r = null;
8371        for (i=0; i<N; i++) {
8372            PackageParser.Service s = pkg.services.get(i);
8373            mServices.removeService(s);
8374            if (chatty) {
8375                if (r == null) {
8376                    r = new StringBuilder(256);
8377                } else {
8378                    r.append(' ');
8379                }
8380                r.append(s.info.name);
8381            }
8382        }
8383        if (r != null) {
8384            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8385        }
8386
8387        N = pkg.receivers.size();
8388        r = null;
8389        for (i=0; i<N; i++) {
8390            PackageParser.Activity a = pkg.receivers.get(i);
8391            mReceivers.removeActivity(a, "receiver");
8392            if (DEBUG_REMOVE && chatty) {
8393                if (r == null) {
8394                    r = new StringBuilder(256);
8395                } else {
8396                    r.append(' ');
8397                }
8398                r.append(a.info.name);
8399            }
8400        }
8401        if (r != null) {
8402            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8403        }
8404
8405        N = pkg.activities.size();
8406        r = null;
8407        for (i=0; i<N; i++) {
8408            PackageParser.Activity a = pkg.activities.get(i);
8409            mActivities.removeActivity(a, "activity");
8410            if (DEBUG_REMOVE && chatty) {
8411                if (r == null) {
8412                    r = new StringBuilder(256);
8413                } else {
8414                    r.append(' ');
8415                }
8416                r.append(a.info.name);
8417            }
8418        }
8419        if (r != null) {
8420            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8421        }
8422
8423        N = pkg.permissions.size();
8424        r = null;
8425        for (i=0; i<N; i++) {
8426            PackageParser.Permission p = pkg.permissions.get(i);
8427            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8428            if (bp == null) {
8429                bp = mSettings.mPermissionTrees.get(p.info.name);
8430            }
8431            if (bp != null && bp.perm == p) {
8432                bp.perm = null;
8433                if (DEBUG_REMOVE && chatty) {
8434                    if (r == null) {
8435                        r = new StringBuilder(256);
8436                    } else {
8437                        r.append(' ');
8438                    }
8439                    r.append(p.info.name);
8440                }
8441            }
8442            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8443                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8444                if (appOpPkgs != null) {
8445                    appOpPkgs.remove(pkg.packageName);
8446                }
8447            }
8448        }
8449        if (r != null) {
8450            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8451        }
8452
8453        N = pkg.requestedPermissions.size();
8454        r = null;
8455        for (i=0; i<N; i++) {
8456            String perm = pkg.requestedPermissions.get(i);
8457            BasePermission bp = mSettings.mPermissions.get(perm);
8458            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8459                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8460                if (appOpPkgs != null) {
8461                    appOpPkgs.remove(pkg.packageName);
8462                    if (appOpPkgs.isEmpty()) {
8463                        mAppOpPermissionPackages.remove(perm);
8464                    }
8465                }
8466            }
8467        }
8468        if (r != null) {
8469            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8470        }
8471
8472        N = pkg.instrumentation.size();
8473        r = null;
8474        for (i=0; i<N; i++) {
8475            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8476            mInstrumentation.remove(a.getComponentName());
8477            if (DEBUG_REMOVE && chatty) {
8478                if (r == null) {
8479                    r = new StringBuilder(256);
8480                } else {
8481                    r.append(' ');
8482                }
8483                r.append(a.info.name);
8484            }
8485        }
8486        if (r != null) {
8487            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8488        }
8489
8490        r = null;
8491        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8492            // Only system apps can hold shared libraries.
8493            if (pkg.libraryNames != null) {
8494                for (i=0; i<pkg.libraryNames.size(); i++) {
8495                    String name = pkg.libraryNames.get(i);
8496                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8497                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8498                        mSharedLibraries.remove(name);
8499                        if (DEBUG_REMOVE && chatty) {
8500                            if (r == null) {
8501                                r = new StringBuilder(256);
8502                            } else {
8503                                r.append(' ');
8504                            }
8505                            r.append(name);
8506                        }
8507                    }
8508                }
8509            }
8510        }
8511        if (r != null) {
8512            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8513        }
8514    }
8515
8516    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8517        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8518            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8519                return true;
8520            }
8521        }
8522        return false;
8523    }
8524
8525    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8526    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8527    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8528
8529    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8530            int flags) {
8531        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8532        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8533    }
8534
8535    private void updatePermissionsLPw(String changingPkg,
8536            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8537        // Make sure there are no dangling permission trees.
8538        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8539        while (it.hasNext()) {
8540            final BasePermission bp = it.next();
8541            if (bp.packageSetting == null) {
8542                // We may not yet have parsed the package, so just see if
8543                // we still know about its settings.
8544                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8545            }
8546            if (bp.packageSetting == null) {
8547                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8548                        + " from package " + bp.sourcePackage);
8549                it.remove();
8550            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8551                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8552                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8553                            + " from package " + bp.sourcePackage);
8554                    flags |= UPDATE_PERMISSIONS_ALL;
8555                    it.remove();
8556                }
8557            }
8558        }
8559
8560        // Make sure all dynamic permissions have been assigned to a package,
8561        // and make sure there are no dangling permissions.
8562        it = mSettings.mPermissions.values().iterator();
8563        while (it.hasNext()) {
8564            final BasePermission bp = it.next();
8565            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8566                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8567                        + bp.name + " pkg=" + bp.sourcePackage
8568                        + " info=" + bp.pendingInfo);
8569                if (bp.packageSetting == null && bp.pendingInfo != null) {
8570                    final BasePermission tree = findPermissionTreeLP(bp.name);
8571                    if (tree != null && tree.perm != null) {
8572                        bp.packageSetting = tree.packageSetting;
8573                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8574                                new PermissionInfo(bp.pendingInfo));
8575                        bp.perm.info.packageName = tree.perm.info.packageName;
8576                        bp.perm.info.name = bp.name;
8577                        bp.uid = tree.uid;
8578                    }
8579                }
8580            }
8581            if (bp.packageSetting == null) {
8582                // We may not yet have parsed the package, so just see if
8583                // we still know about its settings.
8584                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8585            }
8586            if (bp.packageSetting == null) {
8587                Slog.w(TAG, "Removing dangling permission: " + bp.name
8588                        + " from package " + bp.sourcePackage);
8589                it.remove();
8590            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8591                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8592                    Slog.i(TAG, "Removing old permission: " + bp.name
8593                            + " from package " + bp.sourcePackage);
8594                    flags |= UPDATE_PERMISSIONS_ALL;
8595                    it.remove();
8596                }
8597            }
8598        }
8599
8600        // Now update the permissions for all packages, in particular
8601        // replace the granted permissions of the system packages.
8602        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8603            for (PackageParser.Package pkg : mPackages.values()) {
8604                if (pkg != pkgInfo) {
8605                    // Only replace for packages on requested volume
8606                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8607                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8608                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8609                    grantPermissionsLPw(pkg, replace, changingPkg);
8610                }
8611            }
8612        }
8613
8614        if (pkgInfo != null) {
8615            // Only replace for packages on requested volume
8616            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8617            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8618                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8619            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8620        }
8621    }
8622
8623    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8624            String packageOfInterest) {
8625        // IMPORTANT: There are two types of permissions: install and runtime.
8626        // Install time permissions are granted when the app is installed to
8627        // all device users and users added in the future. Runtime permissions
8628        // are granted at runtime explicitly to specific users. Normal and signature
8629        // protected permissions are install time permissions. Dangerous permissions
8630        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8631        // otherwise they are runtime permissions. This function does not manage
8632        // runtime permissions except for the case an app targeting Lollipop MR1
8633        // being upgraded to target a newer SDK, in which case dangerous permissions
8634        // are transformed from install time to runtime ones.
8635
8636        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8637        if (ps == null) {
8638            return;
8639        }
8640
8641        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8642
8643        PermissionsState permissionsState = ps.getPermissionsState();
8644        PermissionsState origPermissions = permissionsState;
8645
8646        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8647
8648        boolean runtimePermissionsRevoked = false;
8649        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8650
8651        boolean changedInstallPermission = false;
8652
8653        if (replace) {
8654            ps.installPermissionsFixed = false;
8655            if (!ps.isSharedUser()) {
8656                origPermissions = new PermissionsState(permissionsState);
8657                permissionsState.reset();
8658            } else {
8659                // We need to know only about runtime permission changes since the
8660                // calling code always writes the install permissions state but
8661                // the runtime ones are written only if changed. The only cases of
8662                // changed runtime permissions here are promotion of an install to
8663                // runtime and revocation of a runtime from a shared user.
8664                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8665                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8666                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8667                    runtimePermissionsRevoked = true;
8668                }
8669            }
8670        }
8671
8672        permissionsState.setGlobalGids(mGlobalGids);
8673
8674        final int N = pkg.requestedPermissions.size();
8675        for (int i=0; i<N; i++) {
8676            final String name = pkg.requestedPermissions.get(i);
8677            final BasePermission bp = mSettings.mPermissions.get(name);
8678
8679            if (DEBUG_INSTALL) {
8680                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8681            }
8682
8683            if (bp == null || bp.packageSetting == null) {
8684                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8685                    Slog.w(TAG, "Unknown permission " + name
8686                            + " in package " + pkg.packageName);
8687                }
8688                continue;
8689            }
8690
8691            final String perm = bp.name;
8692            boolean allowedSig = false;
8693            int grant = GRANT_DENIED;
8694
8695            // Keep track of app op permissions.
8696            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8697                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8698                if (pkgs == null) {
8699                    pkgs = new ArraySet<>();
8700                    mAppOpPermissionPackages.put(bp.name, pkgs);
8701                }
8702                pkgs.add(pkg.packageName);
8703            }
8704
8705            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8706            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8707                    >= Build.VERSION_CODES.M;
8708            switch (level) {
8709                case PermissionInfo.PROTECTION_NORMAL: {
8710                    // For all apps normal permissions are install time ones.
8711                    grant = GRANT_INSTALL;
8712                } break;
8713
8714                case PermissionInfo.PROTECTION_DANGEROUS: {
8715                    // If a permission review is required for legacy apps we represent
8716                    // their permissions as always granted runtime ones since we need
8717                    // to keep the review required permission flag per user while an
8718                    // install permission's state is shared across all users.
8719                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8720                        // For legacy apps dangerous permissions are install time ones.
8721                        grant = GRANT_INSTALL;
8722                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8723                        // For legacy apps that became modern, install becomes runtime.
8724                        grant = GRANT_UPGRADE;
8725                    } else if (mPromoteSystemApps
8726                            && isSystemApp(ps)
8727                            && mExistingSystemPackages.contains(ps.name)) {
8728                        // For legacy system apps, install becomes runtime.
8729                        // We cannot check hasInstallPermission() for system apps since those
8730                        // permissions were granted implicitly and not persisted pre-M.
8731                        grant = GRANT_UPGRADE;
8732                    } else {
8733                        // For modern apps keep runtime permissions unchanged.
8734                        grant = GRANT_RUNTIME;
8735                    }
8736                } break;
8737
8738                case PermissionInfo.PROTECTION_SIGNATURE: {
8739                    // For all apps signature permissions are install time ones.
8740                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8741                    if (allowedSig) {
8742                        grant = GRANT_INSTALL;
8743                    }
8744                } break;
8745            }
8746
8747            if (DEBUG_INSTALL) {
8748                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8749            }
8750
8751            if (grant != GRANT_DENIED) {
8752                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8753                    // If this is an existing, non-system package, then
8754                    // we can't add any new permissions to it.
8755                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8756                        // Except...  if this is a permission that was added
8757                        // to the platform (note: need to only do this when
8758                        // updating the platform).
8759                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8760                            grant = GRANT_DENIED;
8761                        }
8762                    }
8763                }
8764
8765                switch (grant) {
8766                    case GRANT_INSTALL: {
8767                        // Revoke this as runtime permission to handle the case of
8768                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8769                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8770                            if (origPermissions.getRuntimePermissionState(
8771                                    bp.name, userId) != null) {
8772                                // Revoke the runtime permission and clear the flags.
8773                                origPermissions.revokeRuntimePermission(bp, userId);
8774                                origPermissions.updatePermissionFlags(bp, userId,
8775                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8776                                // If we revoked a permission permission, we have to write.
8777                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8778                                        changedRuntimePermissionUserIds, userId);
8779                            }
8780                        }
8781                        // Grant an install permission.
8782                        if (permissionsState.grantInstallPermission(bp) !=
8783                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8784                            changedInstallPermission = true;
8785                        }
8786                    } break;
8787
8788                    case GRANT_RUNTIME: {
8789                        // Grant previously granted runtime permissions.
8790                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8791                            PermissionState permissionState = origPermissions
8792                                    .getRuntimePermissionState(bp.name, userId);
8793                            int flags = permissionState != null
8794                                    ? permissionState.getFlags() : 0;
8795                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8796                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8797                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8798                                    // If we cannot put the permission as it was, we have to write.
8799                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8800                                            changedRuntimePermissionUserIds, userId);
8801                                }
8802                                // If the app supports runtime permissions no need for a review.
8803                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8804                                        && appSupportsRuntimePermissions
8805                                        && (flags & PackageManager
8806                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8807                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8808                                    // Since we changed the flags, we have to write.
8809                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8810                                            changedRuntimePermissionUserIds, userId);
8811                                }
8812                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8813                                    && !appSupportsRuntimePermissions) {
8814                                // For legacy apps that need a permission review, every new
8815                                // runtime permission is granted but it is pending a review.
8816                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8817                                    permissionsState.grantRuntimePermission(bp, userId);
8818                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8819                                    // We changed the permission and flags, hence have to write.
8820                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8821                                            changedRuntimePermissionUserIds, userId);
8822                                }
8823                            }
8824                            // Propagate the permission flags.
8825                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8826                        }
8827                    } break;
8828
8829                    case GRANT_UPGRADE: {
8830                        // Grant runtime permissions for a previously held install permission.
8831                        PermissionState permissionState = origPermissions
8832                                .getInstallPermissionState(bp.name);
8833                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8834
8835                        if (origPermissions.revokeInstallPermission(bp)
8836                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8837                            // We will be transferring the permission flags, so clear them.
8838                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8839                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8840                            changedInstallPermission = true;
8841                        }
8842
8843                        // If the permission is not to be promoted to runtime we ignore it and
8844                        // also its other flags as they are not applicable to install permissions.
8845                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8846                            for (int userId : currentUserIds) {
8847                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8848                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8849                                    // Transfer the permission flags.
8850                                    permissionsState.updatePermissionFlags(bp, userId,
8851                                            flags, flags);
8852                                    // If we granted the permission, we have to write.
8853                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8854                                            changedRuntimePermissionUserIds, userId);
8855                                }
8856                            }
8857                        }
8858                    } break;
8859
8860                    default: {
8861                        if (packageOfInterest == null
8862                                || packageOfInterest.equals(pkg.packageName)) {
8863                            Slog.w(TAG, "Not granting permission " + perm
8864                                    + " to package " + pkg.packageName
8865                                    + " because it was previously installed without");
8866                        }
8867                    } break;
8868                }
8869            } else {
8870                if (permissionsState.revokeInstallPermission(bp) !=
8871                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8872                    // Also drop the permission flags.
8873                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8874                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8875                    changedInstallPermission = true;
8876                    Slog.i(TAG, "Un-granting permission " + perm
8877                            + " from package " + pkg.packageName
8878                            + " (protectionLevel=" + bp.protectionLevel
8879                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8880                            + ")");
8881                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8882                    // Don't print warning for app op permissions, since it is fine for them
8883                    // not to be granted, there is a UI for the user to decide.
8884                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8885                        Slog.w(TAG, "Not granting permission " + perm
8886                                + " to package " + pkg.packageName
8887                                + " (protectionLevel=" + bp.protectionLevel
8888                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8889                                + ")");
8890                    }
8891                }
8892            }
8893        }
8894
8895        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8896                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8897            // This is the first that we have heard about this package, so the
8898            // permissions we have now selected are fixed until explicitly
8899            // changed.
8900            ps.installPermissionsFixed = true;
8901        }
8902
8903        // Persist the runtime permissions state for users with changes. If permissions
8904        // were revoked because no app in the shared user declares them we have to
8905        // write synchronously to avoid losing runtime permissions state.
8906        for (int userId : changedRuntimePermissionUserIds) {
8907            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8908        }
8909
8910        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8911    }
8912
8913    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8914        boolean allowed = false;
8915        final int NP = PackageParser.NEW_PERMISSIONS.length;
8916        for (int ip=0; ip<NP; ip++) {
8917            final PackageParser.NewPermissionInfo npi
8918                    = PackageParser.NEW_PERMISSIONS[ip];
8919            if (npi.name.equals(perm)
8920                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8921                allowed = true;
8922                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8923                        + pkg.packageName);
8924                break;
8925            }
8926        }
8927        return allowed;
8928    }
8929
8930    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8931            BasePermission bp, PermissionsState origPermissions) {
8932        boolean allowed;
8933        allowed = (compareSignatures(
8934                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8935                        == PackageManager.SIGNATURE_MATCH)
8936                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8937                        == PackageManager.SIGNATURE_MATCH);
8938        if (!allowed && (bp.protectionLevel
8939                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8940            if (isSystemApp(pkg)) {
8941                // For updated system applications, a system permission
8942                // is granted only if it had been defined by the original application.
8943                if (pkg.isUpdatedSystemApp()) {
8944                    final PackageSetting sysPs = mSettings
8945                            .getDisabledSystemPkgLPr(pkg.packageName);
8946                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8947                        // If the original was granted this permission, we take
8948                        // that grant decision as read and propagate it to the
8949                        // update.
8950                        if (sysPs.isPrivileged()) {
8951                            allowed = true;
8952                        }
8953                    } else {
8954                        // The system apk may have been updated with an older
8955                        // version of the one on the data partition, but which
8956                        // granted a new system permission that it didn't have
8957                        // before.  In this case we do want to allow the app to
8958                        // now get the new permission if the ancestral apk is
8959                        // privileged to get it.
8960                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8961                            for (int j=0;
8962                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8963                                if (perm.equals(
8964                                        sysPs.pkg.requestedPermissions.get(j))) {
8965                                    allowed = true;
8966                                    break;
8967                                }
8968                            }
8969                        }
8970                    }
8971                } else {
8972                    allowed = isPrivilegedApp(pkg);
8973                }
8974            }
8975        }
8976        if (!allowed) {
8977            if (!allowed && (bp.protectionLevel
8978                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8979                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8980                // If this was a previously normal/dangerous permission that got moved
8981                // to a system permission as part of the runtime permission redesign, then
8982                // we still want to blindly grant it to old apps.
8983                allowed = true;
8984            }
8985            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8986                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8987                // If this permission is to be granted to the system installer and
8988                // this app is an installer, then it gets the permission.
8989                allowed = true;
8990            }
8991            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8992                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8993                // If this permission is to be granted to the system verifier and
8994                // this app is a verifier, then it gets the permission.
8995                allowed = true;
8996            }
8997            if (!allowed && (bp.protectionLevel
8998                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8999                    && isSystemApp(pkg)) {
9000                // Any pre-installed system app is allowed to get this permission.
9001                allowed = true;
9002            }
9003            if (!allowed && (bp.protectionLevel
9004                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9005                // For development permissions, a development permission
9006                // is granted only if it was already granted.
9007                allowed = origPermissions.hasInstallPermission(perm);
9008            }
9009        }
9010        return allowed;
9011    }
9012
9013    final class ActivityIntentResolver
9014            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9015        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9016                boolean defaultOnly, int userId) {
9017            if (!sUserManager.exists(userId)) return null;
9018            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9019            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9020        }
9021
9022        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9023                int userId) {
9024            if (!sUserManager.exists(userId)) return null;
9025            mFlags = flags;
9026            return super.queryIntent(intent, resolvedType,
9027                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9028        }
9029
9030        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9031                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9032            if (!sUserManager.exists(userId)) return null;
9033            if (packageActivities == null) {
9034                return null;
9035            }
9036            mFlags = flags;
9037            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9038            final int N = packageActivities.size();
9039            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9040                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9041
9042            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9043            for (int i = 0; i < N; ++i) {
9044                intentFilters = packageActivities.get(i).intents;
9045                if (intentFilters != null && intentFilters.size() > 0) {
9046                    PackageParser.ActivityIntentInfo[] array =
9047                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9048                    intentFilters.toArray(array);
9049                    listCut.add(array);
9050                }
9051            }
9052            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9053        }
9054
9055        public final void addActivity(PackageParser.Activity a, String type) {
9056            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9057            mActivities.put(a.getComponentName(), a);
9058            if (DEBUG_SHOW_INFO)
9059                Log.v(
9060                TAG, "  " + type + " " +
9061                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9062            if (DEBUG_SHOW_INFO)
9063                Log.v(TAG, "    Class=" + a.info.name);
9064            final int NI = a.intents.size();
9065            for (int j=0; j<NI; j++) {
9066                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9067                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9068                    intent.setPriority(0);
9069                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9070                            + a.className + " with priority > 0, forcing to 0");
9071                }
9072                if (DEBUG_SHOW_INFO) {
9073                    Log.v(TAG, "    IntentFilter:");
9074                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9075                }
9076                if (!intent.debugCheck()) {
9077                    Log.w(TAG, "==> For Activity " + a.info.name);
9078                }
9079                addFilter(intent);
9080            }
9081        }
9082
9083        public final void removeActivity(PackageParser.Activity a, String type) {
9084            mActivities.remove(a.getComponentName());
9085            if (DEBUG_SHOW_INFO) {
9086                Log.v(TAG, "  " + type + " "
9087                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9088                                : a.info.name) + ":");
9089                Log.v(TAG, "    Class=" + a.info.name);
9090            }
9091            final int NI = a.intents.size();
9092            for (int j=0; j<NI; j++) {
9093                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9094                if (DEBUG_SHOW_INFO) {
9095                    Log.v(TAG, "    IntentFilter:");
9096                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9097                }
9098                removeFilter(intent);
9099            }
9100        }
9101
9102        @Override
9103        protected boolean allowFilterResult(
9104                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9105            ActivityInfo filterAi = filter.activity.info;
9106            for (int i=dest.size()-1; i>=0; i--) {
9107                ActivityInfo destAi = dest.get(i).activityInfo;
9108                if (destAi.name == filterAi.name
9109                        && destAi.packageName == filterAi.packageName) {
9110                    return false;
9111                }
9112            }
9113            return true;
9114        }
9115
9116        @Override
9117        protected ActivityIntentInfo[] newArray(int size) {
9118            return new ActivityIntentInfo[size];
9119        }
9120
9121        @Override
9122        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9123            if (!sUserManager.exists(userId)) return true;
9124            PackageParser.Package p = filter.activity.owner;
9125            if (p != null) {
9126                PackageSetting ps = (PackageSetting)p.mExtras;
9127                if (ps != null) {
9128                    // System apps are never considered stopped for purposes of
9129                    // filtering, because there may be no way for the user to
9130                    // actually re-launch them.
9131                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9132                            && ps.getStopped(userId);
9133                }
9134            }
9135            return false;
9136        }
9137
9138        @Override
9139        protected boolean isPackageForFilter(String packageName,
9140                PackageParser.ActivityIntentInfo info) {
9141            return packageName.equals(info.activity.owner.packageName);
9142        }
9143
9144        @Override
9145        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9146                int match, int userId) {
9147            if (!sUserManager.exists(userId)) return null;
9148            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9149                return null;
9150            }
9151            final PackageParser.Activity activity = info.activity;
9152            if (mSafeMode && (activity.info.applicationInfo.flags
9153                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9154                return null;
9155            }
9156            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9157            if (ps == null) {
9158                return null;
9159            }
9160            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9161                    ps.readUserState(userId), userId);
9162            if (ai == null) {
9163                return null;
9164            }
9165            final ResolveInfo res = new ResolveInfo();
9166            res.activityInfo = ai;
9167            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9168                res.filter = info;
9169            }
9170            if (info != null) {
9171                res.handleAllWebDataURI = info.handleAllWebDataURI();
9172            }
9173            res.priority = info.getPriority();
9174            res.preferredOrder = activity.owner.mPreferredOrder;
9175            //System.out.println("Result: " + res.activityInfo.className +
9176            //                   " = " + res.priority);
9177            res.match = match;
9178            res.isDefault = info.hasDefault;
9179            res.labelRes = info.labelRes;
9180            res.nonLocalizedLabel = info.nonLocalizedLabel;
9181            if (userNeedsBadging(userId)) {
9182                res.noResourceId = true;
9183            } else {
9184                res.icon = info.icon;
9185            }
9186            res.iconResourceId = info.icon;
9187            res.system = res.activityInfo.applicationInfo.isSystemApp();
9188            return res;
9189        }
9190
9191        @Override
9192        protected void sortResults(List<ResolveInfo> results) {
9193            Collections.sort(results, mResolvePrioritySorter);
9194        }
9195
9196        @Override
9197        protected void dumpFilter(PrintWriter out, String prefix,
9198                PackageParser.ActivityIntentInfo filter) {
9199            out.print(prefix); out.print(
9200                    Integer.toHexString(System.identityHashCode(filter.activity)));
9201                    out.print(' ');
9202                    filter.activity.printComponentShortName(out);
9203                    out.print(" filter ");
9204                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9205        }
9206
9207        @Override
9208        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9209            return filter.activity;
9210        }
9211
9212        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9213            PackageParser.Activity activity = (PackageParser.Activity)label;
9214            out.print(prefix); out.print(
9215                    Integer.toHexString(System.identityHashCode(activity)));
9216                    out.print(' ');
9217                    activity.printComponentShortName(out);
9218            if (count > 1) {
9219                out.print(" ("); out.print(count); out.print(" filters)");
9220            }
9221            out.println();
9222        }
9223
9224//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9225//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9226//            final List<ResolveInfo> retList = Lists.newArrayList();
9227//            while (i.hasNext()) {
9228//                final ResolveInfo resolveInfo = i.next();
9229//                if (isEnabledLP(resolveInfo.activityInfo)) {
9230//                    retList.add(resolveInfo);
9231//                }
9232//            }
9233//            return retList;
9234//        }
9235
9236        // Keys are String (activity class name), values are Activity.
9237        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9238                = new ArrayMap<ComponentName, PackageParser.Activity>();
9239        private int mFlags;
9240    }
9241
9242    private final class ServiceIntentResolver
9243            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9244        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9245                boolean defaultOnly, int userId) {
9246            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9247            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9248        }
9249
9250        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9251                int userId) {
9252            if (!sUserManager.exists(userId)) return null;
9253            mFlags = flags;
9254            return super.queryIntent(intent, resolvedType,
9255                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9256        }
9257
9258        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9259                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9260            if (!sUserManager.exists(userId)) return null;
9261            if (packageServices == null) {
9262                return null;
9263            }
9264            mFlags = flags;
9265            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9266            final int N = packageServices.size();
9267            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9268                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9269
9270            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9271            for (int i = 0; i < N; ++i) {
9272                intentFilters = packageServices.get(i).intents;
9273                if (intentFilters != null && intentFilters.size() > 0) {
9274                    PackageParser.ServiceIntentInfo[] array =
9275                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9276                    intentFilters.toArray(array);
9277                    listCut.add(array);
9278                }
9279            }
9280            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9281        }
9282
9283        public final void addService(PackageParser.Service s) {
9284            mServices.put(s.getComponentName(), s);
9285            if (DEBUG_SHOW_INFO) {
9286                Log.v(TAG, "  "
9287                        + (s.info.nonLocalizedLabel != null
9288                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9289                Log.v(TAG, "    Class=" + s.info.name);
9290            }
9291            final int NI = s.intents.size();
9292            int j;
9293            for (j=0; j<NI; j++) {
9294                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9295                if (DEBUG_SHOW_INFO) {
9296                    Log.v(TAG, "    IntentFilter:");
9297                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9298                }
9299                if (!intent.debugCheck()) {
9300                    Log.w(TAG, "==> For Service " + s.info.name);
9301                }
9302                addFilter(intent);
9303            }
9304        }
9305
9306        public final void removeService(PackageParser.Service s) {
9307            mServices.remove(s.getComponentName());
9308            if (DEBUG_SHOW_INFO) {
9309                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9310                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9311                Log.v(TAG, "    Class=" + s.info.name);
9312            }
9313            final int NI = s.intents.size();
9314            int j;
9315            for (j=0; j<NI; j++) {
9316                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9317                if (DEBUG_SHOW_INFO) {
9318                    Log.v(TAG, "    IntentFilter:");
9319                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9320                }
9321                removeFilter(intent);
9322            }
9323        }
9324
9325        @Override
9326        protected boolean allowFilterResult(
9327                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9328            ServiceInfo filterSi = filter.service.info;
9329            for (int i=dest.size()-1; i>=0; i--) {
9330                ServiceInfo destAi = dest.get(i).serviceInfo;
9331                if (destAi.name == filterSi.name
9332                        && destAi.packageName == filterSi.packageName) {
9333                    return false;
9334                }
9335            }
9336            return true;
9337        }
9338
9339        @Override
9340        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9341            return new PackageParser.ServiceIntentInfo[size];
9342        }
9343
9344        @Override
9345        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9346            if (!sUserManager.exists(userId)) return true;
9347            PackageParser.Package p = filter.service.owner;
9348            if (p != null) {
9349                PackageSetting ps = (PackageSetting)p.mExtras;
9350                if (ps != null) {
9351                    // System apps are never considered stopped for purposes of
9352                    // filtering, because there may be no way for the user to
9353                    // actually re-launch them.
9354                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9355                            && ps.getStopped(userId);
9356                }
9357            }
9358            return false;
9359        }
9360
9361        @Override
9362        protected boolean isPackageForFilter(String packageName,
9363                PackageParser.ServiceIntentInfo info) {
9364            return packageName.equals(info.service.owner.packageName);
9365        }
9366
9367        @Override
9368        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9369                int match, int userId) {
9370            if (!sUserManager.exists(userId)) return null;
9371            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9372            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9373                return null;
9374            }
9375            final PackageParser.Service service = info.service;
9376            if (mSafeMode && (service.info.applicationInfo.flags
9377                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9378                return null;
9379            }
9380            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9381            if (ps == null) {
9382                return null;
9383            }
9384            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9385                    ps.readUserState(userId), userId);
9386            if (si == null) {
9387                return null;
9388            }
9389            final ResolveInfo res = new ResolveInfo();
9390            res.serviceInfo = si;
9391            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9392                res.filter = filter;
9393            }
9394            res.priority = info.getPriority();
9395            res.preferredOrder = service.owner.mPreferredOrder;
9396            res.match = match;
9397            res.isDefault = info.hasDefault;
9398            res.labelRes = info.labelRes;
9399            res.nonLocalizedLabel = info.nonLocalizedLabel;
9400            res.icon = info.icon;
9401            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9402            return res;
9403        }
9404
9405        @Override
9406        protected void sortResults(List<ResolveInfo> results) {
9407            Collections.sort(results, mResolvePrioritySorter);
9408        }
9409
9410        @Override
9411        protected void dumpFilter(PrintWriter out, String prefix,
9412                PackageParser.ServiceIntentInfo filter) {
9413            out.print(prefix); out.print(
9414                    Integer.toHexString(System.identityHashCode(filter.service)));
9415                    out.print(' ');
9416                    filter.service.printComponentShortName(out);
9417                    out.print(" filter ");
9418                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9419        }
9420
9421        @Override
9422        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9423            return filter.service;
9424        }
9425
9426        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9427            PackageParser.Service service = (PackageParser.Service)label;
9428            out.print(prefix); out.print(
9429                    Integer.toHexString(System.identityHashCode(service)));
9430                    out.print(' ');
9431                    service.printComponentShortName(out);
9432            if (count > 1) {
9433                out.print(" ("); out.print(count); out.print(" filters)");
9434            }
9435            out.println();
9436        }
9437
9438//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9439//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9440//            final List<ResolveInfo> retList = Lists.newArrayList();
9441//            while (i.hasNext()) {
9442//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9443//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9444//                    retList.add(resolveInfo);
9445//                }
9446//            }
9447//            return retList;
9448//        }
9449
9450        // Keys are String (activity class name), values are Activity.
9451        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9452                = new ArrayMap<ComponentName, PackageParser.Service>();
9453        private int mFlags;
9454    };
9455
9456    private final class ProviderIntentResolver
9457            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9458        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9459                boolean defaultOnly, int userId) {
9460            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9461            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9462        }
9463
9464        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9465                int userId) {
9466            if (!sUserManager.exists(userId))
9467                return null;
9468            mFlags = flags;
9469            return super.queryIntent(intent, resolvedType,
9470                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9471        }
9472
9473        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9474                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9475            if (!sUserManager.exists(userId))
9476                return null;
9477            if (packageProviders == null) {
9478                return null;
9479            }
9480            mFlags = flags;
9481            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9482            final int N = packageProviders.size();
9483            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9484                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9485
9486            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9487            for (int i = 0; i < N; ++i) {
9488                intentFilters = packageProviders.get(i).intents;
9489                if (intentFilters != null && intentFilters.size() > 0) {
9490                    PackageParser.ProviderIntentInfo[] array =
9491                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9492                    intentFilters.toArray(array);
9493                    listCut.add(array);
9494                }
9495            }
9496            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9497        }
9498
9499        public final void addProvider(PackageParser.Provider p) {
9500            if (mProviders.containsKey(p.getComponentName())) {
9501                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9502                return;
9503            }
9504
9505            mProviders.put(p.getComponentName(), p);
9506            if (DEBUG_SHOW_INFO) {
9507                Log.v(TAG, "  "
9508                        + (p.info.nonLocalizedLabel != null
9509                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9510                Log.v(TAG, "    Class=" + p.info.name);
9511            }
9512            final int NI = p.intents.size();
9513            int j;
9514            for (j = 0; j < NI; j++) {
9515                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9516                if (DEBUG_SHOW_INFO) {
9517                    Log.v(TAG, "    IntentFilter:");
9518                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9519                }
9520                if (!intent.debugCheck()) {
9521                    Log.w(TAG, "==> For Provider " + p.info.name);
9522                }
9523                addFilter(intent);
9524            }
9525        }
9526
9527        public final void removeProvider(PackageParser.Provider p) {
9528            mProviders.remove(p.getComponentName());
9529            if (DEBUG_SHOW_INFO) {
9530                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9531                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9532                Log.v(TAG, "    Class=" + p.info.name);
9533            }
9534            final int NI = p.intents.size();
9535            int j;
9536            for (j = 0; j < NI; j++) {
9537                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9538                if (DEBUG_SHOW_INFO) {
9539                    Log.v(TAG, "    IntentFilter:");
9540                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9541                }
9542                removeFilter(intent);
9543            }
9544        }
9545
9546        @Override
9547        protected boolean allowFilterResult(
9548                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9549            ProviderInfo filterPi = filter.provider.info;
9550            for (int i = dest.size() - 1; i >= 0; i--) {
9551                ProviderInfo destPi = dest.get(i).providerInfo;
9552                if (destPi.name == filterPi.name
9553                        && destPi.packageName == filterPi.packageName) {
9554                    return false;
9555                }
9556            }
9557            return true;
9558        }
9559
9560        @Override
9561        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9562            return new PackageParser.ProviderIntentInfo[size];
9563        }
9564
9565        @Override
9566        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9567            if (!sUserManager.exists(userId))
9568                return true;
9569            PackageParser.Package p = filter.provider.owner;
9570            if (p != null) {
9571                PackageSetting ps = (PackageSetting) p.mExtras;
9572                if (ps != null) {
9573                    // System apps are never considered stopped for purposes of
9574                    // filtering, because there may be no way for the user to
9575                    // actually re-launch them.
9576                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9577                            && ps.getStopped(userId);
9578                }
9579            }
9580            return false;
9581        }
9582
9583        @Override
9584        protected boolean isPackageForFilter(String packageName,
9585                PackageParser.ProviderIntentInfo info) {
9586            return packageName.equals(info.provider.owner.packageName);
9587        }
9588
9589        @Override
9590        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9591                int match, int userId) {
9592            if (!sUserManager.exists(userId))
9593                return null;
9594            final PackageParser.ProviderIntentInfo info = filter;
9595            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9596                return null;
9597            }
9598            final PackageParser.Provider provider = info.provider;
9599            if (mSafeMode && (provider.info.applicationInfo.flags
9600                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9601                return null;
9602            }
9603            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9604            if (ps == null) {
9605                return null;
9606            }
9607            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9608                    ps.readUserState(userId), userId);
9609            if (pi == null) {
9610                return null;
9611            }
9612            final ResolveInfo res = new ResolveInfo();
9613            res.providerInfo = pi;
9614            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9615                res.filter = filter;
9616            }
9617            res.priority = info.getPriority();
9618            res.preferredOrder = provider.owner.mPreferredOrder;
9619            res.match = match;
9620            res.isDefault = info.hasDefault;
9621            res.labelRes = info.labelRes;
9622            res.nonLocalizedLabel = info.nonLocalizedLabel;
9623            res.icon = info.icon;
9624            res.system = res.providerInfo.applicationInfo.isSystemApp();
9625            return res;
9626        }
9627
9628        @Override
9629        protected void sortResults(List<ResolveInfo> results) {
9630            Collections.sort(results, mResolvePrioritySorter);
9631        }
9632
9633        @Override
9634        protected void dumpFilter(PrintWriter out, String prefix,
9635                PackageParser.ProviderIntentInfo filter) {
9636            out.print(prefix);
9637            out.print(
9638                    Integer.toHexString(System.identityHashCode(filter.provider)));
9639            out.print(' ');
9640            filter.provider.printComponentShortName(out);
9641            out.print(" filter ");
9642            out.println(Integer.toHexString(System.identityHashCode(filter)));
9643        }
9644
9645        @Override
9646        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9647            return filter.provider;
9648        }
9649
9650        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9651            PackageParser.Provider provider = (PackageParser.Provider)label;
9652            out.print(prefix); out.print(
9653                    Integer.toHexString(System.identityHashCode(provider)));
9654                    out.print(' ');
9655                    provider.printComponentShortName(out);
9656            if (count > 1) {
9657                out.print(" ("); out.print(count); out.print(" filters)");
9658            }
9659            out.println();
9660        }
9661
9662        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9663                = new ArrayMap<ComponentName, PackageParser.Provider>();
9664        private int mFlags;
9665    }
9666
9667    private static final class EphemeralIntentResolver
9668            extends IntentResolver<IntentFilter, ResolveInfo> {
9669        @Override
9670        protected IntentFilter[] newArray(int size) {
9671            return new IntentFilter[size];
9672        }
9673
9674        @Override
9675        protected boolean isPackageForFilter(String packageName, IntentFilter info) {
9676            return true;
9677        }
9678
9679        @Override
9680        protected ResolveInfo newResult(IntentFilter info, int match, int userId) {
9681            if (!sUserManager.exists(userId)) return null;
9682            final ResolveInfo res = new ResolveInfo();
9683            res.filter = info;
9684            return res;
9685        }
9686    }
9687
9688    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9689            new Comparator<ResolveInfo>() {
9690        public int compare(ResolveInfo r1, ResolveInfo r2) {
9691            int v1 = r1.priority;
9692            int v2 = r2.priority;
9693            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9694            if (v1 != v2) {
9695                return (v1 > v2) ? -1 : 1;
9696            }
9697            v1 = r1.preferredOrder;
9698            v2 = r2.preferredOrder;
9699            if (v1 != v2) {
9700                return (v1 > v2) ? -1 : 1;
9701            }
9702            if (r1.isDefault != r2.isDefault) {
9703                return r1.isDefault ? -1 : 1;
9704            }
9705            v1 = r1.match;
9706            v2 = r2.match;
9707            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9708            if (v1 != v2) {
9709                return (v1 > v2) ? -1 : 1;
9710            }
9711            if (r1.system != r2.system) {
9712                return r1.system ? -1 : 1;
9713            }
9714            return 0;
9715        }
9716    };
9717
9718    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9719            new Comparator<ProviderInfo>() {
9720        public int compare(ProviderInfo p1, ProviderInfo p2) {
9721            final int v1 = p1.initOrder;
9722            final int v2 = p2.initOrder;
9723            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9724        }
9725    };
9726
9727    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9728            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9729            final int[] userIds) {
9730        mHandler.post(new Runnable() {
9731            @Override
9732            public void run() {
9733                try {
9734                    final IActivityManager am = ActivityManagerNative.getDefault();
9735                    if (am == null) return;
9736                    final int[] resolvedUserIds;
9737                    if (userIds == null) {
9738                        resolvedUserIds = am.getRunningUserIds();
9739                    } else {
9740                        resolvedUserIds = userIds;
9741                    }
9742                    for (int id : resolvedUserIds) {
9743                        final Intent intent = new Intent(action,
9744                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9745                        if (extras != null) {
9746                            intent.putExtras(extras);
9747                        }
9748                        if (targetPkg != null) {
9749                            intent.setPackage(targetPkg);
9750                        }
9751                        // Modify the UID when posting to other users
9752                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9753                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9754                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9755                            intent.putExtra(Intent.EXTRA_UID, uid);
9756                        }
9757                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9758                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9759                        if (DEBUG_BROADCASTS) {
9760                            RuntimeException here = new RuntimeException("here");
9761                            here.fillInStackTrace();
9762                            Slog.d(TAG, "Sending to user " + id + ": "
9763                                    + intent.toShortString(false, true, false, false)
9764                                    + " " + intent.getExtras(), here);
9765                        }
9766                        am.broadcastIntent(null, intent, null, finishedReceiver,
9767                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9768                                null, finishedReceiver != null, false, id);
9769                    }
9770                } catch (RemoteException ex) {
9771                }
9772            }
9773        });
9774    }
9775
9776    /**
9777     * Check if the external storage media is available. This is true if there
9778     * is a mounted external storage medium or if the external storage is
9779     * emulated.
9780     */
9781    private boolean isExternalMediaAvailable() {
9782        return mMediaMounted || Environment.isExternalStorageEmulated();
9783    }
9784
9785    @Override
9786    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9787        // writer
9788        synchronized (mPackages) {
9789            if (!isExternalMediaAvailable()) {
9790                // If the external storage is no longer mounted at this point,
9791                // the caller may not have been able to delete all of this
9792                // packages files and can not delete any more.  Bail.
9793                return null;
9794            }
9795            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9796            if (lastPackage != null) {
9797                pkgs.remove(lastPackage);
9798            }
9799            if (pkgs.size() > 0) {
9800                return pkgs.get(0);
9801            }
9802        }
9803        return null;
9804    }
9805
9806    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9807        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9808                userId, andCode ? 1 : 0, packageName);
9809        if (mSystemReady) {
9810            msg.sendToTarget();
9811        } else {
9812            if (mPostSystemReadyMessages == null) {
9813                mPostSystemReadyMessages = new ArrayList<>();
9814            }
9815            mPostSystemReadyMessages.add(msg);
9816        }
9817    }
9818
9819    void startCleaningPackages() {
9820        // reader
9821        synchronized (mPackages) {
9822            if (!isExternalMediaAvailable()) {
9823                return;
9824            }
9825            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9826                return;
9827            }
9828        }
9829        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9830        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9831        IActivityManager am = ActivityManagerNative.getDefault();
9832        if (am != null) {
9833            try {
9834                am.startService(null, intent, null, mContext.getOpPackageName(),
9835                        UserHandle.USER_SYSTEM);
9836            } catch (RemoteException e) {
9837            }
9838        }
9839    }
9840
9841    @Override
9842    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9843            int installFlags, String installerPackageName, VerificationParams verificationParams,
9844            String packageAbiOverride) {
9845        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9846                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9847    }
9848
9849    @Override
9850    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9851            int installFlags, String installerPackageName, VerificationParams verificationParams,
9852            String packageAbiOverride, int userId) {
9853        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9854
9855        final int callingUid = Binder.getCallingUid();
9856        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9857
9858        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9859            try {
9860                if (observer != null) {
9861                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9862                }
9863            } catch (RemoteException re) {
9864            }
9865            return;
9866        }
9867
9868        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9869            installFlags |= PackageManager.INSTALL_FROM_ADB;
9870
9871        } else {
9872            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9873            // about installerPackageName.
9874
9875            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9876            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9877        }
9878
9879        UserHandle user;
9880        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9881            user = UserHandle.ALL;
9882        } else {
9883            user = new UserHandle(userId);
9884        }
9885
9886        // Only system components can circumvent runtime permissions when installing.
9887        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9888                && mContext.checkCallingOrSelfPermission(Manifest.permission
9889                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9890            throw new SecurityException("You need the "
9891                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9892                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9893        }
9894
9895        verificationParams.setInstallerUid(callingUid);
9896
9897        final File originFile = new File(originPath);
9898        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9899
9900        final Message msg = mHandler.obtainMessage(INIT_COPY);
9901        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9902                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9903        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9904        msg.obj = params;
9905
9906        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9907                System.identityHashCode(msg.obj));
9908        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9909                System.identityHashCode(msg.obj));
9910
9911        mHandler.sendMessage(msg);
9912    }
9913
9914    void installStage(String packageName, File stagedDir, String stagedCid,
9915            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9916            String installerPackageName, int installerUid, UserHandle user) {
9917        if (DEBUG_EPHEMERAL) {
9918            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
9919                Slog.d(TAG, "Ephemeral install of " + packageName);
9920            }
9921        }
9922        final VerificationParams verifParams = new VerificationParams(
9923                null, sessionParams.originatingUri, sessionParams.referrerUri,
9924                sessionParams.originatingUid, null);
9925        verifParams.setInstallerUid(installerUid);
9926
9927        final OriginInfo origin;
9928        if (stagedDir != null) {
9929            origin = OriginInfo.fromStagedFile(stagedDir);
9930        } else {
9931            origin = OriginInfo.fromStagedContainer(stagedCid);
9932        }
9933
9934        final Message msg = mHandler.obtainMessage(INIT_COPY);
9935        final InstallParams params = new InstallParams(origin, null, observer,
9936                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9937                verifParams, user, sessionParams.abiOverride,
9938                sessionParams.grantedRuntimePermissions);
9939        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9940        msg.obj = params;
9941
9942        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9943                System.identityHashCode(msg.obj));
9944        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9945                System.identityHashCode(msg.obj));
9946
9947        mHandler.sendMessage(msg);
9948    }
9949
9950    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9951        Bundle extras = new Bundle(1);
9952        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9953
9954        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9955                packageName, extras, 0, null, null, new int[] {userId});
9956        try {
9957            IActivityManager am = ActivityManagerNative.getDefault();
9958            final boolean isSystem =
9959                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9960            if (isSystem && am.isUserRunning(userId, 0)) {
9961                // The just-installed/enabled app is bundled on the system, so presumed
9962                // to be able to run automatically without needing an explicit launch.
9963                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9964                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9965                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9966                        .setPackage(packageName);
9967                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9968                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9969            }
9970        } catch (RemoteException e) {
9971            // shouldn't happen
9972            Slog.w(TAG, "Unable to bootstrap installed package", e);
9973        }
9974    }
9975
9976    @Override
9977    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9978            int userId) {
9979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9980        PackageSetting pkgSetting;
9981        final int uid = Binder.getCallingUid();
9982        enforceCrossUserPermission(uid, userId, true, true,
9983                "setApplicationHiddenSetting for user " + userId);
9984
9985        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9986            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9987            return false;
9988        }
9989
9990        long callingId = Binder.clearCallingIdentity();
9991        try {
9992            boolean sendAdded = false;
9993            boolean sendRemoved = false;
9994            // writer
9995            synchronized (mPackages) {
9996                pkgSetting = mSettings.mPackages.get(packageName);
9997                if (pkgSetting == null) {
9998                    return false;
9999                }
10000                if (pkgSetting.getHidden(userId) != hidden) {
10001                    pkgSetting.setHidden(hidden, userId);
10002                    mSettings.writePackageRestrictionsLPr(userId);
10003                    if (hidden) {
10004                        sendRemoved = true;
10005                    } else {
10006                        sendAdded = true;
10007                    }
10008                }
10009            }
10010            if (sendAdded) {
10011                sendPackageAddedForUser(packageName, pkgSetting, userId);
10012                return true;
10013            }
10014            if (sendRemoved) {
10015                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10016                        "hiding pkg");
10017                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10018                return true;
10019            }
10020        } finally {
10021            Binder.restoreCallingIdentity(callingId);
10022        }
10023        return false;
10024    }
10025
10026    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10027            int userId) {
10028        final PackageRemovedInfo info = new PackageRemovedInfo();
10029        info.removedPackage = packageName;
10030        info.removedUsers = new int[] {userId};
10031        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10032        info.sendBroadcast(false, false, false);
10033    }
10034
10035    /**
10036     * Returns true if application is not found or there was an error. Otherwise it returns
10037     * the hidden state of the package for the given user.
10038     */
10039    @Override
10040    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10041        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10042        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10043                false, "getApplicationHidden for user " + userId);
10044        PackageSetting pkgSetting;
10045        long callingId = Binder.clearCallingIdentity();
10046        try {
10047            // writer
10048            synchronized (mPackages) {
10049                pkgSetting = mSettings.mPackages.get(packageName);
10050                if (pkgSetting == null) {
10051                    return true;
10052                }
10053                return pkgSetting.getHidden(userId);
10054            }
10055        } finally {
10056            Binder.restoreCallingIdentity(callingId);
10057        }
10058    }
10059
10060    /**
10061     * @hide
10062     */
10063    @Override
10064    public int installExistingPackageAsUser(String packageName, int userId) {
10065        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10066                null);
10067        PackageSetting pkgSetting;
10068        final int uid = Binder.getCallingUid();
10069        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10070                + userId);
10071        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10072            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10073        }
10074
10075        long callingId = Binder.clearCallingIdentity();
10076        try {
10077            boolean sendAdded = false;
10078
10079            // writer
10080            synchronized (mPackages) {
10081                pkgSetting = mSettings.mPackages.get(packageName);
10082                if (pkgSetting == null) {
10083                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10084                }
10085                if (!pkgSetting.getInstalled(userId)) {
10086                    pkgSetting.setInstalled(true, userId);
10087                    pkgSetting.setHidden(false, userId);
10088                    mSettings.writePackageRestrictionsLPr(userId);
10089                    sendAdded = true;
10090                }
10091            }
10092
10093            if (sendAdded) {
10094                sendPackageAddedForUser(packageName, pkgSetting, userId);
10095            }
10096        } finally {
10097            Binder.restoreCallingIdentity(callingId);
10098        }
10099
10100        return PackageManager.INSTALL_SUCCEEDED;
10101    }
10102
10103    boolean isUserRestricted(int userId, String restrictionKey) {
10104        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10105        if (restrictions.getBoolean(restrictionKey, false)) {
10106            Log.w(TAG, "User is restricted: " + restrictionKey);
10107            return true;
10108        }
10109        return false;
10110    }
10111
10112    @Override
10113    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10114        mContext.enforceCallingOrSelfPermission(
10115                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10116                "Only package verification agents can verify applications");
10117
10118        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10119        final PackageVerificationResponse response = new PackageVerificationResponse(
10120                verificationCode, Binder.getCallingUid());
10121        msg.arg1 = id;
10122        msg.obj = response;
10123        mHandler.sendMessage(msg);
10124    }
10125
10126    @Override
10127    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10128            long millisecondsToDelay) {
10129        mContext.enforceCallingOrSelfPermission(
10130                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10131                "Only package verification agents can extend verification timeouts");
10132
10133        final PackageVerificationState state = mPendingVerification.get(id);
10134        final PackageVerificationResponse response = new PackageVerificationResponse(
10135                verificationCodeAtTimeout, Binder.getCallingUid());
10136
10137        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10138            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10139        }
10140        if (millisecondsToDelay < 0) {
10141            millisecondsToDelay = 0;
10142        }
10143        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10144                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10145            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10146        }
10147
10148        if ((state != null) && !state.timeoutExtended()) {
10149            state.extendTimeout();
10150
10151            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10152            msg.arg1 = id;
10153            msg.obj = response;
10154            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10155        }
10156    }
10157
10158    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10159            int verificationCode, UserHandle user) {
10160        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10161        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10162        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10163        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10164        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10165
10166        mContext.sendBroadcastAsUser(intent, user,
10167                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10168    }
10169
10170    private ComponentName matchComponentForVerifier(String packageName,
10171            List<ResolveInfo> receivers) {
10172        ActivityInfo targetReceiver = null;
10173
10174        final int NR = receivers.size();
10175        for (int i = 0; i < NR; i++) {
10176            final ResolveInfo info = receivers.get(i);
10177            if (info.activityInfo == null) {
10178                continue;
10179            }
10180
10181            if (packageName.equals(info.activityInfo.packageName)) {
10182                targetReceiver = info.activityInfo;
10183                break;
10184            }
10185        }
10186
10187        if (targetReceiver == null) {
10188            return null;
10189        }
10190
10191        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10192    }
10193
10194    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10195            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10196        if (pkgInfo.verifiers.length == 0) {
10197            return null;
10198        }
10199
10200        final int N = pkgInfo.verifiers.length;
10201        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10202        for (int i = 0; i < N; i++) {
10203            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10204
10205            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10206                    receivers);
10207            if (comp == null) {
10208                continue;
10209            }
10210
10211            final int verifierUid = getUidForVerifier(verifierInfo);
10212            if (verifierUid == -1) {
10213                continue;
10214            }
10215
10216            if (DEBUG_VERIFY) {
10217                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10218                        + " with the correct signature");
10219            }
10220            sufficientVerifiers.add(comp);
10221            verificationState.addSufficientVerifier(verifierUid);
10222        }
10223
10224        return sufficientVerifiers;
10225    }
10226
10227    private int getUidForVerifier(VerifierInfo verifierInfo) {
10228        synchronized (mPackages) {
10229            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10230            if (pkg == null) {
10231                return -1;
10232            } else if (pkg.mSignatures.length != 1) {
10233                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10234                        + " has more than one signature; ignoring");
10235                return -1;
10236            }
10237
10238            /*
10239             * If the public key of the package's signature does not match
10240             * our expected public key, then this is a different package and
10241             * we should skip.
10242             */
10243
10244            final byte[] expectedPublicKey;
10245            try {
10246                final Signature verifierSig = pkg.mSignatures[0];
10247                final PublicKey publicKey = verifierSig.getPublicKey();
10248                expectedPublicKey = publicKey.getEncoded();
10249            } catch (CertificateException e) {
10250                return -1;
10251            }
10252
10253            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10254
10255            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10256                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10257                        + " does not have the expected public key; ignoring");
10258                return -1;
10259            }
10260
10261            return pkg.applicationInfo.uid;
10262        }
10263    }
10264
10265    @Override
10266    public void finishPackageInstall(int token) {
10267        enforceSystemOrRoot("Only the system is allowed to finish installs");
10268
10269        if (DEBUG_INSTALL) {
10270            Slog.v(TAG, "BM finishing package install for " + token);
10271        }
10272        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10273
10274        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10275        mHandler.sendMessage(msg);
10276    }
10277
10278    /**
10279     * Get the verification agent timeout.
10280     *
10281     * @return verification timeout in milliseconds
10282     */
10283    private long getVerificationTimeout() {
10284        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10285                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10286                DEFAULT_VERIFICATION_TIMEOUT);
10287    }
10288
10289    /**
10290     * Get the default verification agent response code.
10291     *
10292     * @return default verification response code
10293     */
10294    private int getDefaultVerificationResponse() {
10295        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10296                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10297                DEFAULT_VERIFICATION_RESPONSE);
10298    }
10299
10300    /**
10301     * Check whether or not package verification has been enabled.
10302     *
10303     * @return true if verification should be performed
10304     */
10305    private boolean isVerificationEnabled(int userId, int installFlags) {
10306        if (!DEFAULT_VERIFY_ENABLE) {
10307            return false;
10308        }
10309        // TODO: fix b/25118622; don't bypass verification
10310        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10311            return false;
10312        }
10313        // Ephemeral apps don't get the full verification treatment
10314        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10315            if (DEBUG_EPHEMERAL) {
10316                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10317            }
10318            return false;
10319        }
10320
10321        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10322
10323        // Check if installing from ADB
10324        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10325            // Do not run verification in a test harness environment
10326            if (ActivityManager.isRunningInTestHarness()) {
10327                return false;
10328            }
10329            if (ensureVerifyAppsEnabled) {
10330                return true;
10331            }
10332            // Check if the developer does not want package verification for ADB installs
10333            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10334                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10335                return false;
10336            }
10337        }
10338
10339        if (ensureVerifyAppsEnabled) {
10340            return true;
10341        }
10342
10343        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10344                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10345    }
10346
10347    @Override
10348    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10349            throws RemoteException {
10350        mContext.enforceCallingOrSelfPermission(
10351                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10352                "Only intentfilter verification agents can verify applications");
10353
10354        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10355        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10356                Binder.getCallingUid(), verificationCode, failedDomains);
10357        msg.arg1 = id;
10358        msg.obj = response;
10359        mHandler.sendMessage(msg);
10360    }
10361
10362    @Override
10363    public int getIntentVerificationStatus(String packageName, int userId) {
10364        synchronized (mPackages) {
10365            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10366        }
10367    }
10368
10369    @Override
10370    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10371        mContext.enforceCallingOrSelfPermission(
10372                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10373
10374        boolean result = false;
10375        synchronized (mPackages) {
10376            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10377        }
10378        if (result) {
10379            scheduleWritePackageRestrictionsLocked(userId);
10380        }
10381        return result;
10382    }
10383
10384    @Override
10385    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10386        synchronized (mPackages) {
10387            return mSettings.getIntentFilterVerificationsLPr(packageName);
10388        }
10389    }
10390
10391    @Override
10392    public List<IntentFilter> getAllIntentFilters(String packageName) {
10393        if (TextUtils.isEmpty(packageName)) {
10394            return Collections.<IntentFilter>emptyList();
10395        }
10396        synchronized (mPackages) {
10397            PackageParser.Package pkg = mPackages.get(packageName);
10398            if (pkg == null || pkg.activities == null) {
10399                return Collections.<IntentFilter>emptyList();
10400            }
10401            final int count = pkg.activities.size();
10402            ArrayList<IntentFilter> result = new ArrayList<>();
10403            for (int n=0; n<count; n++) {
10404                PackageParser.Activity activity = pkg.activities.get(n);
10405                if (activity.intents != null || activity.intents.size() > 0) {
10406                    result.addAll(activity.intents);
10407                }
10408            }
10409            return result;
10410        }
10411    }
10412
10413    @Override
10414    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10415        mContext.enforceCallingOrSelfPermission(
10416                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10417
10418        synchronized (mPackages) {
10419            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10420            if (packageName != null) {
10421                result |= updateIntentVerificationStatus(packageName,
10422                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10423                        userId);
10424                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10425                        packageName, userId);
10426            }
10427            return result;
10428        }
10429    }
10430
10431    @Override
10432    public String getDefaultBrowserPackageName(int userId) {
10433        synchronized (mPackages) {
10434            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10435        }
10436    }
10437
10438    /**
10439     * Get the "allow unknown sources" setting.
10440     *
10441     * @return the current "allow unknown sources" setting
10442     */
10443    private int getUnknownSourcesSettings() {
10444        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10445                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10446                -1);
10447    }
10448
10449    @Override
10450    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10451        final int uid = Binder.getCallingUid();
10452        // writer
10453        synchronized (mPackages) {
10454            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10455            if (targetPackageSetting == null) {
10456                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10457            }
10458
10459            PackageSetting installerPackageSetting;
10460            if (installerPackageName != null) {
10461                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10462                if (installerPackageSetting == null) {
10463                    throw new IllegalArgumentException("Unknown installer package: "
10464                            + installerPackageName);
10465                }
10466            } else {
10467                installerPackageSetting = null;
10468            }
10469
10470            Signature[] callerSignature;
10471            Object obj = mSettings.getUserIdLPr(uid);
10472            if (obj != null) {
10473                if (obj instanceof SharedUserSetting) {
10474                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10475                } else if (obj instanceof PackageSetting) {
10476                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10477                } else {
10478                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10479                }
10480            } else {
10481                throw new SecurityException("Unknown calling uid " + uid);
10482            }
10483
10484            // Verify: can't set installerPackageName to a package that is
10485            // not signed with the same cert as the caller.
10486            if (installerPackageSetting != null) {
10487                if (compareSignatures(callerSignature,
10488                        installerPackageSetting.signatures.mSignatures)
10489                        != PackageManager.SIGNATURE_MATCH) {
10490                    throw new SecurityException(
10491                            "Caller does not have same cert as new installer package "
10492                            + installerPackageName);
10493                }
10494            }
10495
10496            // Verify: if target already has an installer package, it must
10497            // be signed with the same cert as the caller.
10498            if (targetPackageSetting.installerPackageName != null) {
10499                PackageSetting setting = mSettings.mPackages.get(
10500                        targetPackageSetting.installerPackageName);
10501                // If the currently set package isn't valid, then it's always
10502                // okay to change it.
10503                if (setting != null) {
10504                    if (compareSignatures(callerSignature,
10505                            setting.signatures.mSignatures)
10506                            != PackageManager.SIGNATURE_MATCH) {
10507                        throw new SecurityException(
10508                                "Caller does not have same cert as old installer package "
10509                                + targetPackageSetting.installerPackageName);
10510                    }
10511                }
10512            }
10513
10514            // Okay!
10515            targetPackageSetting.installerPackageName = installerPackageName;
10516            scheduleWriteSettingsLocked();
10517        }
10518    }
10519
10520    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10521        // Queue up an async operation since the package installation may take a little while.
10522        mHandler.post(new Runnable() {
10523            public void run() {
10524                mHandler.removeCallbacks(this);
10525                 // Result object to be returned
10526                PackageInstalledInfo res = new PackageInstalledInfo();
10527                res.returnCode = currentStatus;
10528                res.uid = -1;
10529                res.pkg = null;
10530                res.removedInfo = new PackageRemovedInfo();
10531                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10532                    args.doPreInstall(res.returnCode);
10533                    synchronized (mInstallLock) {
10534                        installPackageTracedLI(args, res);
10535                    }
10536                    args.doPostInstall(res.returnCode, res.uid);
10537                }
10538
10539                // A restore should be performed at this point if (a) the install
10540                // succeeded, (b) the operation is not an update, and (c) the new
10541                // package has not opted out of backup participation.
10542                final boolean update = res.removedInfo.removedPackage != null;
10543                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10544                boolean doRestore = !update
10545                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10546
10547                // Set up the post-install work request bookkeeping.  This will be used
10548                // and cleaned up by the post-install event handling regardless of whether
10549                // there's a restore pass performed.  Token values are >= 1.
10550                int token;
10551                if (mNextInstallToken < 0) mNextInstallToken = 1;
10552                token = mNextInstallToken++;
10553
10554                PostInstallData data = new PostInstallData(args, res);
10555                mRunningInstalls.put(token, data);
10556                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10557
10558                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10559                    // Pass responsibility to the Backup Manager.  It will perform a
10560                    // restore if appropriate, then pass responsibility back to the
10561                    // Package Manager to run the post-install observer callbacks
10562                    // and broadcasts.
10563                    IBackupManager bm = IBackupManager.Stub.asInterface(
10564                            ServiceManager.getService(Context.BACKUP_SERVICE));
10565                    if (bm != null) {
10566                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10567                                + " to BM for possible restore");
10568                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10569                        try {
10570                            // TODO: http://b/22388012
10571                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10572                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10573                            } else {
10574                                doRestore = false;
10575                            }
10576                        } catch (RemoteException e) {
10577                            // can't happen; the backup manager is local
10578                        } catch (Exception e) {
10579                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10580                            doRestore = false;
10581                        }
10582                    } else {
10583                        Slog.e(TAG, "Backup Manager not found!");
10584                        doRestore = false;
10585                    }
10586                }
10587
10588                if (!doRestore) {
10589                    // No restore possible, or the Backup Manager was mysteriously not
10590                    // available -- just fire the post-install work request directly.
10591                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10592
10593                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10594
10595                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10596                    mHandler.sendMessage(msg);
10597                }
10598            }
10599        });
10600    }
10601
10602    private abstract class HandlerParams {
10603        private static final int MAX_RETRIES = 4;
10604
10605        /**
10606         * Number of times startCopy() has been attempted and had a non-fatal
10607         * error.
10608         */
10609        private int mRetries = 0;
10610
10611        /** User handle for the user requesting the information or installation. */
10612        private final UserHandle mUser;
10613        String traceMethod;
10614        int traceCookie;
10615
10616        HandlerParams(UserHandle user) {
10617            mUser = user;
10618        }
10619
10620        UserHandle getUser() {
10621            return mUser;
10622        }
10623
10624        HandlerParams setTraceMethod(String traceMethod) {
10625            this.traceMethod = traceMethod;
10626            return this;
10627        }
10628
10629        HandlerParams setTraceCookie(int traceCookie) {
10630            this.traceCookie = traceCookie;
10631            return this;
10632        }
10633
10634        final boolean startCopy() {
10635            boolean res;
10636            try {
10637                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10638
10639                if (++mRetries > MAX_RETRIES) {
10640                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10641                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10642                    handleServiceError();
10643                    return false;
10644                } else {
10645                    handleStartCopy();
10646                    res = true;
10647                }
10648            } catch (RemoteException e) {
10649                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10650                mHandler.sendEmptyMessage(MCS_RECONNECT);
10651                res = false;
10652            }
10653            handleReturnCode();
10654            return res;
10655        }
10656
10657        final void serviceError() {
10658            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10659            handleServiceError();
10660            handleReturnCode();
10661        }
10662
10663        abstract void handleStartCopy() throws RemoteException;
10664        abstract void handleServiceError();
10665        abstract void handleReturnCode();
10666    }
10667
10668    class MeasureParams extends HandlerParams {
10669        private final PackageStats mStats;
10670        private boolean mSuccess;
10671
10672        private final IPackageStatsObserver mObserver;
10673
10674        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10675            super(new UserHandle(stats.userHandle));
10676            mObserver = observer;
10677            mStats = stats;
10678        }
10679
10680        @Override
10681        public String toString() {
10682            return "MeasureParams{"
10683                + Integer.toHexString(System.identityHashCode(this))
10684                + " " + mStats.packageName + "}";
10685        }
10686
10687        @Override
10688        void handleStartCopy() throws RemoteException {
10689            synchronized (mInstallLock) {
10690                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10691            }
10692
10693            if (mSuccess) {
10694                final boolean mounted;
10695                if (Environment.isExternalStorageEmulated()) {
10696                    mounted = true;
10697                } else {
10698                    final String status = Environment.getExternalStorageState();
10699                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10700                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10701                }
10702
10703                if (mounted) {
10704                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10705
10706                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10707                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10708
10709                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10710                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10711
10712                    // Always subtract cache size, since it's a subdirectory
10713                    mStats.externalDataSize -= mStats.externalCacheSize;
10714
10715                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10716                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10717
10718                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10719                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10720                }
10721            }
10722        }
10723
10724        @Override
10725        void handleReturnCode() {
10726            if (mObserver != null) {
10727                try {
10728                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10729                } catch (RemoteException e) {
10730                    Slog.i(TAG, "Observer no longer exists.");
10731                }
10732            }
10733        }
10734
10735        @Override
10736        void handleServiceError() {
10737            Slog.e(TAG, "Could not measure application " + mStats.packageName
10738                            + " external storage");
10739        }
10740    }
10741
10742    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10743            throws RemoteException {
10744        long result = 0;
10745        for (File path : paths) {
10746            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10747        }
10748        return result;
10749    }
10750
10751    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10752        for (File path : paths) {
10753            try {
10754                mcs.clearDirectory(path.getAbsolutePath());
10755            } catch (RemoteException e) {
10756            }
10757        }
10758    }
10759
10760    static class OriginInfo {
10761        /**
10762         * Location where install is coming from, before it has been
10763         * copied/renamed into place. This could be a single monolithic APK
10764         * file, or a cluster directory. This location may be untrusted.
10765         */
10766        final File file;
10767        final String cid;
10768
10769        /**
10770         * Flag indicating that {@link #file} or {@link #cid} has already been
10771         * staged, meaning downstream users don't need to defensively copy the
10772         * contents.
10773         */
10774        final boolean staged;
10775
10776        /**
10777         * Flag indicating that {@link #file} or {@link #cid} is an already
10778         * installed app that is being moved.
10779         */
10780        final boolean existing;
10781
10782        final String resolvedPath;
10783        final File resolvedFile;
10784
10785        static OriginInfo fromNothing() {
10786            return new OriginInfo(null, null, false, false);
10787        }
10788
10789        static OriginInfo fromUntrustedFile(File file) {
10790            return new OriginInfo(file, null, false, false);
10791        }
10792
10793        static OriginInfo fromExistingFile(File file) {
10794            return new OriginInfo(file, null, false, true);
10795        }
10796
10797        static OriginInfo fromStagedFile(File file) {
10798            return new OriginInfo(file, null, true, false);
10799        }
10800
10801        static OriginInfo fromStagedContainer(String cid) {
10802            return new OriginInfo(null, cid, true, false);
10803        }
10804
10805        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10806            this.file = file;
10807            this.cid = cid;
10808            this.staged = staged;
10809            this.existing = existing;
10810
10811            if (cid != null) {
10812                resolvedPath = PackageHelper.getSdDir(cid);
10813                resolvedFile = new File(resolvedPath);
10814            } else if (file != null) {
10815                resolvedPath = file.getAbsolutePath();
10816                resolvedFile = file;
10817            } else {
10818                resolvedPath = null;
10819                resolvedFile = null;
10820            }
10821        }
10822    }
10823
10824    class MoveInfo {
10825        final int moveId;
10826        final String fromUuid;
10827        final String toUuid;
10828        final String packageName;
10829        final String dataAppName;
10830        final int appId;
10831        final String seinfo;
10832
10833        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10834                String dataAppName, int appId, String seinfo) {
10835            this.moveId = moveId;
10836            this.fromUuid = fromUuid;
10837            this.toUuid = toUuid;
10838            this.packageName = packageName;
10839            this.dataAppName = dataAppName;
10840            this.appId = appId;
10841            this.seinfo = seinfo;
10842        }
10843    }
10844
10845    class InstallParams extends HandlerParams {
10846        final OriginInfo origin;
10847        final MoveInfo move;
10848        final IPackageInstallObserver2 observer;
10849        int installFlags;
10850        final String installerPackageName;
10851        final String volumeUuid;
10852        final VerificationParams verificationParams;
10853        private InstallArgs mArgs;
10854        private int mRet;
10855        final String packageAbiOverride;
10856        final String[] grantedRuntimePermissions;
10857
10858        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10859                int installFlags, String installerPackageName, String volumeUuid,
10860                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10861                String[] grantedPermissions) {
10862            super(user);
10863            this.origin = origin;
10864            this.move = move;
10865            this.observer = observer;
10866            this.installFlags = installFlags;
10867            this.installerPackageName = installerPackageName;
10868            this.volumeUuid = volumeUuid;
10869            this.verificationParams = verificationParams;
10870            this.packageAbiOverride = packageAbiOverride;
10871            this.grantedRuntimePermissions = grantedPermissions;
10872        }
10873
10874        @Override
10875        public String toString() {
10876            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10877                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10878        }
10879
10880        public ManifestDigest getManifestDigest() {
10881            if (verificationParams == null) {
10882                return null;
10883            }
10884            return verificationParams.getManifestDigest();
10885        }
10886
10887        private int installLocationPolicy(PackageInfoLite pkgLite) {
10888            String packageName = pkgLite.packageName;
10889            int installLocation = pkgLite.installLocation;
10890            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10891            // reader
10892            synchronized (mPackages) {
10893                PackageParser.Package pkg = mPackages.get(packageName);
10894                if (pkg != null) {
10895                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10896                        // Check for downgrading.
10897                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10898                            try {
10899                                checkDowngrade(pkg, pkgLite);
10900                            } catch (PackageManagerException e) {
10901                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10902                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10903                            }
10904                        }
10905                        // Check for updated system application.
10906                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10907                            if (onSd) {
10908                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10909                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10910                            }
10911                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10912                        } else {
10913                            if (onSd) {
10914                                // Install flag overrides everything.
10915                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10916                            }
10917                            // If current upgrade specifies particular preference
10918                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10919                                // Application explicitly specified internal.
10920                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10921                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10922                                // App explictly prefers external. Let policy decide
10923                            } else {
10924                                // Prefer previous location
10925                                if (isExternal(pkg)) {
10926                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10927                                }
10928                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10929                            }
10930                        }
10931                    } else {
10932                        // Invalid install. Return error code
10933                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10934                    }
10935                }
10936            }
10937            // All the special cases have been taken care of.
10938            // Return result based on recommended install location.
10939            if (onSd) {
10940                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10941            }
10942            return pkgLite.recommendedInstallLocation;
10943        }
10944
10945        /*
10946         * Invoke remote method to get package information and install
10947         * location values. Override install location based on default
10948         * policy if needed and then create install arguments based
10949         * on the install location.
10950         */
10951        public void handleStartCopy() throws RemoteException {
10952            int ret = PackageManager.INSTALL_SUCCEEDED;
10953
10954            // If we're already staged, we've firmly committed to an install location
10955            if (origin.staged) {
10956                if (origin.file != null) {
10957                    installFlags |= PackageManager.INSTALL_INTERNAL;
10958                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10959                } else if (origin.cid != null) {
10960                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10961                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10962                } else {
10963                    throw new IllegalStateException("Invalid stage location");
10964                }
10965            }
10966
10967            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10968            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10969            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
10970            PackageInfoLite pkgLite = null;
10971
10972            if (onInt && onSd) {
10973                // Check if both bits are set.
10974                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10975                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10976            } else if (onSd && ephemeral) {
10977                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
10978                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10979            } else {
10980                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10981                        packageAbiOverride);
10982
10983                if (DEBUG_EPHEMERAL && ephemeral) {
10984                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
10985                }
10986
10987                /*
10988                 * If we have too little free space, try to free cache
10989                 * before giving up.
10990                 */
10991                if (!origin.staged && pkgLite.recommendedInstallLocation
10992                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10993                    // TODO: focus freeing disk space on the target device
10994                    final StorageManager storage = StorageManager.from(mContext);
10995                    final long lowThreshold = storage.getStorageLowBytes(
10996                            Environment.getDataDirectory());
10997
10998                    final long sizeBytes = mContainerService.calculateInstalledSize(
10999                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11000
11001                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11002                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11003                                installFlags, packageAbiOverride);
11004                    }
11005
11006                    /*
11007                     * The cache free must have deleted the file we
11008                     * downloaded to install.
11009                     *
11010                     * TODO: fix the "freeCache" call to not delete
11011                     *       the file we care about.
11012                     */
11013                    if (pkgLite.recommendedInstallLocation
11014                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11015                        pkgLite.recommendedInstallLocation
11016                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11017                    }
11018                }
11019            }
11020
11021            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11022                int loc = pkgLite.recommendedInstallLocation;
11023                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11024                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11025                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11026                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11027                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11028                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11029                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11030                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11031                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11032                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11033                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11034                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11035                } else {
11036                    // Override with defaults if needed.
11037                    loc = installLocationPolicy(pkgLite);
11038                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11039                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11040                    } else if (!onSd && !onInt) {
11041                        // Override install location with flags
11042                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11043                            // Set the flag to install on external media.
11044                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11045                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11046                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11047                            if (DEBUG_EPHEMERAL) {
11048                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11049                            }
11050                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11051                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11052                                    |PackageManager.INSTALL_INTERNAL);
11053                        } else {
11054                            // Make sure the flag for installing on external
11055                            // media is unset
11056                            installFlags |= PackageManager.INSTALL_INTERNAL;
11057                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11058                        }
11059                    }
11060                }
11061            }
11062
11063            final InstallArgs args = createInstallArgs(this);
11064            mArgs = args;
11065
11066            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11067                // TODO: http://b/22976637
11068                // Apps installed for "all" users use the device owner to verify the app
11069                UserHandle verifierUser = getUser();
11070                if (verifierUser == UserHandle.ALL) {
11071                    verifierUser = UserHandle.SYSTEM;
11072                }
11073
11074                /*
11075                 * Determine if we have any installed package verifiers. If we
11076                 * do, then we'll defer to them to verify the packages.
11077                 */
11078                final int requiredUid = mRequiredVerifierPackage == null ? -1
11079                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11080                if (!origin.existing && requiredUid != -1
11081                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11082                    final Intent verification = new Intent(
11083                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11084                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11085                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11086                            PACKAGE_MIME_TYPE);
11087                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11088
11089                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11090                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11091                            verifierUser.getIdentifier());
11092
11093                    if (DEBUG_VERIFY) {
11094                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11095                                + verification.toString() + " with " + pkgLite.verifiers.length
11096                                + " optional verifiers");
11097                    }
11098
11099                    final int verificationId = mPendingVerificationToken++;
11100
11101                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11102
11103                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11104                            installerPackageName);
11105
11106                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11107                            installFlags);
11108
11109                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11110                            pkgLite.packageName);
11111
11112                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11113                            pkgLite.versionCode);
11114
11115                    if (verificationParams != null) {
11116                        if (verificationParams.getVerificationURI() != null) {
11117                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11118                                 verificationParams.getVerificationURI());
11119                        }
11120                        if (verificationParams.getOriginatingURI() != null) {
11121                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11122                                  verificationParams.getOriginatingURI());
11123                        }
11124                        if (verificationParams.getReferrer() != null) {
11125                            verification.putExtra(Intent.EXTRA_REFERRER,
11126                                  verificationParams.getReferrer());
11127                        }
11128                        if (verificationParams.getOriginatingUid() >= 0) {
11129                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11130                                  verificationParams.getOriginatingUid());
11131                        }
11132                        if (verificationParams.getInstallerUid() >= 0) {
11133                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11134                                  verificationParams.getInstallerUid());
11135                        }
11136                    }
11137
11138                    final PackageVerificationState verificationState = new PackageVerificationState(
11139                            requiredUid, args);
11140
11141                    mPendingVerification.append(verificationId, verificationState);
11142
11143                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11144                            receivers, verificationState);
11145
11146                    /*
11147                     * If any sufficient verifiers were listed in the package
11148                     * manifest, attempt to ask them.
11149                     */
11150                    if (sufficientVerifiers != null) {
11151                        final int N = sufficientVerifiers.size();
11152                        if (N == 0) {
11153                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11154                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11155                        } else {
11156                            for (int i = 0; i < N; i++) {
11157                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11158
11159                                final Intent sufficientIntent = new Intent(verification);
11160                                sufficientIntent.setComponent(verifierComponent);
11161                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11162                            }
11163                        }
11164                    }
11165
11166                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11167                            mRequiredVerifierPackage, receivers);
11168                    if (ret == PackageManager.INSTALL_SUCCEEDED
11169                            && mRequiredVerifierPackage != null) {
11170                        Trace.asyncTraceBegin(
11171                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11172                        /*
11173                         * Send the intent to the required verification agent,
11174                         * but only start the verification timeout after the
11175                         * target BroadcastReceivers have run.
11176                         */
11177                        verification.setComponent(requiredVerifierComponent);
11178                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11179                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11180                                new BroadcastReceiver() {
11181                                    @Override
11182                                    public void onReceive(Context context, Intent intent) {
11183                                        final Message msg = mHandler
11184                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11185                                        msg.arg1 = verificationId;
11186                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11187                                    }
11188                                }, null, 0, null, null);
11189
11190                        /*
11191                         * We don't want the copy to proceed until verification
11192                         * succeeds, so null out this field.
11193                         */
11194                        mArgs = null;
11195                    }
11196                } else {
11197                    /*
11198                     * No package verification is enabled, so immediately start
11199                     * the remote call to initiate copy using temporary file.
11200                     */
11201                    ret = args.copyApk(mContainerService, true);
11202                }
11203            }
11204
11205            mRet = ret;
11206        }
11207
11208        @Override
11209        void handleReturnCode() {
11210            // If mArgs is null, then MCS couldn't be reached. When it
11211            // reconnects, it will try again to install. At that point, this
11212            // will succeed.
11213            if (mArgs != null) {
11214                processPendingInstall(mArgs, mRet);
11215            }
11216        }
11217
11218        @Override
11219        void handleServiceError() {
11220            mArgs = createInstallArgs(this);
11221            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11222        }
11223
11224        public boolean isForwardLocked() {
11225            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11226        }
11227    }
11228
11229    /**
11230     * Used during creation of InstallArgs
11231     *
11232     * @param installFlags package installation flags
11233     * @return true if should be installed on external storage
11234     */
11235    private static boolean installOnExternalAsec(int installFlags) {
11236        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11237            return false;
11238        }
11239        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11240            return true;
11241        }
11242        return false;
11243    }
11244
11245    /**
11246     * Used during creation of InstallArgs
11247     *
11248     * @param installFlags package installation flags
11249     * @return true if should be installed as forward locked
11250     */
11251    private static boolean installForwardLocked(int installFlags) {
11252        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11253    }
11254
11255    private InstallArgs createInstallArgs(InstallParams params) {
11256        if (params.move != null) {
11257            return new MoveInstallArgs(params);
11258        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11259            return new AsecInstallArgs(params);
11260        } else {
11261            return new FileInstallArgs(params);
11262        }
11263    }
11264
11265    /**
11266     * Create args that describe an existing installed package. Typically used
11267     * when cleaning up old installs, or used as a move source.
11268     */
11269    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11270            String resourcePath, String[] instructionSets) {
11271        final boolean isInAsec;
11272        if (installOnExternalAsec(installFlags)) {
11273            /* Apps on SD card are always in ASEC containers. */
11274            isInAsec = true;
11275        } else if (installForwardLocked(installFlags)
11276                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11277            /*
11278             * Forward-locked apps are only in ASEC containers if they're the
11279             * new style
11280             */
11281            isInAsec = true;
11282        } else {
11283            isInAsec = false;
11284        }
11285
11286        if (isInAsec) {
11287            return new AsecInstallArgs(codePath, instructionSets,
11288                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11289        } else {
11290            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11291        }
11292    }
11293
11294    static abstract class InstallArgs {
11295        /** @see InstallParams#origin */
11296        final OriginInfo origin;
11297        /** @see InstallParams#move */
11298        final MoveInfo move;
11299
11300        final IPackageInstallObserver2 observer;
11301        // Always refers to PackageManager flags only
11302        final int installFlags;
11303        final String installerPackageName;
11304        final String volumeUuid;
11305        final ManifestDigest manifestDigest;
11306        final UserHandle user;
11307        final String abiOverride;
11308        final String[] installGrantPermissions;
11309        /** If non-null, drop an async trace when the install completes */
11310        final String traceMethod;
11311        final int traceCookie;
11312
11313        // The list of instruction sets supported by this app. This is currently
11314        // only used during the rmdex() phase to clean up resources. We can get rid of this
11315        // if we move dex files under the common app path.
11316        /* nullable */ String[] instructionSets;
11317
11318        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11319                int installFlags, String installerPackageName, String volumeUuid,
11320                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11321                String abiOverride, String[] installGrantPermissions,
11322                String traceMethod, int traceCookie) {
11323            this.origin = origin;
11324            this.move = move;
11325            this.installFlags = installFlags;
11326            this.observer = observer;
11327            this.installerPackageName = installerPackageName;
11328            this.volumeUuid = volumeUuid;
11329            this.manifestDigest = manifestDigest;
11330            this.user = user;
11331            this.instructionSets = instructionSets;
11332            this.abiOverride = abiOverride;
11333            this.installGrantPermissions = installGrantPermissions;
11334            this.traceMethod = traceMethod;
11335            this.traceCookie = traceCookie;
11336        }
11337
11338        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11339        abstract int doPreInstall(int status);
11340
11341        /**
11342         * Rename package into final resting place. All paths on the given
11343         * scanned package should be updated to reflect the rename.
11344         */
11345        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11346        abstract int doPostInstall(int status, int uid);
11347
11348        /** @see PackageSettingBase#codePathString */
11349        abstract String getCodePath();
11350        /** @see PackageSettingBase#resourcePathString */
11351        abstract String getResourcePath();
11352
11353        // Need installer lock especially for dex file removal.
11354        abstract void cleanUpResourcesLI();
11355        abstract boolean doPostDeleteLI(boolean delete);
11356
11357        /**
11358         * Called before the source arguments are copied. This is used mostly
11359         * for MoveParams when it needs to read the source file to put it in the
11360         * destination.
11361         */
11362        int doPreCopy() {
11363            return PackageManager.INSTALL_SUCCEEDED;
11364        }
11365
11366        /**
11367         * Called after the source arguments are copied. This is used mostly for
11368         * MoveParams when it needs to read the source file to put it in the
11369         * destination.
11370         *
11371         * @return
11372         */
11373        int doPostCopy(int uid) {
11374            return PackageManager.INSTALL_SUCCEEDED;
11375        }
11376
11377        protected boolean isFwdLocked() {
11378            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11379        }
11380
11381        protected boolean isExternalAsec() {
11382            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11383        }
11384
11385        protected boolean isEphemeral() {
11386            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11387        }
11388
11389        UserHandle getUser() {
11390            return user;
11391        }
11392    }
11393
11394    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11395        if (!allCodePaths.isEmpty()) {
11396            if (instructionSets == null) {
11397                throw new IllegalStateException("instructionSet == null");
11398            }
11399            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11400            for (String codePath : allCodePaths) {
11401                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11402                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11403                    if (retCode < 0) {
11404                        Slog.w(TAG, "Couldn't remove dex file for package: "
11405                                + " at location " + codePath + ", retcode=" + retCode);
11406                        // we don't consider this to be a failure of the core package deletion
11407                    }
11408                }
11409            }
11410        }
11411    }
11412
11413    /**
11414     * Logic to handle installation of non-ASEC applications, including copying
11415     * and renaming logic.
11416     */
11417    class FileInstallArgs extends InstallArgs {
11418        private File codeFile;
11419        private File resourceFile;
11420
11421        // Example topology:
11422        // /data/app/com.example/base.apk
11423        // /data/app/com.example/split_foo.apk
11424        // /data/app/com.example/lib/arm/libfoo.so
11425        // /data/app/com.example/lib/arm64/libfoo.so
11426        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11427
11428        /** New install */
11429        FileInstallArgs(InstallParams params) {
11430            super(params.origin, params.move, params.observer, params.installFlags,
11431                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11432                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11433                    params.grantedRuntimePermissions,
11434                    params.traceMethod, params.traceCookie);
11435            if (isFwdLocked()) {
11436                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11437            }
11438        }
11439
11440        /** Existing install */
11441        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11442            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11443                    null, null, null, 0);
11444            this.codeFile = (codePath != null) ? new File(codePath) : null;
11445            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11446        }
11447
11448        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11449            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11450            try {
11451                return doCopyApk(imcs, temp);
11452            } finally {
11453                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11454            }
11455        }
11456
11457        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11458            if (origin.staged) {
11459                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11460                codeFile = origin.file;
11461                resourceFile = origin.file;
11462                return PackageManager.INSTALL_SUCCEEDED;
11463            }
11464
11465            try {
11466                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11467                final File tempDir =
11468                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11469                codeFile = tempDir;
11470                resourceFile = tempDir;
11471            } catch (IOException e) {
11472                Slog.w(TAG, "Failed to create copy file: " + e);
11473                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11474            }
11475
11476            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11477                @Override
11478                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11479                    if (!FileUtils.isValidExtFilename(name)) {
11480                        throw new IllegalArgumentException("Invalid filename: " + name);
11481                    }
11482                    try {
11483                        final File file = new File(codeFile, name);
11484                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11485                                O_RDWR | O_CREAT, 0644);
11486                        Os.chmod(file.getAbsolutePath(), 0644);
11487                        return new ParcelFileDescriptor(fd);
11488                    } catch (ErrnoException e) {
11489                        throw new RemoteException("Failed to open: " + e.getMessage());
11490                    }
11491                }
11492            };
11493
11494            int ret = PackageManager.INSTALL_SUCCEEDED;
11495            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11496            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11497                Slog.e(TAG, "Failed to copy package");
11498                return ret;
11499            }
11500
11501            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11502            NativeLibraryHelper.Handle handle = null;
11503            try {
11504                handle = NativeLibraryHelper.Handle.create(codeFile);
11505                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11506                        abiOverride);
11507            } catch (IOException e) {
11508                Slog.e(TAG, "Copying native libraries failed", e);
11509                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11510            } finally {
11511                IoUtils.closeQuietly(handle);
11512            }
11513
11514            return ret;
11515        }
11516
11517        int doPreInstall(int status) {
11518            if (status != PackageManager.INSTALL_SUCCEEDED) {
11519                cleanUp();
11520            }
11521            return status;
11522        }
11523
11524        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11525            if (status != PackageManager.INSTALL_SUCCEEDED) {
11526                cleanUp();
11527                return false;
11528            }
11529
11530            final File targetDir = codeFile.getParentFile();
11531            final File beforeCodeFile = codeFile;
11532            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11533
11534            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11535            try {
11536                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11537            } catch (ErrnoException e) {
11538                Slog.w(TAG, "Failed to rename", e);
11539                return false;
11540            }
11541
11542            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11543                Slog.w(TAG, "Failed to restorecon");
11544                return false;
11545            }
11546
11547            // Reflect the rename internally
11548            codeFile = afterCodeFile;
11549            resourceFile = afterCodeFile;
11550
11551            // Reflect the rename in scanned details
11552            pkg.codePath = afterCodeFile.getAbsolutePath();
11553            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11554                    pkg.baseCodePath);
11555            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11556                    pkg.splitCodePaths);
11557
11558            // Reflect the rename in app info
11559            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11560            pkg.applicationInfo.setCodePath(pkg.codePath);
11561            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11562            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11563            pkg.applicationInfo.setResourcePath(pkg.codePath);
11564            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11565            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11566
11567            return true;
11568        }
11569
11570        int doPostInstall(int status, int uid) {
11571            if (status != PackageManager.INSTALL_SUCCEEDED) {
11572                cleanUp();
11573            }
11574            return status;
11575        }
11576
11577        @Override
11578        String getCodePath() {
11579            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11580        }
11581
11582        @Override
11583        String getResourcePath() {
11584            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11585        }
11586
11587        private boolean cleanUp() {
11588            if (codeFile == null || !codeFile.exists()) {
11589                return false;
11590            }
11591
11592            if (codeFile.isDirectory()) {
11593                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11594            } else {
11595                codeFile.delete();
11596            }
11597
11598            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11599                resourceFile.delete();
11600            }
11601
11602            return true;
11603        }
11604
11605        void cleanUpResourcesLI() {
11606            // Try enumerating all code paths before deleting
11607            List<String> allCodePaths = Collections.EMPTY_LIST;
11608            if (codeFile != null && codeFile.exists()) {
11609                try {
11610                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11611                    allCodePaths = pkg.getAllCodePaths();
11612                } catch (PackageParserException e) {
11613                    // Ignored; we tried our best
11614                }
11615            }
11616
11617            cleanUp();
11618            removeDexFiles(allCodePaths, instructionSets);
11619        }
11620
11621        boolean doPostDeleteLI(boolean delete) {
11622            // XXX err, shouldn't we respect the delete flag?
11623            cleanUpResourcesLI();
11624            return true;
11625        }
11626    }
11627
11628    private boolean isAsecExternal(String cid) {
11629        final String asecPath = PackageHelper.getSdFilesystem(cid);
11630        return !asecPath.startsWith(mAsecInternalPath);
11631    }
11632
11633    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11634            PackageManagerException {
11635        if (copyRet < 0) {
11636            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11637                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11638                throw new PackageManagerException(copyRet, message);
11639            }
11640        }
11641    }
11642
11643    /**
11644     * Extract the MountService "container ID" from the full code path of an
11645     * .apk.
11646     */
11647    static String cidFromCodePath(String fullCodePath) {
11648        int eidx = fullCodePath.lastIndexOf("/");
11649        String subStr1 = fullCodePath.substring(0, eidx);
11650        int sidx = subStr1.lastIndexOf("/");
11651        return subStr1.substring(sidx+1, eidx);
11652    }
11653
11654    /**
11655     * Logic to handle installation of ASEC applications, including copying and
11656     * renaming logic.
11657     */
11658    class AsecInstallArgs extends InstallArgs {
11659        static final String RES_FILE_NAME = "pkg.apk";
11660        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11661
11662        String cid;
11663        String packagePath;
11664        String resourcePath;
11665
11666        /** New install */
11667        AsecInstallArgs(InstallParams params) {
11668            super(params.origin, params.move, params.observer, params.installFlags,
11669                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11670                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11671                    params.grantedRuntimePermissions,
11672                    params.traceMethod, params.traceCookie);
11673        }
11674
11675        /** Existing install */
11676        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11677                        boolean isExternal, boolean isForwardLocked) {
11678            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11679                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11680                    instructionSets, null, null, null, 0);
11681            // Hackily pretend we're still looking at a full code path
11682            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11683                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11684            }
11685
11686            // Extract cid from fullCodePath
11687            int eidx = fullCodePath.lastIndexOf("/");
11688            String subStr1 = fullCodePath.substring(0, eidx);
11689            int sidx = subStr1.lastIndexOf("/");
11690            cid = subStr1.substring(sidx+1, eidx);
11691            setMountPath(subStr1);
11692        }
11693
11694        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11695            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11696                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11697                    instructionSets, null, null, null, 0);
11698            this.cid = cid;
11699            setMountPath(PackageHelper.getSdDir(cid));
11700        }
11701
11702        void createCopyFile() {
11703            cid = mInstallerService.allocateExternalStageCidLegacy();
11704        }
11705
11706        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11707            if (origin.staged && origin.cid != null) {
11708                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11709                cid = origin.cid;
11710                setMountPath(PackageHelper.getSdDir(cid));
11711                return PackageManager.INSTALL_SUCCEEDED;
11712            }
11713
11714            if (temp) {
11715                createCopyFile();
11716            } else {
11717                /*
11718                 * Pre-emptively destroy the container since it's destroyed if
11719                 * copying fails due to it existing anyway.
11720                 */
11721                PackageHelper.destroySdDir(cid);
11722            }
11723
11724            final String newMountPath = imcs.copyPackageToContainer(
11725                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11726                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11727
11728            if (newMountPath != null) {
11729                setMountPath(newMountPath);
11730                return PackageManager.INSTALL_SUCCEEDED;
11731            } else {
11732                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11733            }
11734        }
11735
11736        @Override
11737        String getCodePath() {
11738            return packagePath;
11739        }
11740
11741        @Override
11742        String getResourcePath() {
11743            return resourcePath;
11744        }
11745
11746        int doPreInstall(int status) {
11747            if (status != PackageManager.INSTALL_SUCCEEDED) {
11748                // Destroy container
11749                PackageHelper.destroySdDir(cid);
11750            } else {
11751                boolean mounted = PackageHelper.isContainerMounted(cid);
11752                if (!mounted) {
11753                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11754                            Process.SYSTEM_UID);
11755                    if (newMountPath != null) {
11756                        setMountPath(newMountPath);
11757                    } else {
11758                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11759                    }
11760                }
11761            }
11762            return status;
11763        }
11764
11765        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11766            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11767            String newMountPath = null;
11768            if (PackageHelper.isContainerMounted(cid)) {
11769                // Unmount the container
11770                if (!PackageHelper.unMountSdDir(cid)) {
11771                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11772                    return false;
11773                }
11774            }
11775            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11776                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11777                        " which might be stale. Will try to clean up.");
11778                // Clean up the stale container and proceed to recreate.
11779                if (!PackageHelper.destroySdDir(newCacheId)) {
11780                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11781                    return false;
11782                }
11783                // Successfully cleaned up stale container. Try to rename again.
11784                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11785                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11786                            + " inspite of cleaning it up.");
11787                    return false;
11788                }
11789            }
11790            if (!PackageHelper.isContainerMounted(newCacheId)) {
11791                Slog.w(TAG, "Mounting container " + newCacheId);
11792                newMountPath = PackageHelper.mountSdDir(newCacheId,
11793                        getEncryptKey(), Process.SYSTEM_UID);
11794            } else {
11795                newMountPath = PackageHelper.getSdDir(newCacheId);
11796            }
11797            if (newMountPath == null) {
11798                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11799                return false;
11800            }
11801            Log.i(TAG, "Succesfully renamed " + cid +
11802                    " to " + newCacheId +
11803                    " at new path: " + newMountPath);
11804            cid = newCacheId;
11805
11806            final File beforeCodeFile = new File(packagePath);
11807            setMountPath(newMountPath);
11808            final File afterCodeFile = new File(packagePath);
11809
11810            // Reflect the rename in scanned details
11811            pkg.codePath = afterCodeFile.getAbsolutePath();
11812            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11813                    pkg.baseCodePath);
11814            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11815                    pkg.splitCodePaths);
11816
11817            // Reflect the rename in app info
11818            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11819            pkg.applicationInfo.setCodePath(pkg.codePath);
11820            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11821            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11822            pkg.applicationInfo.setResourcePath(pkg.codePath);
11823            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11824            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11825
11826            return true;
11827        }
11828
11829        private void setMountPath(String mountPath) {
11830            final File mountFile = new File(mountPath);
11831
11832            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11833            if (monolithicFile.exists()) {
11834                packagePath = monolithicFile.getAbsolutePath();
11835                if (isFwdLocked()) {
11836                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11837                } else {
11838                    resourcePath = packagePath;
11839                }
11840            } else {
11841                packagePath = mountFile.getAbsolutePath();
11842                resourcePath = packagePath;
11843            }
11844        }
11845
11846        int doPostInstall(int status, int uid) {
11847            if (status != PackageManager.INSTALL_SUCCEEDED) {
11848                cleanUp();
11849            } else {
11850                final int groupOwner;
11851                final String protectedFile;
11852                if (isFwdLocked()) {
11853                    groupOwner = UserHandle.getSharedAppGid(uid);
11854                    protectedFile = RES_FILE_NAME;
11855                } else {
11856                    groupOwner = -1;
11857                    protectedFile = null;
11858                }
11859
11860                if (uid < Process.FIRST_APPLICATION_UID
11861                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11862                    Slog.e(TAG, "Failed to finalize " + cid);
11863                    PackageHelper.destroySdDir(cid);
11864                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11865                }
11866
11867                boolean mounted = PackageHelper.isContainerMounted(cid);
11868                if (!mounted) {
11869                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11870                }
11871            }
11872            return status;
11873        }
11874
11875        private void cleanUp() {
11876            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11877
11878            // Destroy secure container
11879            PackageHelper.destroySdDir(cid);
11880        }
11881
11882        private List<String> getAllCodePaths() {
11883            final File codeFile = new File(getCodePath());
11884            if (codeFile != null && codeFile.exists()) {
11885                try {
11886                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11887                    return pkg.getAllCodePaths();
11888                } catch (PackageParserException e) {
11889                    // Ignored; we tried our best
11890                }
11891            }
11892            return Collections.EMPTY_LIST;
11893        }
11894
11895        void cleanUpResourcesLI() {
11896            // Enumerate all code paths before deleting
11897            cleanUpResourcesLI(getAllCodePaths());
11898        }
11899
11900        private void cleanUpResourcesLI(List<String> allCodePaths) {
11901            cleanUp();
11902            removeDexFiles(allCodePaths, instructionSets);
11903        }
11904
11905        String getPackageName() {
11906            return getAsecPackageName(cid);
11907        }
11908
11909        boolean doPostDeleteLI(boolean delete) {
11910            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11911            final List<String> allCodePaths = getAllCodePaths();
11912            boolean mounted = PackageHelper.isContainerMounted(cid);
11913            if (mounted) {
11914                // Unmount first
11915                if (PackageHelper.unMountSdDir(cid)) {
11916                    mounted = false;
11917                }
11918            }
11919            if (!mounted && delete) {
11920                cleanUpResourcesLI(allCodePaths);
11921            }
11922            return !mounted;
11923        }
11924
11925        @Override
11926        int doPreCopy() {
11927            if (isFwdLocked()) {
11928                if (!PackageHelper.fixSdPermissions(cid,
11929                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11930                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11931                }
11932            }
11933
11934            return PackageManager.INSTALL_SUCCEEDED;
11935        }
11936
11937        @Override
11938        int doPostCopy(int uid) {
11939            if (isFwdLocked()) {
11940                if (uid < Process.FIRST_APPLICATION_UID
11941                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11942                                RES_FILE_NAME)) {
11943                    Slog.e(TAG, "Failed to finalize " + cid);
11944                    PackageHelper.destroySdDir(cid);
11945                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11946                }
11947            }
11948
11949            return PackageManager.INSTALL_SUCCEEDED;
11950        }
11951    }
11952
11953    /**
11954     * Logic to handle movement of existing installed applications.
11955     */
11956    class MoveInstallArgs extends InstallArgs {
11957        private File codeFile;
11958        private File resourceFile;
11959
11960        /** New install */
11961        MoveInstallArgs(InstallParams params) {
11962            super(params.origin, params.move, params.observer, params.installFlags,
11963                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11964                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11965                    params.grantedRuntimePermissions,
11966                    params.traceMethod, params.traceCookie);
11967        }
11968
11969        int copyApk(IMediaContainerService imcs, boolean temp) {
11970            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11971                    + move.fromUuid + " to " + move.toUuid);
11972            synchronized (mInstaller) {
11973                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11974                        move.dataAppName, move.appId, move.seinfo) != 0) {
11975                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11976                }
11977            }
11978
11979            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11980            resourceFile = codeFile;
11981            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11982
11983            return PackageManager.INSTALL_SUCCEEDED;
11984        }
11985
11986        int doPreInstall(int status) {
11987            if (status != PackageManager.INSTALL_SUCCEEDED) {
11988                cleanUp(move.toUuid);
11989            }
11990            return status;
11991        }
11992
11993        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11994            if (status != PackageManager.INSTALL_SUCCEEDED) {
11995                cleanUp(move.toUuid);
11996                return false;
11997            }
11998
11999            // Reflect the move in app info
12000            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12001            pkg.applicationInfo.setCodePath(pkg.codePath);
12002            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12003            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12004            pkg.applicationInfo.setResourcePath(pkg.codePath);
12005            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12006            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12007
12008            return true;
12009        }
12010
12011        int doPostInstall(int status, int uid) {
12012            if (status == PackageManager.INSTALL_SUCCEEDED) {
12013                cleanUp(move.fromUuid);
12014            } else {
12015                cleanUp(move.toUuid);
12016            }
12017            return status;
12018        }
12019
12020        @Override
12021        String getCodePath() {
12022            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12023        }
12024
12025        @Override
12026        String getResourcePath() {
12027            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12028        }
12029
12030        private boolean cleanUp(String volumeUuid) {
12031            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12032                    move.dataAppName);
12033            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12034            synchronized (mInstallLock) {
12035                // Clean up both app data and code
12036                removeDataDirsLI(volumeUuid, move.packageName);
12037                if (codeFile.isDirectory()) {
12038                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12039                } else {
12040                    codeFile.delete();
12041                }
12042            }
12043            return true;
12044        }
12045
12046        void cleanUpResourcesLI() {
12047            throw new UnsupportedOperationException();
12048        }
12049
12050        boolean doPostDeleteLI(boolean delete) {
12051            throw new UnsupportedOperationException();
12052        }
12053    }
12054
12055    static String getAsecPackageName(String packageCid) {
12056        int idx = packageCid.lastIndexOf("-");
12057        if (idx == -1) {
12058            return packageCid;
12059        }
12060        return packageCid.substring(0, idx);
12061    }
12062
12063    // Utility method used to create code paths based on package name and available index.
12064    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12065        String idxStr = "";
12066        int idx = 1;
12067        // Fall back to default value of idx=1 if prefix is not
12068        // part of oldCodePath
12069        if (oldCodePath != null) {
12070            String subStr = oldCodePath;
12071            // Drop the suffix right away
12072            if (suffix != null && subStr.endsWith(suffix)) {
12073                subStr = subStr.substring(0, subStr.length() - suffix.length());
12074            }
12075            // If oldCodePath already contains prefix find out the
12076            // ending index to either increment or decrement.
12077            int sidx = subStr.lastIndexOf(prefix);
12078            if (sidx != -1) {
12079                subStr = subStr.substring(sidx + prefix.length());
12080                if (subStr != null) {
12081                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12082                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12083                    }
12084                    try {
12085                        idx = Integer.parseInt(subStr);
12086                        if (idx <= 1) {
12087                            idx++;
12088                        } else {
12089                            idx--;
12090                        }
12091                    } catch(NumberFormatException e) {
12092                    }
12093                }
12094            }
12095        }
12096        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12097        return prefix + idxStr;
12098    }
12099
12100    private File getNextCodePath(File targetDir, String packageName) {
12101        int suffix = 1;
12102        File result;
12103        do {
12104            result = new File(targetDir, packageName + "-" + suffix);
12105            suffix++;
12106        } while (result.exists());
12107        return result;
12108    }
12109
12110    // Utility method that returns the relative package path with respect
12111    // to the installation directory. Like say for /data/data/com.test-1.apk
12112    // string com.test-1 is returned.
12113    static String deriveCodePathName(String codePath) {
12114        if (codePath == null) {
12115            return null;
12116        }
12117        final File codeFile = new File(codePath);
12118        final String name = codeFile.getName();
12119        if (codeFile.isDirectory()) {
12120            return name;
12121        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12122            final int lastDot = name.lastIndexOf('.');
12123            return name.substring(0, lastDot);
12124        } else {
12125            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12126            return null;
12127        }
12128    }
12129
12130    class PackageInstalledInfo {
12131        String name;
12132        int uid;
12133        // The set of users that originally had this package installed.
12134        int[] origUsers;
12135        // The set of users that now have this package installed.
12136        int[] newUsers;
12137        PackageParser.Package pkg;
12138        int returnCode;
12139        String returnMsg;
12140        PackageRemovedInfo removedInfo;
12141
12142        public void setError(int code, String msg) {
12143            returnCode = code;
12144            returnMsg = msg;
12145            Slog.w(TAG, msg);
12146        }
12147
12148        public void setError(String msg, PackageParserException e) {
12149            returnCode = e.error;
12150            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12151            Slog.w(TAG, msg, e);
12152        }
12153
12154        public void setError(String msg, PackageManagerException e) {
12155            returnCode = e.error;
12156            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12157            Slog.w(TAG, msg, e);
12158        }
12159
12160        // In some error cases we want to convey more info back to the observer
12161        String origPackage;
12162        String origPermission;
12163    }
12164
12165    /*
12166     * Install a non-existing package.
12167     */
12168    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12169            UserHandle user, String installerPackageName, String volumeUuid,
12170            PackageInstalledInfo res) {
12171        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12172
12173        // Remember this for later, in case we need to rollback this install
12174        String pkgName = pkg.packageName;
12175
12176        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12177        // TODO: b/23350563
12178        final boolean dataDirExists = Environment
12179                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12180
12181        synchronized(mPackages) {
12182            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12183                // A package with the same name is already installed, though
12184                // it has been renamed to an older name.  The package we
12185                // are trying to install should be installed as an update to
12186                // the existing one, but that has not been requested, so bail.
12187                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12188                        + " without first uninstalling package running as "
12189                        + mSettings.mRenamedPackages.get(pkgName));
12190                return;
12191            }
12192            if (mPackages.containsKey(pkgName)) {
12193                // Don't allow installation over an existing package with the same name.
12194                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12195                        + " without first uninstalling.");
12196                return;
12197            }
12198        }
12199
12200        try {
12201            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12202                    System.currentTimeMillis(), user);
12203
12204            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12205            // delete the partially installed application. the data directory will have to be
12206            // restored if it was already existing
12207            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12208                // remove package from internal structures.  Note that we want deletePackageX to
12209                // delete the package data and cache directories that it created in
12210                // scanPackageLocked, unless those directories existed before we even tried to
12211                // install.
12212                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12213                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12214                                res.removedInfo, true);
12215            }
12216
12217        } catch (PackageManagerException e) {
12218            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12219        }
12220
12221        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12222    }
12223
12224    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12225        // Can't rotate keys during boot or if sharedUser.
12226        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12227                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12228            return false;
12229        }
12230        // app is using upgradeKeySets; make sure all are valid
12231        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12232        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12233        for (int i = 0; i < upgradeKeySets.length; i++) {
12234            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12235                Slog.wtf(TAG, "Package "
12236                         + (oldPs.name != null ? oldPs.name : "<null>")
12237                         + " contains upgrade-key-set reference to unknown key-set: "
12238                         + upgradeKeySets[i]
12239                         + " reverting to signatures check.");
12240                return false;
12241            }
12242        }
12243        return true;
12244    }
12245
12246    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12247        // Upgrade keysets are being used.  Determine if new package has a superset of the
12248        // required keys.
12249        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12250        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12251        for (int i = 0; i < upgradeKeySets.length; i++) {
12252            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12253            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12254                return true;
12255            }
12256        }
12257        return false;
12258    }
12259
12260    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12261            UserHandle user, String installerPackageName, String volumeUuid,
12262            PackageInstalledInfo res) {
12263        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12264
12265        final PackageParser.Package oldPackage;
12266        final String pkgName = pkg.packageName;
12267        final int[] allUsers;
12268        final boolean[] perUserInstalled;
12269
12270        // First find the old package info and check signatures
12271        synchronized(mPackages) {
12272            oldPackage = mPackages.get(pkgName);
12273            final boolean oldIsEphemeral
12274                    = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_EPHEMERAL) != 0);
12275            if (isEphemeral && !oldIsEphemeral) {
12276                // can't downgrade from full to ephemeral
12277                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12278                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12279                return;
12280            }
12281            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12282            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12283            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12284                if(!checkUpgradeKeySetLP(ps, pkg)) {
12285                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12286                            "New package not signed by keys specified by upgrade-keysets: "
12287                            + pkgName);
12288                    return;
12289                }
12290            } else {
12291                // default to original signature matching
12292                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12293                    != PackageManager.SIGNATURE_MATCH) {
12294                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12295                            "New package has a different signature: " + pkgName);
12296                    return;
12297                }
12298            }
12299
12300            // In case of rollback, remember per-user/profile install state
12301            allUsers = sUserManager.getUserIds();
12302            perUserInstalled = new boolean[allUsers.length];
12303            for (int i = 0; i < allUsers.length; i++) {
12304                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12305            }
12306        }
12307
12308        boolean sysPkg = (isSystemApp(oldPackage));
12309        if (sysPkg) {
12310            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12311                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12312        } else {
12313            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12314                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12315        }
12316    }
12317
12318    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12319            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12320            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12321            String volumeUuid, PackageInstalledInfo res) {
12322        String pkgName = deletedPackage.packageName;
12323        boolean deletedPkg = true;
12324        boolean updatedSettings = false;
12325
12326        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12327                + deletedPackage);
12328        long origUpdateTime;
12329        if (pkg.mExtras != null) {
12330            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12331        } else {
12332            origUpdateTime = 0;
12333        }
12334
12335        // First delete the existing package while retaining the data directory
12336        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12337                res.removedInfo, true)) {
12338            // If the existing package wasn't successfully deleted
12339            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12340            deletedPkg = false;
12341        } else {
12342            // Successfully deleted the old package; proceed with replace.
12343
12344            // If deleted package lived in a container, give users a chance to
12345            // relinquish resources before killing.
12346            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12347                if (DEBUG_INSTALL) {
12348                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12349                }
12350                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12351                final ArrayList<String> pkgList = new ArrayList<String>(1);
12352                pkgList.add(deletedPackage.applicationInfo.packageName);
12353                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12354            }
12355
12356            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12357            try {
12358                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12359                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12360                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12361                        perUserInstalled, res, user);
12362                updatedSettings = true;
12363            } catch (PackageManagerException e) {
12364                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12365            }
12366        }
12367
12368        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12369            // remove package from internal structures.  Note that we want deletePackageX to
12370            // delete the package data and cache directories that it created in
12371            // scanPackageLocked, unless those directories existed before we even tried to
12372            // install.
12373            if(updatedSettings) {
12374                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12375                deletePackageLI(
12376                        pkgName, null, true, allUsers, perUserInstalled,
12377                        PackageManager.DELETE_KEEP_DATA,
12378                                res.removedInfo, true);
12379            }
12380            // Since we failed to install the new package we need to restore the old
12381            // package that we deleted.
12382            if (deletedPkg) {
12383                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12384                File restoreFile = new File(deletedPackage.codePath);
12385                // Parse old package
12386                boolean oldExternal = isExternal(deletedPackage);
12387                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12388                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12389                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12390                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12391                try {
12392                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12393                            null);
12394                } catch (PackageManagerException e) {
12395                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12396                            + e.getMessage());
12397                    return;
12398                }
12399                // Restore of old package succeeded. Update permissions.
12400                // writer
12401                synchronized (mPackages) {
12402                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12403                            UPDATE_PERMISSIONS_ALL);
12404                    // can downgrade to reader
12405                    mSettings.writeLPr();
12406                }
12407                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12408            }
12409        }
12410    }
12411
12412    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12413            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12414            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12415            String volumeUuid, PackageInstalledInfo res) {
12416        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12417                + ", old=" + deletedPackage);
12418        boolean disabledSystem = false;
12419        boolean updatedSettings = false;
12420        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12421        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12422                != 0) {
12423            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12424        }
12425        String packageName = deletedPackage.packageName;
12426        if (packageName == null) {
12427            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12428                    "Attempt to delete null packageName.");
12429            return;
12430        }
12431        PackageParser.Package oldPkg;
12432        PackageSetting oldPkgSetting;
12433        // reader
12434        synchronized (mPackages) {
12435            oldPkg = mPackages.get(packageName);
12436            oldPkgSetting = mSettings.mPackages.get(packageName);
12437            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12438                    (oldPkgSetting == null)) {
12439                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12440                        "Couldn't find package:" + packageName + " information");
12441                return;
12442            }
12443        }
12444
12445        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12446
12447        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12448        res.removedInfo.removedPackage = packageName;
12449        // Remove existing system package
12450        removePackageLI(oldPkgSetting, true);
12451        // writer
12452        synchronized (mPackages) {
12453            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12454            if (!disabledSystem && deletedPackage != null) {
12455                // We didn't need to disable the .apk as a current system package,
12456                // which means we are replacing another update that is already
12457                // installed.  We need to make sure to delete the older one's .apk.
12458                res.removedInfo.args = createInstallArgsForExisting(0,
12459                        deletedPackage.applicationInfo.getCodePath(),
12460                        deletedPackage.applicationInfo.getResourcePath(),
12461                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12462            } else {
12463                res.removedInfo.args = null;
12464            }
12465        }
12466
12467        // Successfully disabled the old package. Now proceed with re-installation
12468        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12469
12470        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12471        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12472
12473        PackageParser.Package newPackage = null;
12474        try {
12475            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12476            if (newPackage.mExtras != null) {
12477                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12478                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12479                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12480
12481                // is the update attempting to change shared user? that isn't going to work...
12482                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12483                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12484                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12485                            + " to " + newPkgSetting.sharedUser);
12486                    updatedSettings = true;
12487                }
12488            }
12489
12490            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12491                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12492                        perUserInstalled, res, user);
12493                updatedSettings = true;
12494            }
12495
12496        } catch (PackageManagerException e) {
12497            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12498        }
12499
12500        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12501            // Re installation failed. Restore old information
12502            // Remove new pkg information
12503            if (newPackage != null) {
12504                removeInstalledPackageLI(newPackage, true);
12505            }
12506            // Add back the old system package
12507            try {
12508                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12509            } catch (PackageManagerException e) {
12510                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12511            }
12512            // Restore the old system information in Settings
12513            synchronized (mPackages) {
12514                if (disabledSystem) {
12515                    mSettings.enableSystemPackageLPw(packageName);
12516                }
12517                if (updatedSettings) {
12518                    mSettings.setInstallerPackageName(packageName,
12519                            oldPkgSetting.installerPackageName);
12520                }
12521                mSettings.writeLPr();
12522            }
12523        }
12524    }
12525
12526    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12527        // Collect all used permissions in the UID
12528        ArraySet<String> usedPermissions = new ArraySet<>();
12529        final int packageCount = su.packages.size();
12530        for (int i = 0; i < packageCount; i++) {
12531            PackageSetting ps = su.packages.valueAt(i);
12532            if (ps.pkg == null) {
12533                continue;
12534            }
12535            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12536            for (int j = 0; j < requestedPermCount; j++) {
12537                String permission = ps.pkg.requestedPermissions.get(j);
12538                BasePermission bp = mSettings.mPermissions.get(permission);
12539                if (bp != null) {
12540                    usedPermissions.add(permission);
12541                }
12542            }
12543        }
12544
12545        PermissionsState permissionsState = su.getPermissionsState();
12546        // Prune install permissions
12547        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12548        final int installPermCount = installPermStates.size();
12549        for (int i = installPermCount - 1; i >= 0;  i--) {
12550            PermissionState permissionState = installPermStates.get(i);
12551            if (!usedPermissions.contains(permissionState.getName())) {
12552                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12553                if (bp != null) {
12554                    permissionsState.revokeInstallPermission(bp);
12555                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12556                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12557                }
12558            }
12559        }
12560
12561        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12562
12563        // Prune runtime permissions
12564        for (int userId : allUserIds) {
12565            List<PermissionState> runtimePermStates = permissionsState
12566                    .getRuntimePermissionStates(userId);
12567            final int runtimePermCount = runtimePermStates.size();
12568            for (int i = runtimePermCount - 1; i >= 0; i--) {
12569                PermissionState permissionState = runtimePermStates.get(i);
12570                if (!usedPermissions.contains(permissionState.getName())) {
12571                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12572                    if (bp != null) {
12573                        permissionsState.revokeRuntimePermission(bp, userId);
12574                        permissionsState.updatePermissionFlags(bp, userId,
12575                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12576                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12577                                runtimePermissionChangedUserIds, userId);
12578                    }
12579                }
12580            }
12581        }
12582
12583        return runtimePermissionChangedUserIds;
12584    }
12585
12586    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12587            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12588            UserHandle user) {
12589        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12590
12591        String pkgName = newPackage.packageName;
12592        synchronized (mPackages) {
12593            //write settings. the installStatus will be incomplete at this stage.
12594            //note that the new package setting would have already been
12595            //added to mPackages. It hasn't been persisted yet.
12596            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12597            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12598            mSettings.writeLPr();
12599            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12600        }
12601
12602        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12603        synchronized (mPackages) {
12604            updatePermissionsLPw(newPackage.packageName, newPackage,
12605                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12606                            ? UPDATE_PERMISSIONS_ALL : 0));
12607            // For system-bundled packages, we assume that installing an upgraded version
12608            // of the package implies that the user actually wants to run that new code,
12609            // so we enable the package.
12610            PackageSetting ps = mSettings.mPackages.get(pkgName);
12611            if (ps != null) {
12612                if (isSystemApp(newPackage)) {
12613                    // NB: implicit assumption that system package upgrades apply to all users
12614                    if (DEBUG_INSTALL) {
12615                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12616                    }
12617                    if (res.origUsers != null) {
12618                        for (int userHandle : res.origUsers) {
12619                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12620                                    userHandle, installerPackageName);
12621                        }
12622                    }
12623                    // Also convey the prior install/uninstall state
12624                    if (allUsers != null && perUserInstalled != null) {
12625                        for (int i = 0; i < allUsers.length; i++) {
12626                            if (DEBUG_INSTALL) {
12627                                Slog.d(TAG, "    user " + allUsers[i]
12628                                        + " => " + perUserInstalled[i]);
12629                            }
12630                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12631                        }
12632                        // these install state changes will be persisted in the
12633                        // upcoming call to mSettings.writeLPr().
12634                    }
12635                }
12636                // It's implied that when a user requests installation, they want the app to be
12637                // installed and enabled.
12638                int userId = user.getIdentifier();
12639                if (userId != UserHandle.USER_ALL) {
12640                    ps.setInstalled(true, userId);
12641                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12642                }
12643            }
12644            res.name = pkgName;
12645            res.uid = newPackage.applicationInfo.uid;
12646            res.pkg = newPackage;
12647            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12648            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12649            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12650            //to update install status
12651            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12652            mSettings.writeLPr();
12653            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12654        }
12655
12656        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12657    }
12658
12659    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12660        try {
12661            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12662            installPackageLI(args, res);
12663        } finally {
12664            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12665        }
12666    }
12667
12668    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12669        final int installFlags = args.installFlags;
12670        final String installerPackageName = args.installerPackageName;
12671        final String volumeUuid = args.volumeUuid;
12672        final File tmpPackageFile = new File(args.getCodePath());
12673        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12674        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12675                || (args.volumeUuid != null));
12676        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12677        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12678        boolean replace = false;
12679        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12680        if (args.move != null) {
12681            // moving a complete application; perfom an initial scan on the new install location
12682            scanFlags |= SCAN_INITIAL;
12683        }
12684        // Result object to be returned
12685        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12686
12687        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12688
12689        // Sanity check
12690        if (ephemeral && (forwardLocked || onExternal)) {
12691            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12692                    + " external=" + onExternal);
12693            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12694            return;
12695        }
12696
12697        // Retrieve PackageSettings and parse package
12698        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12699                | PackageParser.PARSE_ENFORCE_CODE
12700                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12701                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12702                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0)
12703                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12704        PackageParser pp = new PackageParser();
12705        pp.setSeparateProcesses(mSeparateProcesses);
12706        pp.setDisplayMetrics(mMetrics);
12707
12708        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12709        final PackageParser.Package pkg;
12710        try {
12711            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12712        } catch (PackageParserException e) {
12713            res.setError("Failed parse during installPackageLI", e);
12714            return;
12715        } finally {
12716            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12717        }
12718
12719        // Mark that we have an install time CPU ABI override.
12720        pkg.cpuAbiOverride = args.abiOverride;
12721
12722        String pkgName = res.name = pkg.packageName;
12723        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12724            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12725                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12726                return;
12727            }
12728        }
12729
12730        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12731        try {
12732            pp.collectCertificates(pkg, parseFlags);
12733        } catch (PackageParserException e) {
12734            res.setError("Failed collect during installPackageLI", e);
12735            return;
12736        } finally {
12737            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12738        }
12739
12740        /* If the installer passed in a manifest digest, compare it now. */
12741        if (args.manifestDigest != null) {
12742            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12743            try {
12744                pp.collectManifestDigest(pkg);
12745            } catch (PackageParserException e) {
12746                res.setError("Failed collect during installPackageLI", e);
12747                return;
12748            } finally {
12749                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12750            }
12751
12752            if (DEBUG_INSTALL) {
12753                final String parsedManifest = pkg.manifestDigest == null ? "null"
12754                        : pkg.manifestDigest.toString();
12755                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12756                        + parsedManifest);
12757            }
12758
12759            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12760                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12761                return;
12762            }
12763        } else if (DEBUG_INSTALL) {
12764            final String parsedManifest = pkg.manifestDigest == null
12765                    ? "null" : pkg.manifestDigest.toString();
12766            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12767        }
12768
12769        // Get rid of all references to package scan path via parser.
12770        pp = null;
12771        String oldCodePath = null;
12772        boolean systemApp = false;
12773        synchronized (mPackages) {
12774            // Check if installing already existing package
12775            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12776                String oldName = mSettings.mRenamedPackages.get(pkgName);
12777                if (pkg.mOriginalPackages != null
12778                        && pkg.mOriginalPackages.contains(oldName)
12779                        && mPackages.containsKey(oldName)) {
12780                    // This package is derived from an original package,
12781                    // and this device has been updating from that original
12782                    // name.  We must continue using the original name, so
12783                    // rename the new package here.
12784                    pkg.setPackageName(oldName);
12785                    pkgName = pkg.packageName;
12786                    replace = true;
12787                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12788                            + oldName + " pkgName=" + pkgName);
12789                } else if (mPackages.containsKey(pkgName)) {
12790                    // This package, under its official name, already exists
12791                    // on the device; we should replace it.
12792                    replace = true;
12793                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12794                }
12795
12796                // Prevent apps opting out from runtime permissions
12797                if (replace) {
12798                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12799                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12800                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12801                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12802                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12803                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12804                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12805                                        + " doesn't support runtime permissions but the old"
12806                                        + " target SDK " + oldTargetSdk + " does.");
12807                        return;
12808                    }
12809                }
12810            }
12811
12812            PackageSetting ps = mSettings.mPackages.get(pkgName);
12813            if (ps != null) {
12814                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12815
12816                // Quick sanity check that we're signed correctly if updating;
12817                // we'll check this again later when scanning, but we want to
12818                // bail early here before tripping over redefined permissions.
12819                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12820                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12821                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12822                                + pkg.packageName + " upgrade keys do not match the "
12823                                + "previously installed version");
12824                        return;
12825                    }
12826                } else {
12827                    try {
12828                        verifySignaturesLP(ps, pkg);
12829                    } catch (PackageManagerException e) {
12830                        res.setError(e.error, e.getMessage());
12831                        return;
12832                    }
12833                }
12834
12835                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12836                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12837                    systemApp = (ps.pkg.applicationInfo.flags &
12838                            ApplicationInfo.FLAG_SYSTEM) != 0;
12839                }
12840                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12841            }
12842
12843            // Check whether the newly-scanned package wants to define an already-defined perm
12844            int N = pkg.permissions.size();
12845            for (int i = N-1; i >= 0; i--) {
12846                PackageParser.Permission perm = pkg.permissions.get(i);
12847                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12848                if (bp != null) {
12849                    // If the defining package is signed with our cert, it's okay.  This
12850                    // also includes the "updating the same package" case, of course.
12851                    // "updating same package" could also involve key-rotation.
12852                    final boolean sigsOk;
12853                    if (bp.sourcePackage.equals(pkg.packageName)
12854                            && (bp.packageSetting instanceof PackageSetting)
12855                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12856                                    scanFlags))) {
12857                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12858                    } else {
12859                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12860                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12861                    }
12862                    if (!sigsOk) {
12863                        // If the owning package is the system itself, we log but allow
12864                        // install to proceed; we fail the install on all other permission
12865                        // redefinitions.
12866                        if (!bp.sourcePackage.equals("android")) {
12867                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12868                                    + pkg.packageName + " attempting to redeclare permission "
12869                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12870                            res.origPermission = perm.info.name;
12871                            res.origPackage = bp.sourcePackage;
12872                            return;
12873                        } else {
12874                            Slog.w(TAG, "Package " + pkg.packageName
12875                                    + " attempting to redeclare system permission "
12876                                    + perm.info.name + "; ignoring new declaration");
12877                            pkg.permissions.remove(i);
12878                        }
12879                    }
12880                }
12881            }
12882
12883        }
12884
12885        if (systemApp) {
12886            if (onExternal) {
12887                // Abort update; system app can't be replaced with app on sdcard
12888                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12889                        "Cannot install updates to system apps on sdcard");
12890                return;
12891            } else if (ephemeral) {
12892                // Abort update; system app can't be replaced with an ephemeral app
12893                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12894                        "Cannot update a system app with an ephemeral app");
12895                return;
12896            }
12897        }
12898
12899        if (args.move != null) {
12900            // We did an in-place move, so dex is ready to roll
12901            scanFlags |= SCAN_NO_DEX;
12902            scanFlags |= SCAN_MOVE;
12903
12904            synchronized (mPackages) {
12905                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12906                if (ps == null) {
12907                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12908                            "Missing settings for moved package " + pkgName);
12909                }
12910
12911                // We moved the entire application as-is, so bring over the
12912                // previously derived ABI information.
12913                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12914                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12915            }
12916
12917        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12918            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12919            scanFlags |= SCAN_NO_DEX;
12920
12921            try {
12922                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12923                        true /* extract libs */);
12924            } catch (PackageManagerException pme) {
12925                Slog.e(TAG, "Error deriving application ABI", pme);
12926                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12927                return;
12928            }
12929        }
12930
12931        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12932            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12933            return;
12934        }
12935
12936        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12937
12938        if (replace) {
12939            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12940                    installerPackageName, volumeUuid, res);
12941        } else {
12942            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12943                    args.user, installerPackageName, volumeUuid, res);
12944        }
12945        synchronized (mPackages) {
12946            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12947            if (ps != null) {
12948                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12949            }
12950        }
12951    }
12952
12953    private void startIntentFilterVerifications(int userId, boolean replacing,
12954            PackageParser.Package pkg) {
12955        if (mIntentFilterVerifierComponent == null) {
12956            Slog.w(TAG, "No IntentFilter verification will not be done as "
12957                    + "there is no IntentFilterVerifier available!");
12958            return;
12959        }
12960
12961        final int verifierUid = getPackageUid(
12962                mIntentFilterVerifierComponent.getPackageName(),
12963                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12964
12965        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12966        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12967        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12968        mHandler.sendMessage(msg);
12969    }
12970
12971    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12972            PackageParser.Package pkg) {
12973        int size = pkg.activities.size();
12974        if (size == 0) {
12975            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12976                    "No activity, so no need to verify any IntentFilter!");
12977            return;
12978        }
12979
12980        final boolean hasDomainURLs = hasDomainURLs(pkg);
12981        if (!hasDomainURLs) {
12982            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12983                    "No domain URLs, so no need to verify any IntentFilter!");
12984            return;
12985        }
12986
12987        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12988                + " if any IntentFilter from the " + size
12989                + " Activities needs verification ...");
12990
12991        int count = 0;
12992        final String packageName = pkg.packageName;
12993
12994        synchronized (mPackages) {
12995            // If this is a new install and we see that we've already run verification for this
12996            // package, we have nothing to do: it means the state was restored from backup.
12997            if (!replacing) {
12998                IntentFilterVerificationInfo ivi =
12999                        mSettings.getIntentFilterVerificationLPr(packageName);
13000                if (ivi != null) {
13001                    if (DEBUG_DOMAIN_VERIFICATION) {
13002                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13003                                + ivi.getStatusString());
13004                    }
13005                    return;
13006                }
13007            }
13008
13009            // If any filters need to be verified, then all need to be.
13010            boolean needToVerify = false;
13011            for (PackageParser.Activity a : pkg.activities) {
13012                for (ActivityIntentInfo filter : a.intents) {
13013                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13014                        if (DEBUG_DOMAIN_VERIFICATION) {
13015                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13016                        }
13017                        needToVerify = true;
13018                        break;
13019                    }
13020                }
13021            }
13022
13023            if (needToVerify) {
13024                final int verificationId = mIntentFilterVerificationToken++;
13025                for (PackageParser.Activity a : pkg.activities) {
13026                    for (ActivityIntentInfo filter : a.intents) {
13027                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13028                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13029                                    "Verification needed for IntentFilter:" + filter.toString());
13030                            mIntentFilterVerifier.addOneIntentFilterVerification(
13031                                    verifierUid, userId, verificationId, filter, packageName);
13032                            count++;
13033                        }
13034                    }
13035                }
13036            }
13037        }
13038
13039        if (count > 0) {
13040            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13041                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13042                    +  " for userId:" + userId);
13043            mIntentFilterVerifier.startVerifications(userId);
13044        } else {
13045            if (DEBUG_DOMAIN_VERIFICATION) {
13046                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13047            }
13048        }
13049    }
13050
13051    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13052        final ComponentName cn  = filter.activity.getComponentName();
13053        final String packageName = cn.getPackageName();
13054
13055        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13056                packageName);
13057        if (ivi == null) {
13058            return true;
13059        }
13060        int status = ivi.getStatus();
13061        switch (status) {
13062            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13063            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13064                return true;
13065
13066            default:
13067                // Nothing to do
13068                return false;
13069        }
13070    }
13071
13072    private static boolean isMultiArch(PackageSetting ps) {
13073        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13074    }
13075
13076    private static boolean isMultiArch(ApplicationInfo info) {
13077        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13078    }
13079
13080    private static boolean isExternal(PackageParser.Package pkg) {
13081        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13082    }
13083
13084    private static boolean isExternal(PackageSetting ps) {
13085        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13086    }
13087
13088    private static boolean isExternal(ApplicationInfo info) {
13089        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13090    }
13091
13092    private static boolean isEphemeral(PackageParser.Package pkg) {
13093        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EPHEMERAL) != 0;
13094    }
13095
13096    private static boolean isEphemeral(PackageSetting ps) {
13097        return (ps.pkgFlags & ApplicationInfo.FLAG_EPHEMERAL) != 0;
13098    }
13099
13100    private static boolean isSystemApp(PackageParser.Package pkg) {
13101        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13102    }
13103
13104    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13105        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13106    }
13107
13108    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13109        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13110    }
13111
13112    private static boolean isSystemApp(PackageSetting ps) {
13113        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13114    }
13115
13116    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13117        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13118    }
13119
13120    private int packageFlagsToInstallFlags(PackageSetting ps) {
13121        int installFlags = 0;
13122        if (isEphemeral(ps)) {
13123            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13124        }
13125        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13126            // This existing package was an external ASEC install when we have
13127            // the external flag without a UUID
13128            installFlags |= PackageManager.INSTALL_EXTERNAL;
13129        }
13130        if (ps.isForwardLocked()) {
13131            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13132        }
13133        return installFlags;
13134    }
13135
13136    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13137        if (isExternal(pkg)) {
13138            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13139                return StorageManager.UUID_PRIMARY_PHYSICAL;
13140            } else {
13141                return pkg.volumeUuid;
13142            }
13143        } else {
13144            return StorageManager.UUID_PRIVATE_INTERNAL;
13145        }
13146    }
13147
13148    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13149        if (isExternal(pkg)) {
13150            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13151                return mSettings.getExternalVersion();
13152            } else {
13153                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13154            }
13155        } else {
13156            return mSettings.getInternalVersion();
13157        }
13158    }
13159
13160    private void deleteTempPackageFiles() {
13161        final FilenameFilter filter = new FilenameFilter() {
13162            public boolean accept(File dir, String name) {
13163                return name.startsWith("vmdl") && name.endsWith(".tmp");
13164            }
13165        };
13166        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13167            file.delete();
13168        }
13169    }
13170
13171    @Override
13172    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13173            int flags) {
13174        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13175                flags);
13176    }
13177
13178    @Override
13179    public void deletePackage(final String packageName,
13180            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13181        mContext.enforceCallingOrSelfPermission(
13182                android.Manifest.permission.DELETE_PACKAGES, null);
13183        Preconditions.checkNotNull(packageName);
13184        Preconditions.checkNotNull(observer);
13185        final int uid = Binder.getCallingUid();
13186        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13187        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13188        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13189            mContext.enforceCallingOrSelfPermission(
13190                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13191                    "deletePackage for user " + userId);
13192        }
13193
13194        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13195            try {
13196                observer.onPackageDeleted(packageName,
13197                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13198            } catch (RemoteException re) {
13199            }
13200            return;
13201        }
13202
13203        for (int currentUserId : users) {
13204            if (getBlockUninstallForUser(packageName, currentUserId)) {
13205                try {
13206                    observer.onPackageDeleted(packageName,
13207                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13208                } catch (RemoteException re) {
13209                }
13210                return;
13211            }
13212        }
13213
13214        if (DEBUG_REMOVE) {
13215            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13216        }
13217        // Queue up an async operation since the package deletion may take a little while.
13218        mHandler.post(new Runnable() {
13219            public void run() {
13220                mHandler.removeCallbacks(this);
13221                final int returnCode = deletePackageX(packageName, userId, flags);
13222                try {
13223                    observer.onPackageDeleted(packageName, returnCode, null);
13224                } catch (RemoteException e) {
13225                    Log.i(TAG, "Observer no longer exists.");
13226                } //end catch
13227            } //end run
13228        });
13229    }
13230
13231    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13232        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13233                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13234        try {
13235            if (dpm != null) {
13236                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13237                        /* callingUserOnly =*/ false);
13238                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13239                        : deviceOwnerComponentName.getPackageName();
13240                // Does the package contains the device owner?
13241                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13242                // this check is probably not needed, since DO should be registered as a device
13243                // admin on some user too. (Original bug for this: b/17657954)
13244                if (packageName.equals(deviceOwnerPackageName)) {
13245                    return true;
13246                }
13247                // Does it contain a device admin for any user?
13248                int[] users;
13249                if (userId == UserHandle.USER_ALL) {
13250                    users = sUserManager.getUserIds();
13251                } else {
13252                    users = new int[]{userId};
13253                }
13254                for (int i = 0; i < users.length; ++i) {
13255                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13256                        return true;
13257                    }
13258                }
13259            }
13260        } catch (RemoteException e) {
13261        }
13262        return false;
13263    }
13264
13265    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13266        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13267    }
13268
13269    /**
13270     *  This method is an internal method that could be get invoked either
13271     *  to delete an installed package or to clean up a failed installation.
13272     *  After deleting an installed package, a broadcast is sent to notify any
13273     *  listeners that the package has been installed. For cleaning up a failed
13274     *  installation, the broadcast is not necessary since the package's
13275     *  installation wouldn't have sent the initial broadcast either
13276     *  The key steps in deleting a package are
13277     *  deleting the package information in internal structures like mPackages,
13278     *  deleting the packages base directories through installd
13279     *  updating mSettings to reflect current status
13280     *  persisting settings for later use
13281     *  sending a broadcast if necessary
13282     */
13283    private int deletePackageX(String packageName, int userId, int flags) {
13284        final PackageRemovedInfo info = new PackageRemovedInfo();
13285        final boolean res;
13286
13287        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13288                ? UserHandle.ALL : new UserHandle(userId);
13289
13290        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13291            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13292            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13293        }
13294
13295        boolean removedForAllUsers = false;
13296        boolean systemUpdate = false;
13297
13298        // for the uninstall-updates case and restricted profiles, remember the per-
13299        // userhandle installed state
13300        int[] allUsers;
13301        boolean[] perUserInstalled;
13302        synchronized (mPackages) {
13303            PackageSetting ps = mSettings.mPackages.get(packageName);
13304            allUsers = sUserManager.getUserIds();
13305            perUserInstalled = new boolean[allUsers.length];
13306            for (int i = 0; i < allUsers.length; i++) {
13307                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13308            }
13309        }
13310
13311        synchronized (mInstallLock) {
13312            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13313            res = deletePackageLI(packageName, removeForUser,
13314                    true, allUsers, perUserInstalled,
13315                    flags | REMOVE_CHATTY, info, true);
13316            systemUpdate = info.isRemovedPackageSystemUpdate;
13317            if (res && !systemUpdate && mPackages.get(packageName) == null) {
13318                removedForAllUsers = true;
13319            }
13320            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13321                    + " removedForAllUsers=" + removedForAllUsers);
13322        }
13323
13324        if (res) {
13325            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13326
13327            // If the removed package was a system update, the old system package
13328            // was re-enabled; we need to broadcast this information
13329            if (systemUpdate) {
13330                Bundle extras = new Bundle(1);
13331                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13332                        ? info.removedAppId : info.uid);
13333                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13334
13335                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13336                        extras, 0, null, null, null);
13337                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13338                        extras, 0, null, null, null);
13339                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13340                        null, 0, packageName, null, null);
13341            }
13342        }
13343        // Force a gc here.
13344        Runtime.getRuntime().gc();
13345        // Delete the resources here after sending the broadcast to let
13346        // other processes clean up before deleting resources.
13347        if (info.args != null) {
13348            synchronized (mInstallLock) {
13349                info.args.doPostDeleteLI(true);
13350            }
13351        }
13352
13353        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13354    }
13355
13356    class PackageRemovedInfo {
13357        String removedPackage;
13358        int uid = -1;
13359        int removedAppId = -1;
13360        int[] removedUsers = null;
13361        boolean isRemovedPackageSystemUpdate = false;
13362        // Clean up resources deleted packages.
13363        InstallArgs args = null;
13364
13365        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13366            Bundle extras = new Bundle(1);
13367            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13368            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13369            if (replacing) {
13370                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13371            }
13372            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13373            if (removedPackage != null) {
13374                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13375                        extras, 0, null, null, removedUsers);
13376                if (fullRemove && !replacing) {
13377                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13378                            extras, 0, null, null, removedUsers);
13379                }
13380            }
13381            if (removedAppId >= 0) {
13382                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13383                        removedUsers);
13384            }
13385        }
13386    }
13387
13388    /*
13389     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13390     * flag is not set, the data directory is removed as well.
13391     * make sure this flag is set for partially installed apps. If not its meaningless to
13392     * delete a partially installed application.
13393     */
13394    private void removePackageDataLI(PackageSetting ps,
13395            int[] allUserHandles, boolean[] perUserInstalled,
13396            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13397        String packageName = ps.name;
13398        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13399        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13400        // Retrieve object to delete permissions for shared user later on
13401        final PackageSetting deletedPs;
13402        // reader
13403        synchronized (mPackages) {
13404            deletedPs = mSettings.mPackages.get(packageName);
13405            if (outInfo != null) {
13406                outInfo.removedPackage = packageName;
13407                outInfo.removedUsers = deletedPs != null
13408                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13409                        : null;
13410            }
13411        }
13412        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13413            removeDataDirsLI(ps.volumeUuid, packageName);
13414            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13415        }
13416        // writer
13417        synchronized (mPackages) {
13418            if (deletedPs != null) {
13419                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13420                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13421                    clearDefaultBrowserIfNeeded(packageName);
13422                    if (outInfo != null) {
13423                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13424                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13425                    }
13426                    updatePermissionsLPw(deletedPs.name, null, 0);
13427                    if (deletedPs.sharedUser != null) {
13428                        // Remove permissions associated with package. Since runtime
13429                        // permissions are per user we have to kill the removed package
13430                        // or packages running under the shared user of the removed
13431                        // package if revoking the permissions requested only by the removed
13432                        // package is successful and this causes a change in gids.
13433                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13434                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13435                                    userId);
13436                            if (userIdToKill == UserHandle.USER_ALL
13437                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13438                                // If gids changed for this user, kill all affected packages.
13439                                mHandler.post(new Runnable() {
13440                                    @Override
13441                                    public void run() {
13442                                        // This has to happen with no lock held.
13443                                        killApplication(deletedPs.name, deletedPs.appId,
13444                                                KILL_APP_REASON_GIDS_CHANGED);
13445                                    }
13446                                });
13447                                break;
13448                            }
13449                        }
13450                    }
13451                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13452                }
13453                // make sure to preserve per-user disabled state if this removal was just
13454                // a downgrade of a system app to the factory package
13455                if (allUserHandles != null && perUserInstalled != null) {
13456                    if (DEBUG_REMOVE) {
13457                        Slog.d(TAG, "Propagating install state across downgrade");
13458                    }
13459                    for (int i = 0; i < allUserHandles.length; i++) {
13460                        if (DEBUG_REMOVE) {
13461                            Slog.d(TAG, "    user " + allUserHandles[i]
13462                                    + " => " + perUserInstalled[i]);
13463                        }
13464                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13465                    }
13466                }
13467            }
13468            // can downgrade to reader
13469            if (writeSettings) {
13470                // Save settings now
13471                mSettings.writeLPr();
13472            }
13473        }
13474        if (outInfo != null) {
13475            // A user ID was deleted here. Go through all users and remove it
13476            // from KeyStore.
13477            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13478        }
13479    }
13480
13481    static boolean locationIsPrivileged(File path) {
13482        try {
13483            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13484                    .getCanonicalPath();
13485            return path.getCanonicalPath().startsWith(privilegedAppDir);
13486        } catch (IOException e) {
13487            Slog.e(TAG, "Unable to access code path " + path);
13488        }
13489        return false;
13490    }
13491
13492    /*
13493     * Tries to delete system package.
13494     */
13495    private boolean deleteSystemPackageLI(PackageSetting newPs,
13496            int[] allUserHandles, boolean[] perUserInstalled,
13497            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13498        final boolean applyUserRestrictions
13499                = (allUserHandles != null) && (perUserInstalled != null);
13500        PackageSetting disabledPs = null;
13501        // Confirm if the system package has been updated
13502        // An updated system app can be deleted. This will also have to restore
13503        // the system pkg from system partition
13504        // reader
13505        synchronized (mPackages) {
13506            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13507        }
13508        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13509                + " disabledPs=" + disabledPs);
13510        if (disabledPs == null) {
13511            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13512            return false;
13513        } else if (DEBUG_REMOVE) {
13514            Slog.d(TAG, "Deleting system pkg from data partition");
13515        }
13516        if (DEBUG_REMOVE) {
13517            if (applyUserRestrictions) {
13518                Slog.d(TAG, "Remembering install states:");
13519                for (int i = 0; i < allUserHandles.length; i++) {
13520                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13521                }
13522            }
13523        }
13524        // Delete the updated package
13525        outInfo.isRemovedPackageSystemUpdate = true;
13526        if (disabledPs.versionCode < newPs.versionCode) {
13527            // Delete data for downgrades
13528            flags &= ~PackageManager.DELETE_KEEP_DATA;
13529        } else {
13530            // Preserve data by setting flag
13531            flags |= PackageManager.DELETE_KEEP_DATA;
13532        }
13533        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13534                allUserHandles, perUserInstalled, outInfo, writeSettings);
13535        if (!ret) {
13536            return false;
13537        }
13538        // writer
13539        synchronized (mPackages) {
13540            // Reinstate the old system package
13541            mSettings.enableSystemPackageLPw(newPs.name);
13542            // Remove any native libraries from the upgraded package.
13543            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13544        }
13545        // Install the system package
13546        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13547        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13548        if (locationIsPrivileged(disabledPs.codePath)) {
13549            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13550        }
13551
13552        final PackageParser.Package newPkg;
13553        try {
13554            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13555        } catch (PackageManagerException e) {
13556            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13557            return false;
13558        }
13559
13560        // writer
13561        synchronized (mPackages) {
13562            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13563
13564            // Propagate the permissions state as we do not want to drop on the floor
13565            // runtime permissions. The update permissions method below will take
13566            // care of removing obsolete permissions and grant install permissions.
13567            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13568            updatePermissionsLPw(newPkg.packageName, newPkg,
13569                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13570
13571            if (applyUserRestrictions) {
13572                if (DEBUG_REMOVE) {
13573                    Slog.d(TAG, "Propagating install state across reinstall");
13574                }
13575                for (int i = 0; i < allUserHandles.length; i++) {
13576                    if (DEBUG_REMOVE) {
13577                        Slog.d(TAG, "    user " + allUserHandles[i]
13578                                + " => " + perUserInstalled[i]);
13579                    }
13580                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13581
13582                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13583                }
13584                // Regardless of writeSettings we need to ensure that this restriction
13585                // state propagation is persisted
13586                mSettings.writeAllUsersPackageRestrictionsLPr();
13587            }
13588            // can downgrade to reader here
13589            if (writeSettings) {
13590                mSettings.writeLPr();
13591            }
13592        }
13593        return true;
13594    }
13595
13596    private boolean deleteInstalledPackageLI(PackageSetting ps,
13597            boolean deleteCodeAndResources, int flags,
13598            int[] allUserHandles, boolean[] perUserInstalled,
13599            PackageRemovedInfo outInfo, boolean writeSettings) {
13600        if (outInfo != null) {
13601            outInfo.uid = ps.appId;
13602        }
13603
13604        // Delete package data from internal structures and also remove data if flag is set
13605        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13606
13607        // Delete application code and resources
13608        if (deleteCodeAndResources && (outInfo != null)) {
13609            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13610                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13611            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13612        }
13613        return true;
13614    }
13615
13616    @Override
13617    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13618            int userId) {
13619        mContext.enforceCallingOrSelfPermission(
13620                android.Manifest.permission.DELETE_PACKAGES, null);
13621        synchronized (mPackages) {
13622            PackageSetting ps = mSettings.mPackages.get(packageName);
13623            if (ps == null) {
13624                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13625                return false;
13626            }
13627            if (!ps.getInstalled(userId)) {
13628                // Can't block uninstall for an app that is not installed or enabled.
13629                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13630                return false;
13631            }
13632            ps.setBlockUninstall(blockUninstall, userId);
13633            mSettings.writePackageRestrictionsLPr(userId);
13634        }
13635        return true;
13636    }
13637
13638    @Override
13639    public boolean getBlockUninstallForUser(String packageName, int userId) {
13640        synchronized (mPackages) {
13641            PackageSetting ps = mSettings.mPackages.get(packageName);
13642            if (ps == null) {
13643                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13644                return false;
13645            }
13646            return ps.getBlockUninstall(userId);
13647        }
13648    }
13649
13650    /*
13651     * This method handles package deletion in general
13652     */
13653    private boolean deletePackageLI(String packageName, UserHandle user,
13654            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13655            int flags, PackageRemovedInfo outInfo,
13656            boolean writeSettings) {
13657        if (packageName == null) {
13658            Slog.w(TAG, "Attempt to delete null packageName.");
13659            return false;
13660        }
13661        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13662        PackageSetting ps;
13663        boolean dataOnly = false;
13664        int removeUser = -1;
13665        int appId = -1;
13666        synchronized (mPackages) {
13667            ps = mSettings.mPackages.get(packageName);
13668            if (ps == null) {
13669                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13670                return false;
13671            }
13672            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13673                    && user.getIdentifier() != UserHandle.USER_ALL) {
13674                // The caller is asking that the package only be deleted for a single
13675                // user.  To do this, we just mark its uninstalled state and delete
13676                // its data.  If this is a system app, we only allow this to happen if
13677                // they have set the special DELETE_SYSTEM_APP which requests different
13678                // semantics than normal for uninstalling system apps.
13679                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13680                final int userId = user.getIdentifier();
13681                ps.setUserState(userId,
13682                        COMPONENT_ENABLED_STATE_DEFAULT,
13683                        false, //installed
13684                        true,  //stopped
13685                        true,  //notLaunched
13686                        false, //hidden
13687                        null, null, null,
13688                        false, // blockUninstall
13689                        ps.readUserState(userId).domainVerificationStatus, 0);
13690                if (!isSystemApp(ps)) {
13691                    // Do not uninstall the APK if an app should be cached
13692                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13693                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13694                        // Other user still have this package installed, so all
13695                        // we need to do is clear this user's data and save that
13696                        // it is uninstalled.
13697                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13698                        removeUser = user.getIdentifier();
13699                        appId = ps.appId;
13700                        scheduleWritePackageRestrictionsLocked(removeUser);
13701                    } else {
13702                        // We need to set it back to 'installed' so the uninstall
13703                        // broadcasts will be sent correctly.
13704                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13705                        ps.setInstalled(true, user.getIdentifier());
13706                    }
13707                } else {
13708                    // This is a system app, so we assume that the
13709                    // other users still have this package installed, so all
13710                    // we need to do is clear this user's data and save that
13711                    // it is uninstalled.
13712                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13713                    removeUser = user.getIdentifier();
13714                    appId = ps.appId;
13715                    scheduleWritePackageRestrictionsLocked(removeUser);
13716                }
13717            }
13718        }
13719
13720        if (removeUser >= 0) {
13721            // From above, we determined that we are deleting this only
13722            // for a single user.  Continue the work here.
13723            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13724            if (outInfo != null) {
13725                outInfo.removedPackage = packageName;
13726                outInfo.removedAppId = appId;
13727                outInfo.removedUsers = new int[] {removeUser};
13728            }
13729            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13730            removeKeystoreDataIfNeeded(removeUser, appId);
13731            schedulePackageCleaning(packageName, removeUser, false);
13732            synchronized (mPackages) {
13733                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13734                    scheduleWritePackageRestrictionsLocked(removeUser);
13735                }
13736                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13737            }
13738            return true;
13739        }
13740
13741        if (dataOnly) {
13742            // Delete application data first
13743            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13744            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13745            return true;
13746        }
13747
13748        boolean ret = false;
13749        if (isSystemApp(ps)) {
13750            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13751            // When an updated system application is deleted we delete the existing resources as well and
13752            // fall back to existing code in system partition
13753            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13754                    flags, outInfo, writeSettings);
13755        } else {
13756            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13757            // Kill application pre-emptively especially for apps on sd.
13758            killApplication(packageName, ps.appId, "uninstall pkg");
13759            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13760                    allUserHandles, perUserInstalled,
13761                    outInfo, writeSettings);
13762        }
13763
13764        return ret;
13765    }
13766
13767    private final class ClearStorageConnection implements ServiceConnection {
13768        IMediaContainerService mContainerService;
13769
13770        @Override
13771        public void onServiceConnected(ComponentName name, IBinder service) {
13772            synchronized (this) {
13773                mContainerService = IMediaContainerService.Stub.asInterface(service);
13774                notifyAll();
13775            }
13776        }
13777
13778        @Override
13779        public void onServiceDisconnected(ComponentName name) {
13780        }
13781    }
13782
13783    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13784        final boolean mounted;
13785        if (Environment.isExternalStorageEmulated()) {
13786            mounted = true;
13787        } else {
13788            final String status = Environment.getExternalStorageState();
13789
13790            mounted = status.equals(Environment.MEDIA_MOUNTED)
13791                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13792        }
13793
13794        if (!mounted) {
13795            return;
13796        }
13797
13798        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13799        int[] users;
13800        if (userId == UserHandle.USER_ALL) {
13801            users = sUserManager.getUserIds();
13802        } else {
13803            users = new int[] { userId };
13804        }
13805        final ClearStorageConnection conn = new ClearStorageConnection();
13806        if (mContext.bindServiceAsUser(
13807                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13808            try {
13809                for (int curUser : users) {
13810                    long timeout = SystemClock.uptimeMillis() + 5000;
13811                    synchronized (conn) {
13812                        long now = SystemClock.uptimeMillis();
13813                        while (conn.mContainerService == null && now < timeout) {
13814                            try {
13815                                conn.wait(timeout - now);
13816                            } catch (InterruptedException e) {
13817                            }
13818                        }
13819                    }
13820                    if (conn.mContainerService == null) {
13821                        return;
13822                    }
13823
13824                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13825                    clearDirectory(conn.mContainerService,
13826                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13827                    if (allData) {
13828                        clearDirectory(conn.mContainerService,
13829                                userEnv.buildExternalStorageAppDataDirs(packageName));
13830                        clearDirectory(conn.mContainerService,
13831                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13832                    }
13833                }
13834            } finally {
13835                mContext.unbindService(conn);
13836            }
13837        }
13838    }
13839
13840    @Override
13841    public void clearApplicationUserData(final String packageName,
13842            final IPackageDataObserver observer, final int userId) {
13843        mContext.enforceCallingOrSelfPermission(
13844                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13845        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13846        // Queue up an async operation since the package deletion may take a little while.
13847        mHandler.post(new Runnable() {
13848            public void run() {
13849                mHandler.removeCallbacks(this);
13850                final boolean succeeded;
13851                synchronized (mInstallLock) {
13852                    succeeded = clearApplicationUserDataLI(packageName, userId);
13853                }
13854                clearExternalStorageDataSync(packageName, userId, true);
13855                if (succeeded) {
13856                    // invoke DeviceStorageMonitor's update method to clear any notifications
13857                    DeviceStorageMonitorInternal
13858                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13859                    if (dsm != null) {
13860                        dsm.checkMemory();
13861                    }
13862                }
13863                if(observer != null) {
13864                    try {
13865                        observer.onRemoveCompleted(packageName, succeeded);
13866                    } catch (RemoteException e) {
13867                        Log.i(TAG, "Observer no longer exists.");
13868                    }
13869                } //end if observer
13870            } //end run
13871        });
13872    }
13873
13874    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13875        if (packageName == null) {
13876            Slog.w(TAG, "Attempt to delete null packageName.");
13877            return false;
13878        }
13879
13880        // Try finding details about the requested package
13881        PackageParser.Package pkg;
13882        synchronized (mPackages) {
13883            pkg = mPackages.get(packageName);
13884            if (pkg == null) {
13885                final PackageSetting ps = mSettings.mPackages.get(packageName);
13886                if (ps != null) {
13887                    pkg = ps.pkg;
13888                }
13889            }
13890
13891            if (pkg == null) {
13892                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13893                return false;
13894            }
13895
13896            PackageSetting ps = (PackageSetting) pkg.mExtras;
13897            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13898        }
13899
13900        // Always delete data directories for package, even if we found no other
13901        // record of app. This helps users recover from UID mismatches without
13902        // resorting to a full data wipe.
13903        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13904        if (retCode < 0) {
13905            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13906            return false;
13907        }
13908
13909        final int appId = pkg.applicationInfo.uid;
13910        removeKeystoreDataIfNeeded(userId, appId);
13911
13912        // Create a native library symlink only if we have native libraries
13913        // and if the native libraries are 32 bit libraries. We do not provide
13914        // this symlink for 64 bit libraries.
13915        if (pkg.applicationInfo.primaryCpuAbi != null &&
13916                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13917            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13918            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13919                    nativeLibPath, userId) < 0) {
13920                Slog.w(TAG, "Failed linking native library dir");
13921                return false;
13922            }
13923        }
13924
13925        return true;
13926    }
13927
13928    /**
13929     * Reverts user permission state changes (permissions and flags) in
13930     * all packages for a given user.
13931     *
13932     * @param userId The device user for which to do a reset.
13933     */
13934    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13935        final int packageCount = mPackages.size();
13936        for (int i = 0; i < packageCount; i++) {
13937            PackageParser.Package pkg = mPackages.valueAt(i);
13938            PackageSetting ps = (PackageSetting) pkg.mExtras;
13939            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13940        }
13941    }
13942
13943    /**
13944     * Reverts user permission state changes (permissions and flags).
13945     *
13946     * @param ps The package for which to reset.
13947     * @param userId The device user for which to do a reset.
13948     */
13949    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13950            final PackageSetting ps, final int userId) {
13951        if (ps.pkg == null) {
13952            return;
13953        }
13954
13955        // These are flags that can change base on user actions.
13956        final int userSettableMask = FLAG_PERMISSION_USER_SET
13957                | FLAG_PERMISSION_USER_FIXED
13958                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
13959                | FLAG_PERMISSION_REVIEW_REQUIRED;
13960
13961        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13962                | FLAG_PERMISSION_POLICY_FIXED;
13963
13964        boolean writeInstallPermissions = false;
13965        boolean writeRuntimePermissions = false;
13966
13967        final int permissionCount = ps.pkg.requestedPermissions.size();
13968        for (int i = 0; i < permissionCount; i++) {
13969            String permission = ps.pkg.requestedPermissions.get(i);
13970
13971            BasePermission bp = mSettings.mPermissions.get(permission);
13972            if (bp == null) {
13973                continue;
13974            }
13975
13976            // If shared user we just reset the state to which only this app contributed.
13977            if (ps.sharedUser != null) {
13978                boolean used = false;
13979                final int packageCount = ps.sharedUser.packages.size();
13980                for (int j = 0; j < packageCount; j++) {
13981                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13982                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13983                            && pkg.pkg.requestedPermissions.contains(permission)) {
13984                        used = true;
13985                        break;
13986                    }
13987                }
13988                if (used) {
13989                    continue;
13990                }
13991            }
13992
13993            PermissionsState permissionsState = ps.getPermissionsState();
13994
13995            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13996
13997            // Always clear the user settable flags.
13998            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13999                    bp.name) != null;
14000            // If permission review is enabled and this is a legacy app, mark the
14001            // permission as requiring a review as this is the initial state.
14002            int flags = 0;
14003            if (Build.PERMISSIONS_REVIEW_REQUIRED
14004                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14005                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14006            }
14007            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14008                if (hasInstallState) {
14009                    writeInstallPermissions = true;
14010                } else {
14011                    writeRuntimePermissions = true;
14012                }
14013            }
14014
14015            // Below is only runtime permission handling.
14016            if (!bp.isRuntime()) {
14017                continue;
14018            }
14019
14020            // Never clobber system or policy.
14021            if ((oldFlags & policyOrSystemFlags) != 0) {
14022                continue;
14023            }
14024
14025            // If this permission was granted by default, make sure it is.
14026            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14027                if (permissionsState.grantRuntimePermission(bp, userId)
14028                        != PERMISSION_OPERATION_FAILURE) {
14029                    writeRuntimePermissions = true;
14030                }
14031            // If permission review is enabled the permissions for a legacy apps
14032            // are represented as constantly granted runtime ones, so don't revoke.
14033            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14034                // Otherwise, reset the permission.
14035                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14036                switch (revokeResult) {
14037                    case PERMISSION_OPERATION_SUCCESS: {
14038                        writeRuntimePermissions = true;
14039                    } break;
14040
14041                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14042                        writeRuntimePermissions = true;
14043                        final int appId = ps.appId;
14044                        mHandler.post(new Runnable() {
14045                            @Override
14046                            public void run() {
14047                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14048                            }
14049                        });
14050                    } break;
14051                }
14052            }
14053        }
14054
14055        // Synchronously write as we are taking permissions away.
14056        if (writeRuntimePermissions) {
14057            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14058        }
14059
14060        // Synchronously write as we are taking permissions away.
14061        if (writeInstallPermissions) {
14062            mSettings.writeLPr();
14063        }
14064    }
14065
14066    /**
14067     * Remove entries from the keystore daemon. Will only remove it if the
14068     * {@code appId} is valid.
14069     */
14070    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14071        if (appId < 0) {
14072            return;
14073        }
14074
14075        final KeyStore keyStore = KeyStore.getInstance();
14076        if (keyStore != null) {
14077            if (userId == UserHandle.USER_ALL) {
14078                for (final int individual : sUserManager.getUserIds()) {
14079                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14080                }
14081            } else {
14082                keyStore.clearUid(UserHandle.getUid(userId, appId));
14083            }
14084        } else {
14085            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14086        }
14087    }
14088
14089    @Override
14090    public void deleteApplicationCacheFiles(final String packageName,
14091            final IPackageDataObserver observer) {
14092        mContext.enforceCallingOrSelfPermission(
14093                android.Manifest.permission.DELETE_CACHE_FILES, null);
14094        // Queue up an async operation since the package deletion may take a little while.
14095        final int userId = UserHandle.getCallingUserId();
14096        mHandler.post(new Runnable() {
14097            public void run() {
14098                mHandler.removeCallbacks(this);
14099                final boolean succeded;
14100                synchronized (mInstallLock) {
14101                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14102                }
14103                clearExternalStorageDataSync(packageName, userId, false);
14104                if (observer != null) {
14105                    try {
14106                        observer.onRemoveCompleted(packageName, succeded);
14107                    } catch (RemoteException e) {
14108                        Log.i(TAG, "Observer no longer exists.");
14109                    }
14110                } //end if observer
14111            } //end run
14112        });
14113    }
14114
14115    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14116        if (packageName == null) {
14117            Slog.w(TAG, "Attempt to delete null packageName.");
14118            return false;
14119        }
14120        PackageParser.Package p;
14121        synchronized (mPackages) {
14122            p = mPackages.get(packageName);
14123        }
14124        if (p == null) {
14125            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14126            return false;
14127        }
14128        final ApplicationInfo applicationInfo = p.applicationInfo;
14129        if (applicationInfo == null) {
14130            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14131            return false;
14132        }
14133        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14134        if (retCode < 0) {
14135            Slog.w(TAG, "Couldn't remove cache files for package: "
14136                       + packageName + " u" + userId);
14137            return false;
14138        }
14139        return true;
14140    }
14141
14142    @Override
14143    public void getPackageSizeInfo(final String packageName, int userHandle,
14144            final IPackageStatsObserver observer) {
14145        mContext.enforceCallingOrSelfPermission(
14146                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14147        if (packageName == null) {
14148            throw new IllegalArgumentException("Attempt to get size of null packageName");
14149        }
14150
14151        PackageStats stats = new PackageStats(packageName, userHandle);
14152
14153        /*
14154         * Queue up an async operation since the package measurement may take a
14155         * little while.
14156         */
14157        Message msg = mHandler.obtainMessage(INIT_COPY);
14158        msg.obj = new MeasureParams(stats, observer);
14159        mHandler.sendMessage(msg);
14160    }
14161
14162    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14163            PackageStats pStats) {
14164        if (packageName == null) {
14165            Slog.w(TAG, "Attempt to get size of null packageName.");
14166            return false;
14167        }
14168        PackageParser.Package p;
14169        boolean dataOnly = false;
14170        String libDirRoot = null;
14171        String asecPath = null;
14172        PackageSetting ps = null;
14173        synchronized (mPackages) {
14174            p = mPackages.get(packageName);
14175            ps = mSettings.mPackages.get(packageName);
14176            if(p == null) {
14177                dataOnly = true;
14178                if((ps == null) || (ps.pkg == null)) {
14179                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14180                    return false;
14181                }
14182                p = ps.pkg;
14183            }
14184            if (ps != null) {
14185                libDirRoot = ps.legacyNativeLibraryPathString;
14186            }
14187            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14188                final long token = Binder.clearCallingIdentity();
14189                try {
14190                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14191                    if (secureContainerId != null) {
14192                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14193                    }
14194                } finally {
14195                    Binder.restoreCallingIdentity(token);
14196                }
14197            }
14198        }
14199        String publicSrcDir = null;
14200        if(!dataOnly) {
14201            final ApplicationInfo applicationInfo = p.applicationInfo;
14202            if (applicationInfo == null) {
14203                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14204                return false;
14205            }
14206            if (p.isForwardLocked()) {
14207                publicSrcDir = applicationInfo.getBaseResourcePath();
14208            }
14209        }
14210        // TODO: extend to measure size of split APKs
14211        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14212        // not just the first level.
14213        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14214        // just the primary.
14215        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14216
14217        String apkPath;
14218        File packageDir = new File(p.codePath);
14219
14220        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14221            apkPath = packageDir.getAbsolutePath();
14222            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14223            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14224                libDirRoot = null;
14225            }
14226        } else {
14227            apkPath = p.baseCodePath;
14228        }
14229
14230        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14231                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14232        if (res < 0) {
14233            return false;
14234        }
14235
14236        // Fix-up for forward-locked applications in ASEC containers.
14237        if (!isExternal(p)) {
14238            pStats.codeSize += pStats.externalCodeSize;
14239            pStats.externalCodeSize = 0L;
14240        }
14241
14242        return true;
14243    }
14244
14245
14246    @Override
14247    public void addPackageToPreferred(String packageName) {
14248        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14249    }
14250
14251    @Override
14252    public void removePackageFromPreferred(String packageName) {
14253        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14254    }
14255
14256    @Override
14257    public List<PackageInfo> getPreferredPackages(int flags) {
14258        return new ArrayList<PackageInfo>();
14259    }
14260
14261    private int getUidTargetSdkVersionLockedLPr(int uid) {
14262        Object obj = mSettings.getUserIdLPr(uid);
14263        if (obj instanceof SharedUserSetting) {
14264            final SharedUserSetting sus = (SharedUserSetting) obj;
14265            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14266            final Iterator<PackageSetting> it = sus.packages.iterator();
14267            while (it.hasNext()) {
14268                final PackageSetting ps = it.next();
14269                if (ps.pkg != null) {
14270                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14271                    if (v < vers) vers = v;
14272                }
14273            }
14274            return vers;
14275        } else if (obj instanceof PackageSetting) {
14276            final PackageSetting ps = (PackageSetting) obj;
14277            if (ps.pkg != null) {
14278                return ps.pkg.applicationInfo.targetSdkVersion;
14279            }
14280        }
14281        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14282    }
14283
14284    @Override
14285    public void addPreferredActivity(IntentFilter filter, int match,
14286            ComponentName[] set, ComponentName activity, int userId) {
14287        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14288                "Adding preferred");
14289    }
14290
14291    private void addPreferredActivityInternal(IntentFilter filter, int match,
14292            ComponentName[] set, ComponentName activity, boolean always, int userId,
14293            String opname) {
14294        // writer
14295        int callingUid = Binder.getCallingUid();
14296        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14297        if (filter.countActions() == 0) {
14298            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14299            return;
14300        }
14301        synchronized (mPackages) {
14302            if (mContext.checkCallingOrSelfPermission(
14303                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14304                    != PackageManager.PERMISSION_GRANTED) {
14305                if (getUidTargetSdkVersionLockedLPr(callingUid)
14306                        < Build.VERSION_CODES.FROYO) {
14307                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14308                            + callingUid);
14309                    return;
14310                }
14311                mContext.enforceCallingOrSelfPermission(
14312                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14313            }
14314
14315            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14316            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14317                    + userId + ":");
14318            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14319            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14320            scheduleWritePackageRestrictionsLocked(userId);
14321        }
14322    }
14323
14324    @Override
14325    public void replacePreferredActivity(IntentFilter filter, int match,
14326            ComponentName[] set, ComponentName activity, int userId) {
14327        if (filter.countActions() != 1) {
14328            throw new IllegalArgumentException(
14329                    "replacePreferredActivity expects filter to have only 1 action.");
14330        }
14331        if (filter.countDataAuthorities() != 0
14332                || filter.countDataPaths() != 0
14333                || filter.countDataSchemes() > 1
14334                || filter.countDataTypes() != 0) {
14335            throw new IllegalArgumentException(
14336                    "replacePreferredActivity expects filter to have no data authorities, " +
14337                    "paths, or types; and at most one scheme.");
14338        }
14339
14340        final int callingUid = Binder.getCallingUid();
14341        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14342        synchronized (mPackages) {
14343            if (mContext.checkCallingOrSelfPermission(
14344                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14345                    != PackageManager.PERMISSION_GRANTED) {
14346                if (getUidTargetSdkVersionLockedLPr(callingUid)
14347                        < Build.VERSION_CODES.FROYO) {
14348                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14349                            + Binder.getCallingUid());
14350                    return;
14351                }
14352                mContext.enforceCallingOrSelfPermission(
14353                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14354            }
14355
14356            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14357            if (pir != null) {
14358                // Get all of the existing entries that exactly match this filter.
14359                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14360                if (existing != null && existing.size() == 1) {
14361                    PreferredActivity cur = existing.get(0);
14362                    if (DEBUG_PREFERRED) {
14363                        Slog.i(TAG, "Checking replace of preferred:");
14364                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14365                        if (!cur.mPref.mAlways) {
14366                            Slog.i(TAG, "  -- CUR; not mAlways!");
14367                        } else {
14368                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14369                            Slog.i(TAG, "  -- CUR: mSet="
14370                                    + Arrays.toString(cur.mPref.mSetComponents));
14371                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14372                            Slog.i(TAG, "  -- NEW: mMatch="
14373                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14374                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14375                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14376                        }
14377                    }
14378                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14379                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14380                            && cur.mPref.sameSet(set)) {
14381                        // Setting the preferred activity to what it happens to be already
14382                        if (DEBUG_PREFERRED) {
14383                            Slog.i(TAG, "Replacing with same preferred activity "
14384                                    + cur.mPref.mShortComponent + " for user "
14385                                    + userId + ":");
14386                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14387                        }
14388                        return;
14389                    }
14390                }
14391
14392                if (existing != null) {
14393                    if (DEBUG_PREFERRED) {
14394                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14395                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14396                    }
14397                    for (int i = 0; i < existing.size(); i++) {
14398                        PreferredActivity pa = existing.get(i);
14399                        if (DEBUG_PREFERRED) {
14400                            Slog.i(TAG, "Removing existing preferred activity "
14401                                    + pa.mPref.mComponent + ":");
14402                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14403                        }
14404                        pir.removeFilter(pa);
14405                    }
14406                }
14407            }
14408            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14409                    "Replacing preferred");
14410        }
14411    }
14412
14413    @Override
14414    public void clearPackagePreferredActivities(String packageName) {
14415        final int uid = Binder.getCallingUid();
14416        // writer
14417        synchronized (mPackages) {
14418            PackageParser.Package pkg = mPackages.get(packageName);
14419            if (pkg == null || pkg.applicationInfo.uid != uid) {
14420                if (mContext.checkCallingOrSelfPermission(
14421                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14422                        != PackageManager.PERMISSION_GRANTED) {
14423                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14424                            < Build.VERSION_CODES.FROYO) {
14425                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14426                                + Binder.getCallingUid());
14427                        return;
14428                    }
14429                    mContext.enforceCallingOrSelfPermission(
14430                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14431                }
14432            }
14433
14434            int user = UserHandle.getCallingUserId();
14435            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14436                scheduleWritePackageRestrictionsLocked(user);
14437            }
14438        }
14439    }
14440
14441    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14442    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14443        ArrayList<PreferredActivity> removed = null;
14444        boolean changed = false;
14445        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14446            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14447            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14448            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14449                continue;
14450            }
14451            Iterator<PreferredActivity> it = pir.filterIterator();
14452            while (it.hasNext()) {
14453                PreferredActivity pa = it.next();
14454                // Mark entry for removal only if it matches the package name
14455                // and the entry is of type "always".
14456                if (packageName == null ||
14457                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14458                                && pa.mPref.mAlways)) {
14459                    if (removed == null) {
14460                        removed = new ArrayList<PreferredActivity>();
14461                    }
14462                    removed.add(pa);
14463                }
14464            }
14465            if (removed != null) {
14466                for (int j=0; j<removed.size(); j++) {
14467                    PreferredActivity pa = removed.get(j);
14468                    pir.removeFilter(pa);
14469                }
14470                changed = true;
14471            }
14472        }
14473        return changed;
14474    }
14475
14476    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14477    private void clearIntentFilterVerificationsLPw(int userId) {
14478        final int packageCount = mPackages.size();
14479        for (int i = 0; i < packageCount; i++) {
14480            PackageParser.Package pkg = mPackages.valueAt(i);
14481            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14482        }
14483    }
14484
14485    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14486    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14487        if (userId == UserHandle.USER_ALL) {
14488            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14489                    sUserManager.getUserIds())) {
14490                for (int oneUserId : sUserManager.getUserIds()) {
14491                    scheduleWritePackageRestrictionsLocked(oneUserId);
14492                }
14493            }
14494        } else {
14495            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14496                scheduleWritePackageRestrictionsLocked(userId);
14497            }
14498        }
14499    }
14500
14501    void clearDefaultBrowserIfNeeded(String packageName) {
14502        for (int oneUserId : sUserManager.getUserIds()) {
14503            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14504            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14505            if (packageName.equals(defaultBrowserPackageName)) {
14506                setDefaultBrowserPackageName(null, oneUserId);
14507            }
14508        }
14509    }
14510
14511    @Override
14512    public void resetApplicationPreferences(int userId) {
14513        mContext.enforceCallingOrSelfPermission(
14514                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14515        // writer
14516        synchronized (mPackages) {
14517            final long identity = Binder.clearCallingIdentity();
14518            try {
14519                clearPackagePreferredActivitiesLPw(null, userId);
14520                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14521                // TODO: We have to reset the default SMS and Phone. This requires
14522                // significant refactoring to keep all default apps in the package
14523                // manager (cleaner but more work) or have the services provide
14524                // callbacks to the package manager to request a default app reset.
14525                applyFactoryDefaultBrowserLPw(userId);
14526                clearIntentFilterVerificationsLPw(userId);
14527                primeDomainVerificationsLPw(userId);
14528                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14529                scheduleWritePackageRestrictionsLocked(userId);
14530            } finally {
14531                Binder.restoreCallingIdentity(identity);
14532            }
14533        }
14534    }
14535
14536    @Override
14537    public int getPreferredActivities(List<IntentFilter> outFilters,
14538            List<ComponentName> outActivities, String packageName) {
14539
14540        int num = 0;
14541        final int userId = UserHandle.getCallingUserId();
14542        // reader
14543        synchronized (mPackages) {
14544            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14545            if (pir != null) {
14546                final Iterator<PreferredActivity> it = pir.filterIterator();
14547                while (it.hasNext()) {
14548                    final PreferredActivity pa = it.next();
14549                    if (packageName == null
14550                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14551                                    && pa.mPref.mAlways)) {
14552                        if (outFilters != null) {
14553                            outFilters.add(new IntentFilter(pa));
14554                        }
14555                        if (outActivities != null) {
14556                            outActivities.add(pa.mPref.mComponent);
14557                        }
14558                    }
14559                }
14560            }
14561        }
14562
14563        return num;
14564    }
14565
14566    @Override
14567    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14568            int userId) {
14569        int callingUid = Binder.getCallingUid();
14570        if (callingUid != Process.SYSTEM_UID) {
14571            throw new SecurityException(
14572                    "addPersistentPreferredActivity can only be run by the system");
14573        }
14574        if (filter.countActions() == 0) {
14575            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14576            return;
14577        }
14578        synchronized (mPackages) {
14579            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14580                    " :");
14581            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14582            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14583                    new PersistentPreferredActivity(filter, activity));
14584            scheduleWritePackageRestrictionsLocked(userId);
14585        }
14586    }
14587
14588    @Override
14589    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14590        int callingUid = Binder.getCallingUid();
14591        if (callingUid != Process.SYSTEM_UID) {
14592            throw new SecurityException(
14593                    "clearPackagePersistentPreferredActivities can only be run by the system");
14594        }
14595        ArrayList<PersistentPreferredActivity> removed = null;
14596        boolean changed = false;
14597        synchronized (mPackages) {
14598            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14599                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14600                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14601                        .valueAt(i);
14602                if (userId != thisUserId) {
14603                    continue;
14604                }
14605                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14606                while (it.hasNext()) {
14607                    PersistentPreferredActivity ppa = it.next();
14608                    // Mark entry for removal only if it matches the package name.
14609                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14610                        if (removed == null) {
14611                            removed = new ArrayList<PersistentPreferredActivity>();
14612                        }
14613                        removed.add(ppa);
14614                    }
14615                }
14616                if (removed != null) {
14617                    for (int j=0; j<removed.size(); j++) {
14618                        PersistentPreferredActivity ppa = removed.get(j);
14619                        ppir.removeFilter(ppa);
14620                    }
14621                    changed = true;
14622                }
14623            }
14624
14625            if (changed) {
14626                scheduleWritePackageRestrictionsLocked(userId);
14627            }
14628        }
14629    }
14630
14631    /**
14632     * Common machinery for picking apart a restored XML blob and passing
14633     * it to a caller-supplied functor to be applied to the running system.
14634     */
14635    private void restoreFromXml(XmlPullParser parser, int userId,
14636            String expectedStartTag, BlobXmlRestorer functor)
14637            throws IOException, XmlPullParserException {
14638        int type;
14639        while ((type = parser.next()) != XmlPullParser.START_TAG
14640                && type != XmlPullParser.END_DOCUMENT) {
14641        }
14642        if (type != XmlPullParser.START_TAG) {
14643            // oops didn't find a start tag?!
14644            if (DEBUG_BACKUP) {
14645                Slog.e(TAG, "Didn't find start tag during restore");
14646            }
14647            return;
14648        }
14649
14650        // this is supposed to be TAG_PREFERRED_BACKUP
14651        if (!expectedStartTag.equals(parser.getName())) {
14652            if (DEBUG_BACKUP) {
14653                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14654            }
14655            return;
14656        }
14657
14658        // skip interfering stuff, then we're aligned with the backing implementation
14659        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14660        functor.apply(parser, userId);
14661    }
14662
14663    private interface BlobXmlRestorer {
14664        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14665    }
14666
14667    /**
14668     * Non-Binder method, support for the backup/restore mechanism: write the
14669     * full set of preferred activities in its canonical XML format.  Returns the
14670     * XML output as a byte array, or null if there is none.
14671     */
14672    @Override
14673    public byte[] getPreferredActivityBackup(int userId) {
14674        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14675            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14676        }
14677
14678        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14679        try {
14680            final XmlSerializer serializer = new FastXmlSerializer();
14681            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14682            serializer.startDocument(null, true);
14683            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14684
14685            synchronized (mPackages) {
14686                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14687            }
14688
14689            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14690            serializer.endDocument();
14691            serializer.flush();
14692        } catch (Exception e) {
14693            if (DEBUG_BACKUP) {
14694                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14695            }
14696            return null;
14697        }
14698
14699        return dataStream.toByteArray();
14700    }
14701
14702    @Override
14703    public void restorePreferredActivities(byte[] backup, int userId) {
14704        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14705            throw new SecurityException("Only the system may call restorePreferredActivities()");
14706        }
14707
14708        try {
14709            final XmlPullParser parser = Xml.newPullParser();
14710            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14711            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14712                    new BlobXmlRestorer() {
14713                        @Override
14714                        public void apply(XmlPullParser parser, int userId)
14715                                throws XmlPullParserException, IOException {
14716                            synchronized (mPackages) {
14717                                mSettings.readPreferredActivitiesLPw(parser, userId);
14718                            }
14719                        }
14720                    } );
14721        } catch (Exception e) {
14722            if (DEBUG_BACKUP) {
14723                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14724            }
14725        }
14726    }
14727
14728    /**
14729     * Non-Binder method, support for the backup/restore mechanism: write the
14730     * default browser (etc) settings in its canonical XML format.  Returns the default
14731     * browser XML representation as a byte array, or null if there is none.
14732     */
14733    @Override
14734    public byte[] getDefaultAppsBackup(int userId) {
14735        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14736            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14737        }
14738
14739        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14740        try {
14741            final XmlSerializer serializer = new FastXmlSerializer();
14742            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14743            serializer.startDocument(null, true);
14744            serializer.startTag(null, TAG_DEFAULT_APPS);
14745
14746            synchronized (mPackages) {
14747                mSettings.writeDefaultAppsLPr(serializer, userId);
14748            }
14749
14750            serializer.endTag(null, TAG_DEFAULT_APPS);
14751            serializer.endDocument();
14752            serializer.flush();
14753        } catch (Exception e) {
14754            if (DEBUG_BACKUP) {
14755                Slog.e(TAG, "Unable to write default apps for backup", e);
14756            }
14757            return null;
14758        }
14759
14760        return dataStream.toByteArray();
14761    }
14762
14763    @Override
14764    public void restoreDefaultApps(byte[] backup, int userId) {
14765        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14766            throw new SecurityException("Only the system may call restoreDefaultApps()");
14767        }
14768
14769        try {
14770            final XmlPullParser parser = Xml.newPullParser();
14771            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14772            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14773                    new BlobXmlRestorer() {
14774                        @Override
14775                        public void apply(XmlPullParser parser, int userId)
14776                                throws XmlPullParserException, IOException {
14777                            synchronized (mPackages) {
14778                                mSettings.readDefaultAppsLPw(parser, userId);
14779                            }
14780                        }
14781                    } );
14782        } catch (Exception e) {
14783            if (DEBUG_BACKUP) {
14784                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14785            }
14786        }
14787    }
14788
14789    @Override
14790    public byte[] getIntentFilterVerificationBackup(int userId) {
14791        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14792            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14793        }
14794
14795        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14796        try {
14797            final XmlSerializer serializer = new FastXmlSerializer();
14798            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14799            serializer.startDocument(null, true);
14800            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14801
14802            synchronized (mPackages) {
14803                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14804            }
14805
14806            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14807            serializer.endDocument();
14808            serializer.flush();
14809        } catch (Exception e) {
14810            if (DEBUG_BACKUP) {
14811                Slog.e(TAG, "Unable to write default apps for backup", e);
14812            }
14813            return null;
14814        }
14815
14816        return dataStream.toByteArray();
14817    }
14818
14819    @Override
14820    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14821        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14822            throw new SecurityException("Only the system may call restorePreferredActivities()");
14823        }
14824
14825        try {
14826            final XmlPullParser parser = Xml.newPullParser();
14827            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14828            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14829                    new BlobXmlRestorer() {
14830                        @Override
14831                        public void apply(XmlPullParser parser, int userId)
14832                                throws XmlPullParserException, IOException {
14833                            synchronized (mPackages) {
14834                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14835                                mSettings.writeLPr();
14836                            }
14837                        }
14838                    } );
14839        } catch (Exception e) {
14840            if (DEBUG_BACKUP) {
14841                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14842            }
14843        }
14844    }
14845
14846    @Override
14847    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14848            int sourceUserId, int targetUserId, int flags) {
14849        mContext.enforceCallingOrSelfPermission(
14850                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14851        int callingUid = Binder.getCallingUid();
14852        enforceOwnerRights(ownerPackage, callingUid);
14853        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14854        if (intentFilter.countActions() == 0) {
14855            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14856            return;
14857        }
14858        synchronized (mPackages) {
14859            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14860                    ownerPackage, targetUserId, flags);
14861            CrossProfileIntentResolver resolver =
14862                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14863            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14864            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14865            if (existing != null) {
14866                int size = existing.size();
14867                for (int i = 0; i < size; i++) {
14868                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14869                        return;
14870                    }
14871                }
14872            }
14873            resolver.addFilter(newFilter);
14874            scheduleWritePackageRestrictionsLocked(sourceUserId);
14875        }
14876    }
14877
14878    @Override
14879    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14880        mContext.enforceCallingOrSelfPermission(
14881                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14882        int callingUid = Binder.getCallingUid();
14883        enforceOwnerRights(ownerPackage, callingUid);
14884        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14885        synchronized (mPackages) {
14886            CrossProfileIntentResolver resolver =
14887                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14888            ArraySet<CrossProfileIntentFilter> set =
14889                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14890            for (CrossProfileIntentFilter filter : set) {
14891                if (filter.getOwnerPackage().equals(ownerPackage)) {
14892                    resolver.removeFilter(filter);
14893                }
14894            }
14895            scheduleWritePackageRestrictionsLocked(sourceUserId);
14896        }
14897    }
14898
14899    // Enforcing that callingUid is owning pkg on userId
14900    private void enforceOwnerRights(String pkg, int callingUid) {
14901        // The system owns everything.
14902        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14903            return;
14904        }
14905        int callingUserId = UserHandle.getUserId(callingUid);
14906        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14907        if (pi == null) {
14908            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14909                    + callingUserId);
14910        }
14911        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14912            throw new SecurityException("Calling uid " + callingUid
14913                    + " does not own package " + pkg);
14914        }
14915    }
14916
14917    @Override
14918    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14919        Intent intent = new Intent(Intent.ACTION_MAIN);
14920        intent.addCategory(Intent.CATEGORY_HOME);
14921
14922        final int callingUserId = UserHandle.getCallingUserId();
14923        List<ResolveInfo> list = queryIntentActivities(intent, null,
14924                PackageManager.GET_META_DATA, callingUserId);
14925        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14926                true, false, false, callingUserId);
14927
14928        allHomeCandidates.clear();
14929        if (list != null) {
14930            for (ResolveInfo ri : list) {
14931                allHomeCandidates.add(ri);
14932            }
14933        }
14934        return (preferred == null || preferred.activityInfo == null)
14935                ? null
14936                : new ComponentName(preferred.activityInfo.packageName,
14937                        preferred.activityInfo.name);
14938    }
14939
14940    @Override
14941    public void setApplicationEnabledSetting(String appPackageName,
14942            int newState, int flags, int userId, String callingPackage) {
14943        if (!sUserManager.exists(userId)) return;
14944        if (callingPackage == null) {
14945            callingPackage = Integer.toString(Binder.getCallingUid());
14946        }
14947        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14948    }
14949
14950    @Override
14951    public void setComponentEnabledSetting(ComponentName componentName,
14952            int newState, int flags, int userId) {
14953        if (!sUserManager.exists(userId)) return;
14954        setEnabledSetting(componentName.getPackageName(),
14955                componentName.getClassName(), newState, flags, userId, null);
14956    }
14957
14958    private void setEnabledSetting(final String packageName, String className, int newState,
14959            final int flags, int userId, String callingPackage) {
14960        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14961              || newState == COMPONENT_ENABLED_STATE_ENABLED
14962              || newState == COMPONENT_ENABLED_STATE_DISABLED
14963              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14964              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14965            throw new IllegalArgumentException("Invalid new component state: "
14966                    + newState);
14967        }
14968        PackageSetting pkgSetting;
14969        final int uid = Binder.getCallingUid();
14970        final int permission = mContext.checkCallingOrSelfPermission(
14971                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14972        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14973        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14974        boolean sendNow = false;
14975        boolean isApp = (className == null);
14976        String componentName = isApp ? packageName : className;
14977        int packageUid = -1;
14978        ArrayList<String> components;
14979
14980        // writer
14981        synchronized (mPackages) {
14982            pkgSetting = mSettings.mPackages.get(packageName);
14983            if (pkgSetting == null) {
14984                if (className == null) {
14985                    throw new IllegalArgumentException(
14986                            "Unknown package: " + packageName);
14987                }
14988                throw new IllegalArgumentException(
14989                        "Unknown component: " + packageName
14990                        + "/" + className);
14991            }
14992            // Allow root and verify that userId is not being specified by a different user
14993            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14994                throw new SecurityException(
14995                        "Permission Denial: attempt to change component state from pid="
14996                        + Binder.getCallingPid()
14997                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14998            }
14999            if (className == null) {
15000                // We're dealing with an application/package level state change
15001                if (pkgSetting.getEnabled(userId) == newState) {
15002                    // Nothing to do
15003                    return;
15004                }
15005                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15006                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15007                    // Don't care about who enables an app.
15008                    callingPackage = null;
15009                }
15010                pkgSetting.setEnabled(newState, userId, callingPackage);
15011                // pkgSetting.pkg.mSetEnabled = newState;
15012            } else {
15013                // We're dealing with a component level state change
15014                // First, verify that this is a valid class name.
15015                PackageParser.Package pkg = pkgSetting.pkg;
15016                if (pkg == null || !pkg.hasComponentClassName(className)) {
15017                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
15018                        throw new IllegalArgumentException("Component class " + className
15019                                + " does not exist in " + packageName);
15020                    } else {
15021                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15022                                + className + " does not exist in " + packageName);
15023                    }
15024                }
15025                switch (newState) {
15026                case COMPONENT_ENABLED_STATE_ENABLED:
15027                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15028                        return;
15029                    }
15030                    break;
15031                case COMPONENT_ENABLED_STATE_DISABLED:
15032                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15033                        return;
15034                    }
15035                    break;
15036                case COMPONENT_ENABLED_STATE_DEFAULT:
15037                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15038                        return;
15039                    }
15040                    break;
15041                default:
15042                    Slog.e(TAG, "Invalid new component state: " + newState);
15043                    return;
15044                }
15045            }
15046            scheduleWritePackageRestrictionsLocked(userId);
15047            components = mPendingBroadcasts.get(userId, packageName);
15048            final boolean newPackage = components == null;
15049            if (newPackage) {
15050                components = new ArrayList<String>();
15051            }
15052            if (!components.contains(componentName)) {
15053                components.add(componentName);
15054            }
15055            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15056                sendNow = true;
15057                // Purge entry from pending broadcast list if another one exists already
15058                // since we are sending one right away.
15059                mPendingBroadcasts.remove(userId, packageName);
15060            } else {
15061                if (newPackage) {
15062                    mPendingBroadcasts.put(userId, packageName, components);
15063                }
15064                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15065                    // Schedule a message
15066                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15067                }
15068            }
15069        }
15070
15071        long callingId = Binder.clearCallingIdentity();
15072        try {
15073            if (sendNow) {
15074                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15075                sendPackageChangedBroadcast(packageName,
15076                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15077            }
15078        } finally {
15079            Binder.restoreCallingIdentity(callingId);
15080        }
15081    }
15082
15083    private void sendPackageChangedBroadcast(String packageName,
15084            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15085        if (DEBUG_INSTALL)
15086            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15087                    + componentNames);
15088        Bundle extras = new Bundle(4);
15089        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15090        String nameList[] = new String[componentNames.size()];
15091        componentNames.toArray(nameList);
15092        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15093        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15094        extras.putInt(Intent.EXTRA_UID, packageUid);
15095        // If this is not reporting a change of the overall package, then only send it
15096        // to registered receivers.  We don't want to launch a swath of apps for every
15097        // little component state change.
15098        final int flags = !componentNames.contains(packageName)
15099                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15100        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15101                new int[] {UserHandle.getUserId(packageUid)});
15102    }
15103
15104    @Override
15105    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15106        if (!sUserManager.exists(userId)) return;
15107        final int uid = Binder.getCallingUid();
15108        final int permission = mContext.checkCallingOrSelfPermission(
15109                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15110        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15111        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15112        // writer
15113        synchronized (mPackages) {
15114            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15115                    allowedByPermission, uid, userId)) {
15116                scheduleWritePackageRestrictionsLocked(userId);
15117            }
15118        }
15119    }
15120
15121    @Override
15122    public String getInstallerPackageName(String packageName) {
15123        // reader
15124        synchronized (mPackages) {
15125            return mSettings.getInstallerPackageNameLPr(packageName);
15126        }
15127    }
15128
15129    @Override
15130    public int getApplicationEnabledSetting(String packageName, int userId) {
15131        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15132        int uid = Binder.getCallingUid();
15133        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15134        // reader
15135        synchronized (mPackages) {
15136            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15137        }
15138    }
15139
15140    @Override
15141    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15142        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15143        int uid = Binder.getCallingUid();
15144        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15145        // reader
15146        synchronized (mPackages) {
15147            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15148        }
15149    }
15150
15151    @Override
15152    public void enterSafeMode() {
15153        enforceSystemOrRoot("Only the system can request entering safe mode");
15154
15155        if (!mSystemReady) {
15156            mSafeMode = true;
15157        }
15158    }
15159
15160    @Override
15161    public void systemReady() {
15162        mSystemReady = true;
15163
15164        // Read the compatibilty setting when the system is ready.
15165        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15166                mContext.getContentResolver(),
15167                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15168        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15169        if (DEBUG_SETTINGS) {
15170            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15171        }
15172
15173        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15174
15175        synchronized (mPackages) {
15176            // Verify that all of the preferred activity components actually
15177            // exist.  It is possible for applications to be updated and at
15178            // that point remove a previously declared activity component that
15179            // had been set as a preferred activity.  We try to clean this up
15180            // the next time we encounter that preferred activity, but it is
15181            // possible for the user flow to never be able to return to that
15182            // situation so here we do a sanity check to make sure we haven't
15183            // left any junk around.
15184            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15185            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15186                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15187                removed.clear();
15188                for (PreferredActivity pa : pir.filterSet()) {
15189                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15190                        removed.add(pa);
15191                    }
15192                }
15193                if (removed.size() > 0) {
15194                    for (int r=0; r<removed.size(); r++) {
15195                        PreferredActivity pa = removed.get(r);
15196                        Slog.w(TAG, "Removing dangling preferred activity: "
15197                                + pa.mPref.mComponent);
15198                        pir.removeFilter(pa);
15199                    }
15200                    mSettings.writePackageRestrictionsLPr(
15201                            mSettings.mPreferredActivities.keyAt(i));
15202                }
15203            }
15204
15205            for (int userId : UserManagerService.getInstance().getUserIds()) {
15206                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15207                    grantPermissionsUserIds = ArrayUtils.appendInt(
15208                            grantPermissionsUserIds, userId);
15209                }
15210            }
15211        }
15212        sUserManager.systemReady();
15213
15214        // If we upgraded grant all default permissions before kicking off.
15215        for (int userId : grantPermissionsUserIds) {
15216            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15217        }
15218
15219        // Kick off any messages waiting for system ready
15220        if (mPostSystemReadyMessages != null) {
15221            for (Message msg : mPostSystemReadyMessages) {
15222                msg.sendToTarget();
15223            }
15224            mPostSystemReadyMessages = null;
15225        }
15226
15227        // Watch for external volumes that come and go over time
15228        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15229        storage.registerListener(mStorageListener);
15230
15231        mInstallerService.systemReady();
15232        mPackageDexOptimizer.systemReady();
15233
15234        MountServiceInternal mountServiceInternal = LocalServices.getService(
15235                MountServiceInternal.class);
15236        mountServiceInternal.addExternalStoragePolicy(
15237                new MountServiceInternal.ExternalStorageMountPolicy() {
15238            @Override
15239            public int getMountMode(int uid, String packageName) {
15240                if (Process.isIsolated(uid)) {
15241                    return Zygote.MOUNT_EXTERNAL_NONE;
15242                }
15243                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15244                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15245                }
15246                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15247                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15248                }
15249                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15250                    return Zygote.MOUNT_EXTERNAL_READ;
15251                }
15252                return Zygote.MOUNT_EXTERNAL_WRITE;
15253            }
15254
15255            @Override
15256            public boolean hasExternalStorage(int uid, String packageName) {
15257                return true;
15258            }
15259        });
15260    }
15261
15262    @Override
15263    public boolean isSafeMode() {
15264        return mSafeMode;
15265    }
15266
15267    @Override
15268    public boolean hasSystemUidErrors() {
15269        return mHasSystemUidErrors;
15270    }
15271
15272    static String arrayToString(int[] array) {
15273        StringBuffer buf = new StringBuffer(128);
15274        buf.append('[');
15275        if (array != null) {
15276            for (int i=0; i<array.length; i++) {
15277                if (i > 0) buf.append(", ");
15278                buf.append(array[i]);
15279            }
15280        }
15281        buf.append(']');
15282        return buf.toString();
15283    }
15284
15285    static class DumpState {
15286        public static final int DUMP_LIBS = 1 << 0;
15287        public static final int DUMP_FEATURES = 1 << 1;
15288        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15289        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15290        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15291        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15292        public static final int DUMP_PERMISSIONS = 1 << 6;
15293        public static final int DUMP_PACKAGES = 1 << 7;
15294        public static final int DUMP_SHARED_USERS = 1 << 8;
15295        public static final int DUMP_MESSAGES = 1 << 9;
15296        public static final int DUMP_PROVIDERS = 1 << 10;
15297        public static final int DUMP_VERIFIERS = 1 << 11;
15298        public static final int DUMP_PREFERRED = 1 << 12;
15299        public static final int DUMP_PREFERRED_XML = 1 << 13;
15300        public static final int DUMP_KEYSETS = 1 << 14;
15301        public static final int DUMP_VERSION = 1 << 15;
15302        public static final int DUMP_INSTALLS = 1 << 16;
15303        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15304        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15305
15306        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15307
15308        private int mTypes;
15309
15310        private int mOptions;
15311
15312        private boolean mTitlePrinted;
15313
15314        private SharedUserSetting mSharedUser;
15315
15316        public boolean isDumping(int type) {
15317            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15318                return true;
15319            }
15320
15321            return (mTypes & type) != 0;
15322        }
15323
15324        public void setDump(int type) {
15325            mTypes |= type;
15326        }
15327
15328        public boolean isOptionEnabled(int option) {
15329            return (mOptions & option) != 0;
15330        }
15331
15332        public void setOptionEnabled(int option) {
15333            mOptions |= option;
15334        }
15335
15336        public boolean onTitlePrinted() {
15337            final boolean printed = mTitlePrinted;
15338            mTitlePrinted = true;
15339            return printed;
15340        }
15341
15342        public boolean getTitlePrinted() {
15343            return mTitlePrinted;
15344        }
15345
15346        public void setTitlePrinted(boolean enabled) {
15347            mTitlePrinted = enabled;
15348        }
15349
15350        public SharedUserSetting getSharedUser() {
15351            return mSharedUser;
15352        }
15353
15354        public void setSharedUser(SharedUserSetting user) {
15355            mSharedUser = user;
15356        }
15357    }
15358
15359    @Override
15360    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15361            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15362        (new PackageManagerShellCommand(this)).exec(
15363                this, in, out, err, args, resultReceiver);
15364    }
15365
15366    @Override
15367    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15368        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15369                != PackageManager.PERMISSION_GRANTED) {
15370            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15371                    + Binder.getCallingPid()
15372                    + ", uid=" + Binder.getCallingUid()
15373                    + " without permission "
15374                    + android.Manifest.permission.DUMP);
15375            return;
15376        }
15377
15378        DumpState dumpState = new DumpState();
15379        boolean fullPreferred = false;
15380        boolean checkin = false;
15381
15382        String packageName = null;
15383        ArraySet<String> permissionNames = null;
15384
15385        int opti = 0;
15386        while (opti < args.length) {
15387            String opt = args[opti];
15388            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15389                break;
15390            }
15391            opti++;
15392
15393            if ("-a".equals(opt)) {
15394                // Right now we only know how to print all.
15395            } else if ("-h".equals(opt)) {
15396                pw.println("Package manager dump options:");
15397                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15398                pw.println("    --checkin: dump for a checkin");
15399                pw.println("    -f: print details of intent filters");
15400                pw.println("    -h: print this help");
15401                pw.println("  cmd may be one of:");
15402                pw.println("    l[ibraries]: list known shared libraries");
15403                pw.println("    f[eatures]: list device features");
15404                pw.println("    k[eysets]: print known keysets");
15405                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15406                pw.println("    perm[issions]: dump permissions");
15407                pw.println("    permission [name ...]: dump declaration and use of given permission");
15408                pw.println("    pref[erred]: print preferred package settings");
15409                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15410                pw.println("    prov[iders]: dump content providers");
15411                pw.println("    p[ackages]: dump installed packages");
15412                pw.println("    s[hared-users]: dump shared user IDs");
15413                pw.println("    m[essages]: print collected runtime messages");
15414                pw.println("    v[erifiers]: print package verifier info");
15415                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15416                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15417                pw.println("    version: print database version info");
15418                pw.println("    write: write current settings now");
15419                pw.println("    installs: details about install sessions");
15420                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15421                pw.println("    <package.name>: info about given package");
15422                return;
15423            } else if ("--checkin".equals(opt)) {
15424                checkin = true;
15425            } else if ("-f".equals(opt)) {
15426                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15427            } else {
15428                pw.println("Unknown argument: " + opt + "; use -h for help");
15429            }
15430        }
15431
15432        // Is the caller requesting to dump a particular piece of data?
15433        if (opti < args.length) {
15434            String cmd = args[opti];
15435            opti++;
15436            // Is this a package name?
15437            if ("android".equals(cmd) || cmd.contains(".")) {
15438                packageName = cmd;
15439                // When dumping a single package, we always dump all of its
15440                // filter information since the amount of data will be reasonable.
15441                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15442            } else if ("check-permission".equals(cmd)) {
15443                if (opti >= args.length) {
15444                    pw.println("Error: check-permission missing permission argument");
15445                    return;
15446                }
15447                String perm = args[opti];
15448                opti++;
15449                if (opti >= args.length) {
15450                    pw.println("Error: check-permission missing package argument");
15451                    return;
15452                }
15453                String pkg = args[opti];
15454                opti++;
15455                int user = UserHandle.getUserId(Binder.getCallingUid());
15456                if (opti < args.length) {
15457                    try {
15458                        user = Integer.parseInt(args[opti]);
15459                    } catch (NumberFormatException e) {
15460                        pw.println("Error: check-permission user argument is not a number: "
15461                                + args[opti]);
15462                        return;
15463                    }
15464                }
15465                pw.println(checkPermission(perm, pkg, user));
15466                return;
15467            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15468                dumpState.setDump(DumpState.DUMP_LIBS);
15469            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15470                dumpState.setDump(DumpState.DUMP_FEATURES);
15471            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15472                if (opti >= args.length) {
15473                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15474                            | DumpState.DUMP_SERVICE_RESOLVERS
15475                            | DumpState.DUMP_RECEIVER_RESOLVERS
15476                            | DumpState.DUMP_CONTENT_RESOLVERS);
15477                } else {
15478                    while (opti < args.length) {
15479                        String name = args[opti];
15480                        if ("a".equals(name) || "activity".equals(name)) {
15481                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15482                        } else if ("s".equals(name) || "service".equals(name)) {
15483                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15484                        } else if ("r".equals(name) || "receiver".equals(name)) {
15485                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15486                        } else if ("c".equals(name) || "content".equals(name)) {
15487                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15488                        } else {
15489                            pw.println("Error: unknown resolver table type: " + name);
15490                            return;
15491                        }
15492                        opti++;
15493                    }
15494                }
15495            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15496                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15497            } else if ("permission".equals(cmd)) {
15498                if (opti >= args.length) {
15499                    pw.println("Error: permission requires permission name");
15500                    return;
15501                }
15502                permissionNames = new ArraySet<>();
15503                while (opti < args.length) {
15504                    permissionNames.add(args[opti]);
15505                    opti++;
15506                }
15507                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15508                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15509            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15510                dumpState.setDump(DumpState.DUMP_PREFERRED);
15511            } else if ("preferred-xml".equals(cmd)) {
15512                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15513                if (opti < args.length && "--full".equals(args[opti])) {
15514                    fullPreferred = true;
15515                    opti++;
15516                }
15517            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15518                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15519            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15520                dumpState.setDump(DumpState.DUMP_PACKAGES);
15521            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15522                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15523            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15524                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15525            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15526                dumpState.setDump(DumpState.DUMP_MESSAGES);
15527            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15528                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15529            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15530                    || "intent-filter-verifiers".equals(cmd)) {
15531                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15532            } else if ("version".equals(cmd)) {
15533                dumpState.setDump(DumpState.DUMP_VERSION);
15534            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15535                dumpState.setDump(DumpState.DUMP_KEYSETS);
15536            } else if ("installs".equals(cmd)) {
15537                dumpState.setDump(DumpState.DUMP_INSTALLS);
15538            } else if ("write".equals(cmd)) {
15539                synchronized (mPackages) {
15540                    mSettings.writeLPr();
15541                    pw.println("Settings written.");
15542                    return;
15543                }
15544            }
15545        }
15546
15547        if (checkin) {
15548            pw.println("vers,1");
15549        }
15550
15551        // reader
15552        synchronized (mPackages) {
15553            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15554                if (!checkin) {
15555                    if (dumpState.onTitlePrinted())
15556                        pw.println();
15557                    pw.println("Database versions:");
15558                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15559                }
15560            }
15561
15562            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15563                if (!checkin) {
15564                    if (dumpState.onTitlePrinted())
15565                        pw.println();
15566                    pw.println("Verifiers:");
15567                    pw.print("  Required: ");
15568                    pw.print(mRequiredVerifierPackage);
15569                    pw.print(" (uid=");
15570                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15571                    pw.println(")");
15572                } else if (mRequiredVerifierPackage != null) {
15573                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15574                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15575                }
15576            }
15577
15578            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15579                    packageName == null) {
15580                if (mIntentFilterVerifierComponent != null) {
15581                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15582                    if (!checkin) {
15583                        if (dumpState.onTitlePrinted())
15584                            pw.println();
15585                        pw.println("Intent Filter Verifier:");
15586                        pw.print("  Using: ");
15587                        pw.print(verifierPackageName);
15588                        pw.print(" (uid=");
15589                        pw.print(getPackageUid(verifierPackageName, 0));
15590                        pw.println(")");
15591                    } else if (verifierPackageName != null) {
15592                        pw.print("ifv,"); pw.print(verifierPackageName);
15593                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15594                    }
15595                } else {
15596                    pw.println();
15597                    pw.println("No Intent Filter Verifier available!");
15598                }
15599            }
15600
15601            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15602                boolean printedHeader = false;
15603                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15604                while (it.hasNext()) {
15605                    String name = it.next();
15606                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15607                    if (!checkin) {
15608                        if (!printedHeader) {
15609                            if (dumpState.onTitlePrinted())
15610                                pw.println();
15611                            pw.println("Libraries:");
15612                            printedHeader = true;
15613                        }
15614                        pw.print("  ");
15615                    } else {
15616                        pw.print("lib,");
15617                    }
15618                    pw.print(name);
15619                    if (!checkin) {
15620                        pw.print(" -> ");
15621                    }
15622                    if (ent.path != null) {
15623                        if (!checkin) {
15624                            pw.print("(jar) ");
15625                            pw.print(ent.path);
15626                        } else {
15627                            pw.print(",jar,");
15628                            pw.print(ent.path);
15629                        }
15630                    } else {
15631                        if (!checkin) {
15632                            pw.print("(apk) ");
15633                            pw.print(ent.apk);
15634                        } else {
15635                            pw.print(",apk,");
15636                            pw.print(ent.apk);
15637                        }
15638                    }
15639                    pw.println();
15640                }
15641            }
15642
15643            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15644                if (dumpState.onTitlePrinted())
15645                    pw.println();
15646                if (!checkin) {
15647                    pw.println("Features:");
15648                }
15649                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15650                while (it.hasNext()) {
15651                    String name = it.next();
15652                    if (!checkin) {
15653                        pw.print("  ");
15654                    } else {
15655                        pw.print("feat,");
15656                    }
15657                    pw.println(name);
15658                }
15659            }
15660
15661            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15662                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15663                        : "Activity Resolver Table:", "  ", packageName,
15664                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15665                    dumpState.setTitlePrinted(true);
15666                }
15667            }
15668            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15669                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15670                        : "Receiver Resolver Table:", "  ", packageName,
15671                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15672                    dumpState.setTitlePrinted(true);
15673                }
15674            }
15675            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15676                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15677                        : "Service Resolver Table:", "  ", packageName,
15678                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15679                    dumpState.setTitlePrinted(true);
15680                }
15681            }
15682            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15683                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15684                        : "Provider Resolver Table:", "  ", packageName,
15685                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15686                    dumpState.setTitlePrinted(true);
15687                }
15688            }
15689
15690            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15691                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15692                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15693                    int user = mSettings.mPreferredActivities.keyAt(i);
15694                    if (pir.dump(pw,
15695                            dumpState.getTitlePrinted()
15696                                ? "\nPreferred Activities User " + user + ":"
15697                                : "Preferred Activities User " + user + ":", "  ",
15698                            packageName, true, false)) {
15699                        dumpState.setTitlePrinted(true);
15700                    }
15701                }
15702            }
15703
15704            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15705                pw.flush();
15706                FileOutputStream fout = new FileOutputStream(fd);
15707                BufferedOutputStream str = new BufferedOutputStream(fout);
15708                XmlSerializer serializer = new FastXmlSerializer();
15709                try {
15710                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15711                    serializer.startDocument(null, true);
15712                    serializer.setFeature(
15713                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15714                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15715                    serializer.endDocument();
15716                    serializer.flush();
15717                } catch (IllegalArgumentException e) {
15718                    pw.println("Failed writing: " + e);
15719                } catch (IllegalStateException e) {
15720                    pw.println("Failed writing: " + e);
15721                } catch (IOException e) {
15722                    pw.println("Failed writing: " + e);
15723                }
15724            }
15725
15726            if (!checkin
15727                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15728                    && packageName == null) {
15729                pw.println();
15730                int count = mSettings.mPackages.size();
15731                if (count == 0) {
15732                    pw.println("No applications!");
15733                    pw.println();
15734                } else {
15735                    final String prefix = "  ";
15736                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15737                    if (allPackageSettings.size() == 0) {
15738                        pw.println("No domain preferred apps!");
15739                        pw.println();
15740                    } else {
15741                        pw.println("App verification status:");
15742                        pw.println();
15743                        count = 0;
15744                        for (PackageSetting ps : allPackageSettings) {
15745                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15746                            if (ivi == null || ivi.getPackageName() == null) continue;
15747                            pw.println(prefix + "Package: " + ivi.getPackageName());
15748                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15749                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15750                            pw.println();
15751                            count++;
15752                        }
15753                        if (count == 0) {
15754                            pw.println(prefix + "No app verification established.");
15755                            pw.println();
15756                        }
15757                        for (int userId : sUserManager.getUserIds()) {
15758                            pw.println("App linkages for user " + userId + ":");
15759                            pw.println();
15760                            count = 0;
15761                            for (PackageSetting ps : allPackageSettings) {
15762                                final long status = ps.getDomainVerificationStatusForUser(userId);
15763                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15764                                    continue;
15765                                }
15766                                pw.println(prefix + "Package: " + ps.name);
15767                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15768                                String statusStr = IntentFilterVerificationInfo.
15769                                        getStatusStringFromValue(status);
15770                                pw.println(prefix + "Status:  " + statusStr);
15771                                pw.println();
15772                                count++;
15773                            }
15774                            if (count == 0) {
15775                                pw.println(prefix + "No configured app linkages.");
15776                                pw.println();
15777                            }
15778                        }
15779                    }
15780                }
15781            }
15782
15783            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15784                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15785                if (packageName == null && permissionNames == null) {
15786                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15787                        if (iperm == 0) {
15788                            if (dumpState.onTitlePrinted())
15789                                pw.println();
15790                            pw.println("AppOp Permissions:");
15791                        }
15792                        pw.print("  AppOp Permission ");
15793                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15794                        pw.println(":");
15795                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15796                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15797                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15798                        }
15799                    }
15800                }
15801            }
15802
15803            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15804                boolean printedSomething = false;
15805                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15806                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15807                        continue;
15808                    }
15809                    if (!printedSomething) {
15810                        if (dumpState.onTitlePrinted())
15811                            pw.println();
15812                        pw.println("Registered ContentProviders:");
15813                        printedSomething = true;
15814                    }
15815                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15816                    pw.print("    "); pw.println(p.toString());
15817                }
15818                printedSomething = false;
15819                for (Map.Entry<String, PackageParser.Provider> entry :
15820                        mProvidersByAuthority.entrySet()) {
15821                    PackageParser.Provider p = entry.getValue();
15822                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15823                        continue;
15824                    }
15825                    if (!printedSomething) {
15826                        if (dumpState.onTitlePrinted())
15827                            pw.println();
15828                        pw.println("ContentProvider Authorities:");
15829                        printedSomething = true;
15830                    }
15831                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15832                    pw.print("    "); pw.println(p.toString());
15833                    if (p.info != null && p.info.applicationInfo != null) {
15834                        final String appInfo = p.info.applicationInfo.toString();
15835                        pw.print("      applicationInfo="); pw.println(appInfo);
15836                    }
15837                }
15838            }
15839
15840            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15841                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15842            }
15843
15844            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15845                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15846            }
15847
15848            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15849                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15850            }
15851
15852            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15853                // XXX should handle packageName != null by dumping only install data that
15854                // the given package is involved with.
15855                if (dumpState.onTitlePrinted()) pw.println();
15856                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15857            }
15858
15859            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15860                if (dumpState.onTitlePrinted()) pw.println();
15861                mSettings.dumpReadMessagesLPr(pw, dumpState);
15862
15863                pw.println();
15864                pw.println("Package warning messages:");
15865                BufferedReader in = null;
15866                String line = null;
15867                try {
15868                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15869                    while ((line = in.readLine()) != null) {
15870                        if (line.contains("ignored: updated version")) continue;
15871                        pw.println(line);
15872                    }
15873                } catch (IOException ignored) {
15874                } finally {
15875                    IoUtils.closeQuietly(in);
15876                }
15877            }
15878
15879            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15880                BufferedReader in = null;
15881                String line = null;
15882                try {
15883                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15884                    while ((line = in.readLine()) != null) {
15885                        if (line.contains("ignored: updated version")) continue;
15886                        pw.print("msg,");
15887                        pw.println(line);
15888                    }
15889                } catch (IOException ignored) {
15890                } finally {
15891                    IoUtils.closeQuietly(in);
15892                }
15893            }
15894        }
15895    }
15896
15897    private String dumpDomainString(String packageName) {
15898        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15899        List<IntentFilter> filters = getAllIntentFilters(packageName);
15900
15901        ArraySet<String> result = new ArraySet<>();
15902        if (iviList.size() > 0) {
15903            for (IntentFilterVerificationInfo ivi : iviList) {
15904                for (String host : ivi.getDomains()) {
15905                    result.add(host);
15906                }
15907            }
15908        }
15909        if (filters != null && filters.size() > 0) {
15910            for (IntentFilter filter : filters) {
15911                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15912                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15913                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15914                    result.addAll(filter.getHostsList());
15915                }
15916            }
15917        }
15918
15919        StringBuilder sb = new StringBuilder(result.size() * 16);
15920        for (String domain : result) {
15921            if (sb.length() > 0) sb.append(" ");
15922            sb.append(domain);
15923        }
15924        return sb.toString();
15925    }
15926
15927    // ------- apps on sdcard specific code -------
15928    static final boolean DEBUG_SD_INSTALL = false;
15929
15930    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15931
15932    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15933
15934    private boolean mMediaMounted = false;
15935
15936    static String getEncryptKey() {
15937        try {
15938            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15939                    SD_ENCRYPTION_KEYSTORE_NAME);
15940            if (sdEncKey == null) {
15941                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15942                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15943                if (sdEncKey == null) {
15944                    Slog.e(TAG, "Failed to create encryption keys");
15945                    return null;
15946                }
15947            }
15948            return sdEncKey;
15949        } catch (NoSuchAlgorithmException nsae) {
15950            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15951            return null;
15952        } catch (IOException ioe) {
15953            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15954            return null;
15955        }
15956    }
15957
15958    /*
15959     * Update media status on PackageManager.
15960     */
15961    @Override
15962    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15963        int callingUid = Binder.getCallingUid();
15964        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15965            throw new SecurityException("Media status can only be updated by the system");
15966        }
15967        // reader; this apparently protects mMediaMounted, but should probably
15968        // be a different lock in that case.
15969        synchronized (mPackages) {
15970            Log.i(TAG, "Updating external media status from "
15971                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15972                    + (mediaStatus ? "mounted" : "unmounted"));
15973            if (DEBUG_SD_INSTALL)
15974                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15975                        + ", mMediaMounted=" + mMediaMounted);
15976            if (mediaStatus == mMediaMounted) {
15977                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15978                        : 0, -1);
15979                mHandler.sendMessage(msg);
15980                return;
15981            }
15982            mMediaMounted = mediaStatus;
15983        }
15984        // Queue up an async operation since the package installation may take a
15985        // little while.
15986        mHandler.post(new Runnable() {
15987            public void run() {
15988                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15989            }
15990        });
15991    }
15992
15993    /**
15994     * Called by MountService when the initial ASECs to scan are available.
15995     * Should block until all the ASEC containers are finished being scanned.
15996     */
15997    public void scanAvailableAsecs() {
15998        updateExternalMediaStatusInner(true, false, false);
15999        if (mShouldRestoreconData) {
16000            SELinuxMMAC.setRestoreconDone();
16001            mShouldRestoreconData = false;
16002        }
16003    }
16004
16005    /*
16006     * Collect information of applications on external media, map them against
16007     * existing containers and update information based on current mount status.
16008     * Please note that we always have to report status if reportStatus has been
16009     * set to true especially when unloading packages.
16010     */
16011    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16012            boolean externalStorage) {
16013        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16014        int[] uidArr = EmptyArray.INT;
16015
16016        final String[] list = PackageHelper.getSecureContainerList();
16017        if (ArrayUtils.isEmpty(list)) {
16018            Log.i(TAG, "No secure containers found");
16019        } else {
16020            // Process list of secure containers and categorize them
16021            // as active or stale based on their package internal state.
16022
16023            // reader
16024            synchronized (mPackages) {
16025                for (String cid : list) {
16026                    // Leave stages untouched for now; installer service owns them
16027                    if (PackageInstallerService.isStageName(cid)) continue;
16028
16029                    if (DEBUG_SD_INSTALL)
16030                        Log.i(TAG, "Processing container " + cid);
16031                    String pkgName = getAsecPackageName(cid);
16032                    if (pkgName == null) {
16033                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16034                        continue;
16035                    }
16036                    if (DEBUG_SD_INSTALL)
16037                        Log.i(TAG, "Looking for pkg : " + pkgName);
16038
16039                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16040                    if (ps == null) {
16041                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16042                        continue;
16043                    }
16044
16045                    /*
16046                     * Skip packages that are not external if we're unmounting
16047                     * external storage.
16048                     */
16049                    if (externalStorage && !isMounted && !isExternal(ps)) {
16050                        continue;
16051                    }
16052
16053                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16054                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16055                    // The package status is changed only if the code path
16056                    // matches between settings and the container id.
16057                    if (ps.codePathString != null
16058                            && ps.codePathString.startsWith(args.getCodePath())) {
16059                        if (DEBUG_SD_INSTALL) {
16060                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16061                                    + " at code path: " + ps.codePathString);
16062                        }
16063
16064                        // We do have a valid package installed on sdcard
16065                        processCids.put(args, ps.codePathString);
16066                        final int uid = ps.appId;
16067                        if (uid != -1) {
16068                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16069                        }
16070                    } else {
16071                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16072                                + ps.codePathString);
16073                    }
16074                }
16075            }
16076
16077            Arrays.sort(uidArr);
16078        }
16079
16080        // Process packages with valid entries.
16081        if (isMounted) {
16082            if (DEBUG_SD_INSTALL)
16083                Log.i(TAG, "Loading packages");
16084            loadMediaPackages(processCids, uidArr, externalStorage);
16085            startCleaningPackages();
16086            mInstallerService.onSecureContainersAvailable();
16087        } else {
16088            if (DEBUG_SD_INSTALL)
16089                Log.i(TAG, "Unloading packages");
16090            unloadMediaPackages(processCids, uidArr, reportStatus);
16091        }
16092    }
16093
16094    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16095            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16096        final int size = infos.size();
16097        final String[] packageNames = new String[size];
16098        final int[] packageUids = new int[size];
16099        for (int i = 0; i < size; i++) {
16100            final ApplicationInfo info = infos.get(i);
16101            packageNames[i] = info.packageName;
16102            packageUids[i] = info.uid;
16103        }
16104        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16105                finishedReceiver);
16106    }
16107
16108    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16109            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16110        sendResourcesChangedBroadcast(mediaStatus, replacing,
16111                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16112    }
16113
16114    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16115            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16116        int size = pkgList.length;
16117        if (size > 0) {
16118            // Send broadcasts here
16119            Bundle extras = new Bundle();
16120            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16121            if (uidArr != null) {
16122                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16123            }
16124            if (replacing) {
16125                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16126            }
16127            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16128                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16129            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16130        }
16131    }
16132
16133   /*
16134     * Look at potentially valid container ids from processCids If package
16135     * information doesn't match the one on record or package scanning fails,
16136     * the cid is added to list of removeCids. We currently don't delete stale
16137     * containers.
16138     */
16139    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16140            boolean externalStorage) {
16141        ArrayList<String> pkgList = new ArrayList<String>();
16142        Set<AsecInstallArgs> keys = processCids.keySet();
16143
16144        for (AsecInstallArgs args : keys) {
16145            String codePath = processCids.get(args);
16146            if (DEBUG_SD_INSTALL)
16147                Log.i(TAG, "Loading container : " + args.cid);
16148            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16149            try {
16150                // Make sure there are no container errors first.
16151                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16152                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16153                            + " when installing from sdcard");
16154                    continue;
16155                }
16156                // Check code path here.
16157                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16158                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16159                            + " does not match one in settings " + codePath);
16160                    continue;
16161                }
16162                // Parse package
16163                int parseFlags = mDefParseFlags;
16164                if (args.isExternalAsec()) {
16165                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16166                }
16167                if (args.isFwdLocked()) {
16168                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16169                }
16170
16171                synchronized (mInstallLock) {
16172                    PackageParser.Package pkg = null;
16173                    try {
16174                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16175                    } catch (PackageManagerException e) {
16176                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16177                    }
16178                    // Scan the package
16179                    if (pkg != null) {
16180                        /*
16181                         * TODO why is the lock being held? doPostInstall is
16182                         * called in other places without the lock. This needs
16183                         * to be straightened out.
16184                         */
16185                        // writer
16186                        synchronized (mPackages) {
16187                            retCode = PackageManager.INSTALL_SUCCEEDED;
16188                            pkgList.add(pkg.packageName);
16189                            // Post process args
16190                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16191                                    pkg.applicationInfo.uid);
16192                        }
16193                    } else {
16194                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16195                    }
16196                }
16197
16198            } finally {
16199                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16200                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16201                }
16202            }
16203        }
16204        // writer
16205        synchronized (mPackages) {
16206            // If the platform SDK has changed since the last time we booted,
16207            // we need to re-grant app permission to catch any new ones that
16208            // appear. This is really a hack, and means that apps can in some
16209            // cases get permissions that the user didn't initially explicitly
16210            // allow... it would be nice to have some better way to handle
16211            // this situation.
16212            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16213                    : mSettings.getInternalVersion();
16214            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16215                    : StorageManager.UUID_PRIVATE_INTERNAL;
16216
16217            int updateFlags = UPDATE_PERMISSIONS_ALL;
16218            if (ver.sdkVersion != mSdkVersion) {
16219                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16220                        + mSdkVersion + "; regranting permissions for external");
16221                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16222            }
16223            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16224
16225            // Yay, everything is now upgraded
16226            ver.forceCurrent();
16227
16228            // can downgrade to reader
16229            // Persist settings
16230            mSettings.writeLPr();
16231        }
16232        // Send a broadcast to let everyone know we are done processing
16233        if (pkgList.size() > 0) {
16234            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16235        }
16236    }
16237
16238   /*
16239     * Utility method to unload a list of specified containers
16240     */
16241    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16242        // Just unmount all valid containers.
16243        for (AsecInstallArgs arg : cidArgs) {
16244            synchronized (mInstallLock) {
16245                arg.doPostDeleteLI(false);
16246           }
16247       }
16248   }
16249
16250    /*
16251     * Unload packages mounted on external media. This involves deleting package
16252     * data from internal structures, sending broadcasts about diabled packages,
16253     * gc'ing to free up references, unmounting all secure containers
16254     * corresponding to packages on external media, and posting a
16255     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16256     * that we always have to post this message if status has been requested no
16257     * matter what.
16258     */
16259    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16260            final boolean reportStatus) {
16261        if (DEBUG_SD_INSTALL)
16262            Log.i(TAG, "unloading media packages");
16263        ArrayList<String> pkgList = new ArrayList<String>();
16264        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16265        final Set<AsecInstallArgs> keys = processCids.keySet();
16266        for (AsecInstallArgs args : keys) {
16267            String pkgName = args.getPackageName();
16268            if (DEBUG_SD_INSTALL)
16269                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16270            // Delete package internally
16271            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16272            synchronized (mInstallLock) {
16273                boolean res = deletePackageLI(pkgName, null, false, null, null,
16274                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16275                if (res) {
16276                    pkgList.add(pkgName);
16277                } else {
16278                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16279                    failedList.add(args);
16280                }
16281            }
16282        }
16283
16284        // reader
16285        synchronized (mPackages) {
16286            // We didn't update the settings after removing each package;
16287            // write them now for all packages.
16288            mSettings.writeLPr();
16289        }
16290
16291        // We have to absolutely send UPDATED_MEDIA_STATUS only
16292        // after confirming that all the receivers processed the ordered
16293        // broadcast when packages get disabled, force a gc to clean things up.
16294        // and unload all the containers.
16295        if (pkgList.size() > 0) {
16296            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16297                    new IIntentReceiver.Stub() {
16298                public void performReceive(Intent intent, int resultCode, String data,
16299                        Bundle extras, boolean ordered, boolean sticky,
16300                        int sendingUser) throws RemoteException {
16301                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16302                            reportStatus ? 1 : 0, 1, keys);
16303                    mHandler.sendMessage(msg);
16304                }
16305            });
16306        } else {
16307            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16308                    keys);
16309            mHandler.sendMessage(msg);
16310        }
16311    }
16312
16313    private void loadPrivatePackages(final VolumeInfo vol) {
16314        mHandler.post(new Runnable() {
16315            @Override
16316            public void run() {
16317                loadPrivatePackagesInner(vol);
16318            }
16319        });
16320    }
16321
16322    private void loadPrivatePackagesInner(VolumeInfo vol) {
16323        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16324        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16325
16326        final VersionInfo ver;
16327        final List<PackageSetting> packages;
16328        synchronized (mPackages) {
16329            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16330            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16331        }
16332
16333        for (PackageSetting ps : packages) {
16334            synchronized (mInstallLock) {
16335                final PackageParser.Package pkg;
16336                try {
16337                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16338                    loaded.add(pkg.applicationInfo);
16339                } catch (PackageManagerException e) {
16340                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16341                }
16342
16343                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16344                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16345                }
16346            }
16347        }
16348
16349        synchronized (mPackages) {
16350            int updateFlags = UPDATE_PERMISSIONS_ALL;
16351            if (ver.sdkVersion != mSdkVersion) {
16352                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16353                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16354                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16355            }
16356            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16357
16358            // Yay, everything is now upgraded
16359            ver.forceCurrent();
16360
16361            mSettings.writeLPr();
16362        }
16363
16364        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16365        sendResourcesChangedBroadcast(true, false, loaded, null);
16366    }
16367
16368    private void unloadPrivatePackages(final VolumeInfo vol) {
16369        mHandler.post(new Runnable() {
16370            @Override
16371            public void run() {
16372                unloadPrivatePackagesInner(vol);
16373            }
16374        });
16375    }
16376
16377    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16378        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16379        synchronized (mInstallLock) {
16380        synchronized (mPackages) {
16381            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16382            for (PackageSetting ps : packages) {
16383                if (ps.pkg == null) continue;
16384
16385                final ApplicationInfo info = ps.pkg.applicationInfo;
16386                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16387                if (deletePackageLI(ps.name, null, false, null, null,
16388                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16389                    unloaded.add(info);
16390                } else {
16391                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16392                }
16393            }
16394
16395            mSettings.writeLPr();
16396        }
16397        }
16398
16399        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16400        sendResourcesChangedBroadcast(false, false, unloaded, null);
16401    }
16402
16403    /**
16404     * Examine all users present on given mounted volume, and destroy data
16405     * belonging to users that are no longer valid, or whose user ID has been
16406     * recycled.
16407     */
16408    private void reconcileUsers(String volumeUuid) {
16409        final File[] files = FileUtils
16410                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16411        for (File file : files) {
16412            if (!file.isDirectory()) continue;
16413
16414            final int userId;
16415            final UserInfo info;
16416            try {
16417                userId = Integer.parseInt(file.getName());
16418                info = sUserManager.getUserInfo(userId);
16419            } catch (NumberFormatException e) {
16420                Slog.w(TAG, "Invalid user directory " + file);
16421                continue;
16422            }
16423
16424            boolean destroyUser = false;
16425            if (info == null) {
16426                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16427                        + " because no matching user was found");
16428                destroyUser = true;
16429            } else {
16430                try {
16431                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16432                } catch (IOException e) {
16433                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16434                            + " because we failed to enforce serial number: " + e);
16435                    destroyUser = true;
16436                }
16437            }
16438
16439            if (destroyUser) {
16440                synchronized (mInstallLock) {
16441                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16442                }
16443            }
16444        }
16445
16446        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16447        final UserManager um = mContext.getSystemService(UserManager.class);
16448        for (UserInfo user : um.getUsers()) {
16449            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16450            if (userDir.exists()) continue;
16451
16452            try {
16453                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16454                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16455            } catch (IOException e) {
16456                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16457            }
16458        }
16459    }
16460
16461    /**
16462     * Examine all apps present on given mounted volume, and destroy apps that
16463     * aren't expected, either due to uninstallation or reinstallation on
16464     * another volume.
16465     */
16466    private void reconcileApps(String volumeUuid) {
16467        final File[] files = FileUtils
16468                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16469        for (File file : files) {
16470            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16471                    && !PackageInstallerService.isStageName(file.getName());
16472            if (!isPackage) {
16473                // Ignore entries which are not packages
16474                continue;
16475            }
16476
16477            boolean destroyApp = false;
16478            String packageName = null;
16479            try {
16480                final PackageLite pkg = PackageParser.parsePackageLite(file,
16481                        PackageParser.PARSE_MUST_BE_APK);
16482                packageName = pkg.packageName;
16483
16484                synchronized (mPackages) {
16485                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16486                    if (ps == null) {
16487                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16488                                + volumeUuid + " because we found no install record");
16489                        destroyApp = true;
16490                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16491                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16492                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16493                        destroyApp = true;
16494                    }
16495                }
16496
16497            } catch (PackageParserException e) {
16498                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16499                destroyApp = true;
16500            }
16501
16502            if (destroyApp) {
16503                synchronized (mInstallLock) {
16504                    if (packageName != null) {
16505                        removeDataDirsLI(volumeUuid, packageName);
16506                    }
16507                    if (file.isDirectory()) {
16508                        mInstaller.rmPackageDir(file.getAbsolutePath());
16509                    } else {
16510                        file.delete();
16511                    }
16512                }
16513            }
16514        }
16515    }
16516
16517    private void unfreezePackage(String packageName) {
16518        synchronized (mPackages) {
16519            final PackageSetting ps = mSettings.mPackages.get(packageName);
16520            if (ps != null) {
16521                ps.frozen = false;
16522            }
16523        }
16524    }
16525
16526    @Override
16527    public int movePackage(final String packageName, final String volumeUuid) {
16528        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16529
16530        final int moveId = mNextMoveId.getAndIncrement();
16531        mHandler.post(new Runnable() {
16532            @Override
16533            public void run() {
16534                try {
16535                    movePackageInternal(packageName, volumeUuid, moveId);
16536                } catch (PackageManagerException e) {
16537                    Slog.w(TAG, "Failed to move " + packageName, e);
16538                    mMoveCallbacks.notifyStatusChanged(moveId,
16539                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16540                }
16541            }
16542        });
16543        return moveId;
16544    }
16545
16546    private void movePackageInternal(final String packageName, final String volumeUuid,
16547            final int moveId) throws PackageManagerException {
16548        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16549        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16550        final PackageManager pm = mContext.getPackageManager();
16551
16552        final boolean currentAsec;
16553        final String currentVolumeUuid;
16554        final File codeFile;
16555        final String installerPackageName;
16556        final String packageAbiOverride;
16557        final int appId;
16558        final String seinfo;
16559        final String label;
16560
16561        // reader
16562        synchronized (mPackages) {
16563            final PackageParser.Package pkg = mPackages.get(packageName);
16564            final PackageSetting ps = mSettings.mPackages.get(packageName);
16565            if (pkg == null || ps == null) {
16566                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16567            }
16568
16569            if (pkg.applicationInfo.isSystemApp()) {
16570                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16571                        "Cannot move system application");
16572            }
16573
16574            if (pkg.applicationInfo.isExternalAsec()) {
16575                currentAsec = true;
16576                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16577            } else if (pkg.applicationInfo.isForwardLocked()) {
16578                currentAsec = true;
16579                currentVolumeUuid = "forward_locked";
16580            } else {
16581                currentAsec = false;
16582                currentVolumeUuid = ps.volumeUuid;
16583
16584                final File probe = new File(pkg.codePath);
16585                final File probeOat = new File(probe, "oat");
16586                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16587                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16588                            "Move only supported for modern cluster style installs");
16589                }
16590            }
16591
16592            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16593                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16594                        "Package already moved to " + volumeUuid);
16595            }
16596
16597            if (ps.frozen) {
16598                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16599                        "Failed to move already frozen package");
16600            }
16601            ps.frozen = true;
16602
16603            codeFile = new File(pkg.codePath);
16604            installerPackageName = ps.installerPackageName;
16605            packageAbiOverride = ps.cpuAbiOverrideString;
16606            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16607            seinfo = pkg.applicationInfo.seinfo;
16608            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16609        }
16610
16611        // Now that we're guarded by frozen state, kill app during move
16612        final long token = Binder.clearCallingIdentity();
16613        try {
16614            killApplication(packageName, appId, "move pkg");
16615        } finally {
16616            Binder.restoreCallingIdentity(token);
16617        }
16618
16619        final Bundle extras = new Bundle();
16620        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16621        extras.putString(Intent.EXTRA_TITLE, label);
16622        mMoveCallbacks.notifyCreated(moveId, extras);
16623
16624        int installFlags;
16625        final boolean moveCompleteApp;
16626        final File measurePath;
16627
16628        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16629            installFlags = INSTALL_INTERNAL;
16630            moveCompleteApp = !currentAsec;
16631            measurePath = Environment.getDataAppDirectory(volumeUuid);
16632        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16633            installFlags = INSTALL_EXTERNAL;
16634            moveCompleteApp = false;
16635            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16636        } else {
16637            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16638            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16639                    || !volume.isMountedWritable()) {
16640                unfreezePackage(packageName);
16641                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16642                        "Move location not mounted private volume");
16643            }
16644
16645            Preconditions.checkState(!currentAsec);
16646
16647            installFlags = INSTALL_INTERNAL;
16648            moveCompleteApp = true;
16649            measurePath = Environment.getDataAppDirectory(volumeUuid);
16650        }
16651
16652        final PackageStats stats = new PackageStats(null, -1);
16653        synchronized (mInstaller) {
16654            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16655                unfreezePackage(packageName);
16656                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16657                        "Failed to measure package size");
16658            }
16659        }
16660
16661        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16662                + stats.dataSize);
16663
16664        final long startFreeBytes = measurePath.getFreeSpace();
16665        final long sizeBytes;
16666        if (moveCompleteApp) {
16667            sizeBytes = stats.codeSize + stats.dataSize;
16668        } else {
16669            sizeBytes = stats.codeSize;
16670        }
16671
16672        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16673            unfreezePackage(packageName);
16674            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16675                    "Not enough free space to move");
16676        }
16677
16678        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16679
16680        final CountDownLatch installedLatch = new CountDownLatch(1);
16681        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16682            @Override
16683            public void onUserActionRequired(Intent intent) throws RemoteException {
16684                throw new IllegalStateException();
16685            }
16686
16687            @Override
16688            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16689                    Bundle extras) throws RemoteException {
16690                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16691                        + PackageManager.installStatusToString(returnCode, msg));
16692
16693                installedLatch.countDown();
16694
16695                // Regardless of success or failure of the move operation,
16696                // always unfreeze the package
16697                unfreezePackage(packageName);
16698
16699                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16700                switch (status) {
16701                    case PackageInstaller.STATUS_SUCCESS:
16702                        mMoveCallbacks.notifyStatusChanged(moveId,
16703                                PackageManager.MOVE_SUCCEEDED);
16704                        break;
16705                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16706                        mMoveCallbacks.notifyStatusChanged(moveId,
16707                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16708                        break;
16709                    default:
16710                        mMoveCallbacks.notifyStatusChanged(moveId,
16711                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16712                        break;
16713                }
16714            }
16715        };
16716
16717        final MoveInfo move;
16718        if (moveCompleteApp) {
16719            // Kick off a thread to report progress estimates
16720            new Thread() {
16721                @Override
16722                public void run() {
16723                    while (true) {
16724                        try {
16725                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16726                                break;
16727                            }
16728                        } catch (InterruptedException ignored) {
16729                        }
16730
16731                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16732                        final int progress = 10 + (int) MathUtils.constrain(
16733                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16734                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16735                    }
16736                }
16737            }.start();
16738
16739            final String dataAppName = codeFile.getName();
16740            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16741                    dataAppName, appId, seinfo);
16742        } else {
16743            move = null;
16744        }
16745
16746        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16747
16748        final Message msg = mHandler.obtainMessage(INIT_COPY);
16749        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16750        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16751                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16752        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16753        msg.obj = params;
16754
16755        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16756                System.identityHashCode(msg.obj));
16757        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16758                System.identityHashCode(msg.obj));
16759
16760        mHandler.sendMessage(msg);
16761    }
16762
16763    @Override
16764    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16765        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16766
16767        final int realMoveId = mNextMoveId.getAndIncrement();
16768        final Bundle extras = new Bundle();
16769        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16770        mMoveCallbacks.notifyCreated(realMoveId, extras);
16771
16772        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16773            @Override
16774            public void onCreated(int moveId, Bundle extras) {
16775                // Ignored
16776            }
16777
16778            @Override
16779            public void onStatusChanged(int moveId, int status, long estMillis) {
16780                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16781            }
16782        };
16783
16784        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16785        storage.setPrimaryStorageUuid(volumeUuid, callback);
16786        return realMoveId;
16787    }
16788
16789    @Override
16790    public int getMoveStatus(int moveId) {
16791        mContext.enforceCallingOrSelfPermission(
16792                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16793        return mMoveCallbacks.mLastStatus.get(moveId);
16794    }
16795
16796    @Override
16797    public void registerMoveCallback(IPackageMoveObserver callback) {
16798        mContext.enforceCallingOrSelfPermission(
16799                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16800        mMoveCallbacks.register(callback);
16801    }
16802
16803    @Override
16804    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16805        mContext.enforceCallingOrSelfPermission(
16806                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16807        mMoveCallbacks.unregister(callback);
16808    }
16809
16810    @Override
16811    public boolean setInstallLocation(int loc) {
16812        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16813                null);
16814        if (getInstallLocation() == loc) {
16815            return true;
16816        }
16817        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16818                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16819            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16820                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16821            return true;
16822        }
16823        return false;
16824   }
16825
16826    @Override
16827    public int getInstallLocation() {
16828        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16829                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16830                PackageHelper.APP_INSTALL_AUTO);
16831    }
16832
16833    /** Called by UserManagerService */
16834    void cleanUpUser(UserManagerService userManager, int userHandle) {
16835        synchronized (mPackages) {
16836            mDirtyUsers.remove(userHandle);
16837            mUserNeedsBadging.delete(userHandle);
16838            mSettings.removeUserLPw(userHandle);
16839            mPendingBroadcasts.remove(userHandle);
16840        }
16841        synchronized (mInstallLock) {
16842            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16843            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16844                final String volumeUuid = vol.getFsUuid();
16845                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16846                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16847            }
16848            synchronized (mPackages) {
16849                removeUnusedPackagesLILPw(userManager, userHandle);
16850            }
16851        }
16852    }
16853
16854    /**
16855     * We're removing userHandle and would like to remove any downloaded packages
16856     * that are no longer in use by any other user.
16857     * @param userHandle the user being removed
16858     */
16859    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16860        final boolean DEBUG_CLEAN_APKS = false;
16861        int [] users = userManager.getUserIds();
16862        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16863        while (psit.hasNext()) {
16864            PackageSetting ps = psit.next();
16865            if (ps.pkg == null) {
16866                continue;
16867            }
16868            final String packageName = ps.pkg.packageName;
16869            // Skip over if system app
16870            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16871                continue;
16872            }
16873            if (DEBUG_CLEAN_APKS) {
16874                Slog.i(TAG, "Checking package " + packageName);
16875            }
16876            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16877            if (keep) {
16878                if (DEBUG_CLEAN_APKS) {
16879                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16880                }
16881            } else {
16882                for (int i = 0; i < users.length; i++) {
16883                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16884                        keep = true;
16885                        if (DEBUG_CLEAN_APKS) {
16886                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
16887                                    + users[i]);
16888                        }
16889                        break;
16890                    }
16891                }
16892            }
16893            if (!keep) {
16894                if (DEBUG_CLEAN_APKS) {
16895                    Slog.i(TAG, "  Removing package " + packageName);
16896                }
16897                mHandler.post(new Runnable() {
16898                    public void run() {
16899                        deletePackageX(packageName, userHandle, 0);
16900                    } //end run
16901                });
16902            }
16903        }
16904    }
16905
16906    /** Called by UserManagerService */
16907    void createNewUser(int userHandle) {
16908        synchronized (mInstallLock) {
16909            mInstaller.createUserConfig(userHandle);
16910            mSettings.createNewUserLI(this, mInstaller, userHandle);
16911        }
16912        synchronized (mPackages) {
16913            applyFactoryDefaultBrowserLPw(userHandle);
16914            primeDomainVerificationsLPw(userHandle);
16915        }
16916    }
16917
16918    void newUserCreated(final int userHandle) {
16919        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16920        // If permission review for legacy apps is required, we represent
16921        // dagerous permissions for such apps as always granted runtime
16922        // permissions to keep per user flag state whether review is needed.
16923        // Hence, if a new user is added we have to propagate dangerous
16924        // permission grants for these legacy apps.
16925        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
16926            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
16927                    | UPDATE_PERMISSIONS_REPLACE_ALL);
16928        }
16929    }
16930
16931    @Override
16932    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16933        mContext.enforceCallingOrSelfPermission(
16934                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16935                "Only package verification agents can read the verifier device identity");
16936
16937        synchronized (mPackages) {
16938            return mSettings.getVerifierDeviceIdentityLPw();
16939        }
16940    }
16941
16942    @Override
16943    public void setPermissionEnforced(String permission, boolean enforced) {
16944        // TODO: Now that we no longer change GID for storage, this should to away.
16945        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16946                "setPermissionEnforced");
16947        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16948            synchronized (mPackages) {
16949                if (mSettings.mReadExternalStorageEnforced == null
16950                        || mSettings.mReadExternalStorageEnforced != enforced) {
16951                    mSettings.mReadExternalStorageEnforced = enforced;
16952                    mSettings.writeLPr();
16953                }
16954            }
16955            // kill any non-foreground processes so we restart them and
16956            // grant/revoke the GID.
16957            final IActivityManager am = ActivityManagerNative.getDefault();
16958            if (am != null) {
16959                final long token = Binder.clearCallingIdentity();
16960                try {
16961                    am.killProcessesBelowForeground("setPermissionEnforcement");
16962                } catch (RemoteException e) {
16963                } finally {
16964                    Binder.restoreCallingIdentity(token);
16965                }
16966            }
16967        } else {
16968            throw new IllegalArgumentException("No selective enforcement for " + permission);
16969        }
16970    }
16971
16972    @Override
16973    @Deprecated
16974    public boolean isPermissionEnforced(String permission) {
16975        return true;
16976    }
16977
16978    @Override
16979    public boolean isStorageLow() {
16980        final long token = Binder.clearCallingIdentity();
16981        try {
16982            final DeviceStorageMonitorInternal
16983                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16984            if (dsm != null) {
16985                return dsm.isMemoryLow();
16986            } else {
16987                return false;
16988            }
16989        } finally {
16990            Binder.restoreCallingIdentity(token);
16991        }
16992    }
16993
16994    @Override
16995    public IPackageInstaller getPackageInstaller() {
16996        return mInstallerService;
16997    }
16998
16999    private boolean userNeedsBadging(int userId) {
17000        int index = mUserNeedsBadging.indexOfKey(userId);
17001        if (index < 0) {
17002            final UserInfo userInfo;
17003            final long token = Binder.clearCallingIdentity();
17004            try {
17005                userInfo = sUserManager.getUserInfo(userId);
17006            } finally {
17007                Binder.restoreCallingIdentity(token);
17008            }
17009            final boolean b;
17010            if (userInfo != null && userInfo.isManagedProfile()) {
17011                b = true;
17012            } else {
17013                b = false;
17014            }
17015            mUserNeedsBadging.put(userId, b);
17016            return b;
17017        }
17018        return mUserNeedsBadging.valueAt(index);
17019    }
17020
17021    @Override
17022    public KeySet getKeySetByAlias(String packageName, String alias) {
17023        if (packageName == null || alias == null) {
17024            return null;
17025        }
17026        synchronized(mPackages) {
17027            final PackageParser.Package pkg = mPackages.get(packageName);
17028            if (pkg == null) {
17029                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17030                throw new IllegalArgumentException("Unknown package: " + packageName);
17031            }
17032            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17033            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17034        }
17035    }
17036
17037    @Override
17038    public KeySet getSigningKeySet(String packageName) {
17039        if (packageName == null) {
17040            return null;
17041        }
17042        synchronized(mPackages) {
17043            final PackageParser.Package pkg = mPackages.get(packageName);
17044            if (pkg == null) {
17045                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17046                throw new IllegalArgumentException("Unknown package: " + packageName);
17047            }
17048            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17049                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17050                throw new SecurityException("May not access signing KeySet of other apps.");
17051            }
17052            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17053            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17054        }
17055    }
17056
17057    @Override
17058    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17059        if (packageName == null || ks == null) {
17060            return false;
17061        }
17062        synchronized(mPackages) {
17063            final PackageParser.Package pkg = mPackages.get(packageName);
17064            if (pkg == null) {
17065                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17066                throw new IllegalArgumentException("Unknown package: " + packageName);
17067            }
17068            IBinder ksh = ks.getToken();
17069            if (ksh instanceof KeySetHandle) {
17070                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17071                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17072            }
17073            return false;
17074        }
17075    }
17076
17077    @Override
17078    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17079        if (packageName == null || ks == null) {
17080            return false;
17081        }
17082        synchronized(mPackages) {
17083            final PackageParser.Package pkg = mPackages.get(packageName);
17084            if (pkg == null) {
17085                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17086                throw new IllegalArgumentException("Unknown package: " + packageName);
17087            }
17088            IBinder ksh = ks.getToken();
17089            if (ksh instanceof KeySetHandle) {
17090                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17091                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17092            }
17093            return false;
17094        }
17095    }
17096
17097    private void deletePackageIfUnusedLPr(final String packageName) {
17098        PackageSetting ps = mSettings.mPackages.get(packageName);
17099        if (ps == null) {
17100            return;
17101        }
17102        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17103            // TODO Implement atomic delete if package is unused
17104            // It is currently possible that the package will be deleted even if it is installed
17105            // after this method returns.
17106            mHandler.post(new Runnable() {
17107                public void run() {
17108                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17109                }
17110            });
17111        }
17112    }
17113
17114    /**
17115     * Check and throw if the given before/after packages would be considered a
17116     * downgrade.
17117     */
17118    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17119            throws PackageManagerException {
17120        if (after.versionCode < before.mVersionCode) {
17121            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17122                    "Update version code " + after.versionCode + " is older than current "
17123                    + before.mVersionCode);
17124        } else if (after.versionCode == before.mVersionCode) {
17125            if (after.baseRevisionCode < before.baseRevisionCode) {
17126                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17127                        "Update base revision code " + after.baseRevisionCode
17128                        + " is older than current " + before.baseRevisionCode);
17129            }
17130
17131            if (!ArrayUtils.isEmpty(after.splitNames)) {
17132                for (int i = 0; i < after.splitNames.length; i++) {
17133                    final String splitName = after.splitNames[i];
17134                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17135                    if (j != -1) {
17136                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17137                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17138                                    "Update split " + splitName + " revision code "
17139                                    + after.splitRevisionCodes[i] + " is older than current "
17140                                    + before.splitRevisionCodes[j]);
17141                        }
17142                    }
17143                }
17144            }
17145        }
17146    }
17147
17148    private static class MoveCallbacks extends Handler {
17149        private static final int MSG_CREATED = 1;
17150        private static final int MSG_STATUS_CHANGED = 2;
17151
17152        private final RemoteCallbackList<IPackageMoveObserver>
17153                mCallbacks = new RemoteCallbackList<>();
17154
17155        private final SparseIntArray mLastStatus = new SparseIntArray();
17156
17157        public MoveCallbacks(Looper looper) {
17158            super(looper);
17159        }
17160
17161        public void register(IPackageMoveObserver callback) {
17162            mCallbacks.register(callback);
17163        }
17164
17165        public void unregister(IPackageMoveObserver callback) {
17166            mCallbacks.unregister(callback);
17167        }
17168
17169        @Override
17170        public void handleMessage(Message msg) {
17171            final SomeArgs args = (SomeArgs) msg.obj;
17172            final int n = mCallbacks.beginBroadcast();
17173            for (int i = 0; i < n; i++) {
17174                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17175                try {
17176                    invokeCallback(callback, msg.what, args);
17177                } catch (RemoteException ignored) {
17178                }
17179            }
17180            mCallbacks.finishBroadcast();
17181            args.recycle();
17182        }
17183
17184        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17185                throws RemoteException {
17186            switch (what) {
17187                case MSG_CREATED: {
17188                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17189                    break;
17190                }
17191                case MSG_STATUS_CHANGED: {
17192                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17193                    break;
17194                }
17195            }
17196        }
17197
17198        private void notifyCreated(int moveId, Bundle extras) {
17199            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17200
17201            final SomeArgs args = SomeArgs.obtain();
17202            args.argi1 = moveId;
17203            args.arg2 = extras;
17204            obtainMessage(MSG_CREATED, args).sendToTarget();
17205        }
17206
17207        private void notifyStatusChanged(int moveId, int status) {
17208            notifyStatusChanged(moveId, status, -1);
17209        }
17210
17211        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17212            Slog.v(TAG, "Move " + moveId + " status " + status);
17213
17214            final SomeArgs args = SomeArgs.obtain();
17215            args.argi1 = moveId;
17216            args.argi2 = status;
17217            args.arg3 = estMillis;
17218            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17219
17220            synchronized (mLastStatus) {
17221                mLastStatus.put(moveId, status);
17222            }
17223        }
17224    }
17225
17226    private final class OnPermissionChangeListeners extends Handler {
17227        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17228
17229        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17230                new RemoteCallbackList<>();
17231
17232        public OnPermissionChangeListeners(Looper looper) {
17233            super(looper);
17234        }
17235
17236        @Override
17237        public void handleMessage(Message msg) {
17238            switch (msg.what) {
17239                case MSG_ON_PERMISSIONS_CHANGED: {
17240                    final int uid = msg.arg1;
17241                    handleOnPermissionsChanged(uid);
17242                } break;
17243            }
17244        }
17245
17246        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17247            mPermissionListeners.register(listener);
17248
17249        }
17250
17251        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17252            mPermissionListeners.unregister(listener);
17253        }
17254
17255        public void onPermissionsChanged(int uid) {
17256            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17257                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17258            }
17259        }
17260
17261        private void handleOnPermissionsChanged(int uid) {
17262            final int count = mPermissionListeners.beginBroadcast();
17263            try {
17264                for (int i = 0; i < count; i++) {
17265                    IOnPermissionsChangeListener callback = mPermissionListeners
17266                            .getBroadcastItem(i);
17267                    try {
17268                        callback.onPermissionsChanged(uid);
17269                    } catch (RemoteException e) {
17270                        Log.e(TAG, "Permission listener is dead", e);
17271                    }
17272                }
17273            } finally {
17274                mPermissionListeners.finishBroadcast();
17275            }
17276        }
17277    }
17278
17279    private class PackageManagerInternalImpl extends PackageManagerInternal {
17280        @Override
17281        public void setLocationPackagesProvider(PackagesProvider provider) {
17282            synchronized (mPackages) {
17283                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17284            }
17285        }
17286
17287        @Override
17288        public void setImePackagesProvider(PackagesProvider provider) {
17289            synchronized (mPackages) {
17290                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17291            }
17292        }
17293
17294        @Override
17295        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17296            synchronized (mPackages) {
17297                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17298            }
17299        }
17300
17301        @Override
17302        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17303            synchronized (mPackages) {
17304                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17305            }
17306        }
17307
17308        @Override
17309        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17310            synchronized (mPackages) {
17311                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17312            }
17313        }
17314
17315        @Override
17316        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17317            synchronized (mPackages) {
17318                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17319            }
17320        }
17321
17322        @Override
17323        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17324            synchronized (mPackages) {
17325                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17326            }
17327        }
17328
17329        @Override
17330        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17331            synchronized (mPackages) {
17332                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17333                        packageName, userId);
17334            }
17335        }
17336
17337        @Override
17338        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17339            synchronized (mPackages) {
17340                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17341                        packageName, userId);
17342            }
17343        }
17344
17345        @Override
17346        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17347            synchronized (mPackages) {
17348                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17349                        packageName, userId);
17350            }
17351        }
17352
17353        @Override
17354        public void setKeepUninstalledPackages(final List<String> packageList) {
17355            Preconditions.checkNotNull(packageList);
17356            List<String> removedFromList = null;
17357            synchronized (mPackages) {
17358                if (mKeepUninstalledPackages != null) {
17359                    final int packagesCount = mKeepUninstalledPackages.size();
17360                    for (int i = 0; i < packagesCount; i++) {
17361                        String oldPackage = mKeepUninstalledPackages.get(i);
17362                        if (packageList != null && packageList.contains(oldPackage)) {
17363                            continue;
17364                        }
17365                        if (removedFromList == null) {
17366                            removedFromList = new ArrayList<>();
17367                        }
17368                        removedFromList.add(oldPackage);
17369                    }
17370                }
17371                mKeepUninstalledPackages = new ArrayList<>(packageList);
17372                if (removedFromList != null) {
17373                    final int removedCount = removedFromList.size();
17374                    for (int i = 0; i < removedCount; i++) {
17375                        deletePackageIfUnusedLPr(removedFromList.get(i));
17376                    }
17377                }
17378            }
17379        }
17380
17381        @Override
17382        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17383            synchronized (mPackages) {
17384                // If we do not support permission review, done.
17385                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17386                    return false;
17387                }
17388
17389                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17390                if (packageSetting == null) {
17391                    return false;
17392                }
17393
17394                // Permission review applies only to apps not supporting the new permission model.
17395                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17396                    return false;
17397                }
17398
17399                // Legacy apps have the permission and get user consent on launch.
17400                PermissionsState permissionsState = packageSetting.getPermissionsState();
17401                return permissionsState.isPermissionReviewRequired(userId);
17402            }
17403        }
17404    }
17405
17406    @Override
17407    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17408        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17409        synchronized (mPackages) {
17410            final long identity = Binder.clearCallingIdentity();
17411            try {
17412                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17413                        packageNames, userId);
17414            } finally {
17415                Binder.restoreCallingIdentity(identity);
17416            }
17417        }
17418    }
17419
17420    private static void enforceSystemOrPhoneCaller(String tag) {
17421        int callingUid = Binder.getCallingUid();
17422        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17423            throw new SecurityException(
17424                    "Cannot call " + tag + " from UID " + callingUid);
17425        }
17426    }
17427}
17428