PackageManagerService.java revision 2acf063da08dfff69f184c9a6a90a7a5fe60d818
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.EphemeralApplicationInfo;
109import android.content.pm.FeatureInfo;
110import android.content.pm.IOnPermissionsChangeListener;
111import android.content.pm.IPackageDataObserver;
112import android.content.pm.IPackageDeleteObserver;
113import android.content.pm.IPackageDeleteObserver2;
114import android.content.pm.IPackageInstallObserver2;
115import android.content.pm.IPackageInstaller;
116import android.content.pm.IPackageManager;
117import android.content.pm.IPackageMoveObserver;
118import android.content.pm.IPackageStatsObserver;
119import android.content.pm.InstrumentationInfo;
120import android.content.pm.IntentFilterVerificationInfo;
121import android.content.pm.KeySet;
122import android.content.pm.ManifestDigest;
123import android.content.pm.PackageCleanItem;
124import android.content.pm.PackageInfo;
125import android.content.pm.PackageInfoLite;
126import android.content.pm.PackageInstaller;
127import android.content.pm.PackageManager;
128import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
129import android.content.pm.PackageManagerInternal;
130import android.content.pm.PackageParser;
131import android.content.pm.PackageParser.ActivityIntentInfo;
132import android.content.pm.PackageParser.PackageLite;
133import android.content.pm.PackageParser.PackageParserException;
134import android.content.pm.PackageStats;
135import android.content.pm.PackageUserState;
136import android.content.pm.ParceledListSlice;
137import android.content.pm.PermissionGroupInfo;
138import android.content.pm.PermissionInfo;
139import android.content.pm.ProviderInfo;
140import android.content.pm.ResolveInfo;
141import android.content.pm.ServiceInfo;
142import android.content.pm.Signature;
143import android.content.pm.UserInfo;
144import android.content.pm.VerificationParams;
145import android.content.pm.VerifierDeviceIdentity;
146import android.content.pm.VerifierInfo;
147import android.content.res.Resources;
148import android.graphics.Bitmap;
149import android.hardware.display.DisplayManager;
150import android.net.Uri;
151import android.os.Debug;
152import android.os.Binder;
153import android.os.Build;
154import android.os.Bundle;
155import android.os.Environment;
156import android.os.Environment.UserEnvironment;
157import android.os.FileUtils;
158import android.os.Handler;
159import android.os.IBinder;
160import android.os.Looper;
161import android.os.Message;
162import android.os.Parcel;
163import android.os.ParcelFileDescriptor;
164import android.os.Process;
165import android.os.RemoteCallbackList;
166import android.os.RemoteException;
167import android.os.ResultReceiver;
168import android.os.SELinux;
169import android.os.ServiceManager;
170import android.os.SystemClock;
171import android.os.SystemProperties;
172import android.os.Trace;
173import android.os.UserHandle;
174import android.os.UserManager;
175import android.os.storage.IMountService;
176import android.os.storage.MountServiceInternal;
177import android.os.storage.StorageEventListener;
178import android.os.storage.StorageManager;
179import android.os.storage.VolumeInfo;
180import android.os.storage.VolumeRecord;
181import android.security.KeyStore;
182import android.security.SystemKeyStore;
183import android.system.ErrnoException;
184import android.system.Os;
185import android.system.StructStat;
186import android.text.TextUtils;
187import android.text.format.DateUtils;
188import android.util.ArrayMap;
189import android.util.ArraySet;
190import android.util.AtomicFile;
191import android.util.DisplayMetrics;
192import android.util.EventLog;
193import android.util.ExceptionUtils;
194import android.util.Log;
195import android.util.LogPrinter;
196import android.util.MathUtils;
197import android.util.PrintStreamPrinter;
198import android.util.Slog;
199import android.util.SparseArray;
200import android.util.SparseBooleanArray;
201import android.util.SparseIntArray;
202import android.util.Xml;
203import android.view.Display;
204
205import com.android.internal.annotations.GuardedBy;
206import dalvik.system.DexFile;
207import dalvik.system.VMRuntime;
208
209import libcore.io.IoUtils;
210import libcore.util.EmptyArray;
211
212import com.android.internal.R;
213import com.android.internal.app.EphemeralResolveInfo;
214import com.android.internal.app.IMediaContainerService;
215import com.android.internal.app.ResolverActivity;
216import com.android.internal.content.NativeLibraryHelper;
217import com.android.internal.content.PackageHelper;
218import com.android.internal.os.IParcelFileDescriptorFactory;
219import com.android.internal.os.SomeArgs;
220import com.android.internal.os.Zygote;
221import com.android.internal.util.ArrayUtils;
222import com.android.internal.util.FastPrintWriter;
223import com.android.internal.util.FastXmlSerializer;
224import com.android.internal.util.IndentingPrintWriter;
225import com.android.internal.util.Preconditions;
226import com.android.server.EventLogTags;
227import com.android.server.FgThread;
228import com.android.server.IntentResolver;
229import com.android.server.LocalServices;
230import com.android.server.ServiceThread;
231import com.android.server.SystemConfig;
232import com.android.server.Watchdog;
233import com.android.server.pm.PermissionsState.PermissionState;
234import com.android.server.pm.Settings.DatabaseVersion;
235import com.android.server.pm.Settings.VersionInfo;
236import com.android.server.storage.DeviceStorageMonitorInternal;
237
238import org.xmlpull.v1.XmlPullParser;
239import org.xmlpull.v1.XmlPullParserException;
240import org.xmlpull.v1.XmlSerializer;
241
242import java.io.BufferedInputStream;
243import java.io.BufferedOutputStream;
244import java.io.BufferedReader;
245import java.io.ByteArrayInputStream;
246import java.io.ByteArrayOutputStream;
247import java.io.File;
248import java.io.FileDescriptor;
249import java.io.FileNotFoundException;
250import java.io.FileOutputStream;
251import java.io.FileReader;
252import java.io.FilenameFilter;
253import java.io.IOException;
254import java.io.InputStream;
255import java.io.PrintWriter;
256import java.nio.charset.StandardCharsets;
257import java.security.MessageDigest;
258import java.security.NoSuchAlgorithmException;
259import java.security.PublicKey;
260import java.security.cert.CertificateEncodingException;
261import java.security.cert.CertificateException;
262import java.text.SimpleDateFormat;
263import java.util.ArrayList;
264import java.util.Arrays;
265import java.util.Collection;
266import java.util.Collections;
267import java.util.Comparator;
268import java.util.Date;
269import java.util.Iterator;
270import java.util.List;
271import java.util.Map;
272import java.util.Objects;
273import java.util.Set;
274import java.util.concurrent.CountDownLatch;
275import java.util.concurrent.TimeUnit;
276import java.util.concurrent.atomic.AtomicBoolean;
277import java.util.concurrent.atomic.AtomicInteger;
278import java.util.concurrent.atomic.AtomicLong;
279
280/**
281 * Keep track of all those .apks everywhere.
282 *
283 * This is very central to the platform's security; please run the unit
284 * tests whenever making modifications here:
285 *
286runtest -c android.content.pm.PackageManagerTests frameworks-core
287 *
288 * {@hide}
289 */
290public class PackageManagerService extends IPackageManager.Stub {
291    static final String TAG = "PackageManager";
292    static final boolean DEBUG_SETTINGS = false;
293    static final boolean DEBUG_PREFERRED = false;
294    static final boolean DEBUG_UPGRADE = false;
295    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
296    private static final boolean DEBUG_BACKUP = false;
297    private static final boolean DEBUG_INSTALL = false;
298    private static final boolean DEBUG_REMOVE = false;
299    private static final boolean DEBUG_BROADCASTS = false;
300    private static final boolean DEBUG_SHOW_INFO = false;
301    private static final boolean DEBUG_PACKAGE_INFO = false;
302    private static final boolean DEBUG_INTENT_MATCHING = false;
303    private static final boolean DEBUG_PACKAGE_SCANNING = false;
304    private static final boolean DEBUG_VERIFY = false;
305    private static final boolean DEBUG_DEXOPT = false;
306    private static final boolean DEBUG_ABI_SELECTION = false;
307    private static final boolean DEBUG_EPHEMERAL = false;
308
309    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
310
311    private static final int RADIO_UID = Process.PHONE_UID;
312    private static final int LOG_UID = Process.LOG_UID;
313    private static final int NFC_UID = Process.NFC_UID;
314    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
315    private static final int SHELL_UID = Process.SHELL_UID;
316
317    // Cap the size of permission trees that 3rd party apps can define
318    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
319
320    // Suffix used during package installation when copying/moving
321    // package apks to install directory.
322    private static final String INSTALL_PACKAGE_SUFFIX = "-";
323
324    static final int SCAN_NO_DEX = 1<<1;
325    static final int SCAN_FORCE_DEX = 1<<2;
326    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
327    static final int SCAN_NEW_INSTALL = 1<<4;
328    static final int SCAN_NO_PATHS = 1<<5;
329    static final int SCAN_UPDATE_TIME = 1<<6;
330    static final int SCAN_DEFER_DEX = 1<<7;
331    static final int SCAN_BOOTING = 1<<8;
332    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
333    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
334    static final int SCAN_REPLACING = 1<<11;
335    static final int SCAN_REQUIRE_KNOWN = 1<<12;
336    static final int SCAN_MOVE = 1<<13;
337    static final int SCAN_INITIAL = 1<<14;
338
339    static final int REMOVE_CHATTY = 1<<16;
340
341    private static final int[] EMPTY_INT_ARRAY = new int[0];
342
343    /**
344     * Timeout (in milliseconds) after which the watchdog should declare that
345     * our handler thread is wedged.  The usual default for such things is one
346     * minute but we sometimes do very lengthy I/O operations on this thread,
347     * such as installing multi-gigabyte applications, so ours needs to be longer.
348     */
349    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
350
351    /**
352     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
353     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
354     * settings entry if available, otherwise we use the hardcoded default.  If it's been
355     * more than this long since the last fstrim, we force one during the boot sequence.
356     *
357     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
358     * one gets run at the next available charging+idle time.  This final mandatory
359     * no-fstrim check kicks in only of the other scheduling criteria is never met.
360     */
361    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
362
363    /**
364     * Whether verification is enabled by default.
365     */
366    private static final boolean DEFAULT_VERIFY_ENABLE = true;
367
368    /**
369     * The default maximum time to wait for the verification agent to return in
370     * milliseconds.
371     */
372    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
373
374    /**
375     * The default response for package verification timeout.
376     *
377     * This can be either PackageManager.VERIFICATION_ALLOW or
378     * PackageManager.VERIFICATION_REJECT.
379     */
380    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
381
382    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
383
384    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
385            DEFAULT_CONTAINER_PACKAGE,
386            "com.android.defcontainer.DefaultContainerService");
387
388    private static final String KILL_APP_REASON_GIDS_CHANGED =
389            "permission grant or revoke changed gids";
390
391    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
392            "permissions revoked";
393
394    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
395
396    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
397
398    /** Permission grant: not grant the permission. */
399    private static final int GRANT_DENIED = 1;
400
401    /** Permission grant: grant the permission as an install permission. */
402    private static final int GRANT_INSTALL = 2;
403
404    /** Permission grant: grant the permission as a runtime one. */
405    private static final int GRANT_RUNTIME = 3;
406
407    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
408    private static final int GRANT_UPGRADE = 4;
409
410    /** Canonical intent used to identify what counts as a "web browser" app */
411    private static final Intent sBrowserIntent;
412    static {
413        sBrowserIntent = new Intent();
414        sBrowserIntent.setAction(Intent.ACTION_VIEW);
415        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
416        sBrowserIntent.setData(Uri.parse("http:"));
417    }
418
419    final ServiceThread mHandlerThread;
420
421    final PackageHandler mHandler;
422
423    /**
424     * Messages for {@link #mHandler} that need to wait for system ready before
425     * being dispatched.
426     */
427    private ArrayList<Message> mPostSystemReadyMessages;
428
429    final int mSdkVersion = Build.VERSION.SDK_INT;
430
431    final Context mContext;
432    final boolean mFactoryTest;
433    final boolean mOnlyCore;
434    final DisplayMetrics mMetrics;
435    final int mDefParseFlags;
436    final String[] mSeparateProcesses;
437    final boolean mIsUpgrade;
438
439    // This is where all application persistent data goes.
440    final File mAppDataDir;
441
442    // This is where all application persistent data goes for secondary users.
443    final File mUserAppDataDir;
444
445    /** The location for ASEC container files on internal storage. */
446    final String mAsecInternalPath;
447
448    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
449    // LOCK HELD.  Can be called with mInstallLock held.
450    @GuardedBy("mInstallLock")
451    final Installer mInstaller;
452
453    /** Directory where installed third-party apps stored */
454    final File mAppInstallDir;
455    final File mEphemeralInstallDir;
456
457    /**
458     * Directory to which applications installed internally have their
459     * 32 bit native libraries copied.
460     */
461    private File mAppLib32InstallDir;
462
463    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
464    // apps.
465    final File mDrmAppPrivateInstallDir;
466
467    // ----------------------------------------------------------------
468
469    // Lock for state used when installing and doing other long running
470    // operations.  Methods that must be called with this lock held have
471    // the suffix "LI".
472    final Object mInstallLock = new Object();
473
474    // ----------------------------------------------------------------
475
476    // Keys are String (package name), values are Package.  This also serves
477    // as the lock for the global state.  Methods that must be called with
478    // this lock held have the prefix "LP".
479    @GuardedBy("mPackages")
480    final ArrayMap<String, PackageParser.Package> mPackages =
481            new ArrayMap<String, PackageParser.Package>();
482
483    // Tracks available target package names -> overlay package paths.
484    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
485        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
486
487    /**
488     * Tracks new system packages [received in an OTA] that we expect to
489     * find updated user-installed versions. Keys are package name, values
490     * are package location.
491     */
492    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
493
494    /**
495     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
496     */
497    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
498    /**
499     * Whether or not system app permissions should be promoted from install to runtime.
500     */
501    boolean mPromoteSystemApps;
502
503    final Settings mSettings;
504    boolean mRestoredSettings;
505
506    // System configuration read by SystemConfig.
507    final int[] mGlobalGids;
508    final SparseArray<ArraySet<String>> mSystemPermissions;
509    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
510
511    // If mac_permissions.xml was found for seinfo labeling.
512    boolean mFoundPolicyFile;
513
514    // If a recursive restorecon of /data/data/<pkg> is needed.
515    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
516
517    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
518
519    public static final class SharedLibraryEntry {
520        public final String path;
521        public final String apk;
522
523        SharedLibraryEntry(String _path, String _apk) {
524            path = _path;
525            apk = _apk;
526        }
527    }
528
529    // Currently known shared libraries.
530    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
531            new ArrayMap<String, SharedLibraryEntry>();
532
533    // All available activities, for your resolving pleasure.
534    final ActivityIntentResolver mActivities =
535            new ActivityIntentResolver();
536
537    // All available receivers, for your resolving pleasure.
538    final ActivityIntentResolver mReceivers =
539            new ActivityIntentResolver();
540
541    // All available services, for your resolving pleasure.
542    final ServiceIntentResolver mServices = new ServiceIntentResolver();
543
544    // All available providers, for your resolving pleasure.
545    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
546
547    // Mapping from provider base names (first directory in content URI codePath)
548    // to the provider information.
549    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
550            new ArrayMap<String, PackageParser.Provider>();
551
552    // Mapping from instrumentation class names to info about them.
553    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
554            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
555
556    // Mapping from permission names to info about them.
557    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
558            new ArrayMap<String, PackageParser.PermissionGroup>();
559
560    // Packages whose data we have transfered into another package, thus
561    // should no longer exist.
562    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
563
564    // Broadcast actions that are only available to the system.
565    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
566
567    /** List of packages waiting for verification. */
568    final SparseArray<PackageVerificationState> mPendingVerification
569            = new SparseArray<PackageVerificationState>();
570
571    /** Set of packages associated with each app op permission. */
572    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
573
574    final PackageInstallerService mInstallerService;
575
576    private final PackageDexOptimizer mPackageDexOptimizer;
577
578    private AtomicInteger mNextMoveId = new AtomicInteger();
579    private final MoveCallbacks mMoveCallbacks;
580
581    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
582
583    // Cache of users who need badging.
584    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
585
586    /** Token for keys in mPendingVerification. */
587    private int mPendingVerificationToken = 0;
588
589    volatile boolean mSystemReady;
590    volatile boolean mSafeMode;
591    volatile boolean mHasSystemUidErrors;
592
593    ApplicationInfo mAndroidApplication;
594    final ActivityInfo mResolveActivity = new ActivityInfo();
595    final ResolveInfo mResolveInfo = new ResolveInfo();
596    ComponentName mResolveComponentName;
597    PackageParser.Package mPlatformPackage;
598    ComponentName mCustomResolverComponentName;
599
600    boolean mResolverReplaced = false;
601
602    private final ComponentName mIntentFilterVerifierComponent;
603    private int mIntentFilterVerificationToken = 0;
604
605    /** Component that knows whether or not an ephemeral application exists */
606    final ComponentName mEphemeralResolverComponent;
607    /** The service connection to the ephemeral resolver */
608    final EphemeralResolverConnection mEphemeralResolverConnection;
609
610    /** Component used to install ephemeral applications */
611    final ComponentName mEphemeralInstallerComponent;
612    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
613    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
614
615    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
616            = new SparseArray<IntentFilterVerificationState>();
617
618    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
619            new DefaultPermissionGrantPolicy(this);
620
621    // List of packages names to keep cached, even if they are uninstalled for all users
622    private List<String> mKeepUninstalledPackages;
623
624    private static class IFVerificationParams {
625        PackageParser.Package pkg;
626        boolean replacing;
627        int userId;
628        int verifierUid;
629
630        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
631                int _userId, int _verifierUid) {
632            pkg = _pkg;
633            replacing = _replacing;
634            userId = _userId;
635            replacing = _replacing;
636            verifierUid = _verifierUid;
637        }
638    }
639
640    private interface IntentFilterVerifier<T extends IntentFilter> {
641        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
642                                               T filter, String packageName);
643        void startVerifications(int userId);
644        void receiveVerificationResponse(int verificationId);
645    }
646
647    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
648        private Context mContext;
649        private ComponentName mIntentFilterVerifierComponent;
650        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
651
652        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
653            mContext = context;
654            mIntentFilterVerifierComponent = verifierComponent;
655        }
656
657        private String getDefaultScheme() {
658            return IntentFilter.SCHEME_HTTPS;
659        }
660
661        @Override
662        public void startVerifications(int userId) {
663            // Launch verifications requests
664            int count = mCurrentIntentFilterVerifications.size();
665            for (int n=0; n<count; n++) {
666                int verificationId = mCurrentIntentFilterVerifications.get(n);
667                final IntentFilterVerificationState ivs =
668                        mIntentFilterVerificationStates.get(verificationId);
669
670                String packageName = ivs.getPackageName();
671
672                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
673                final int filterCount = filters.size();
674                ArraySet<String> domainsSet = new ArraySet<>();
675                for (int m=0; m<filterCount; m++) {
676                    PackageParser.ActivityIntentInfo filter = filters.get(m);
677                    domainsSet.addAll(filter.getHostsList());
678                }
679                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
680                synchronized (mPackages) {
681                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
682                            packageName, domainsList) != null) {
683                        scheduleWriteSettingsLocked();
684                    }
685                }
686                sendVerificationRequest(userId, verificationId, ivs);
687            }
688            mCurrentIntentFilterVerifications.clear();
689        }
690
691        private void sendVerificationRequest(int userId, int verificationId,
692                IntentFilterVerificationState ivs) {
693
694            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
695            verificationIntent.putExtra(
696                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
697                    verificationId);
698            verificationIntent.putExtra(
699                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
700                    getDefaultScheme());
701            verificationIntent.putExtra(
702                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
703                    ivs.getHostsString());
704            verificationIntent.putExtra(
705                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
706                    ivs.getPackageName());
707            verificationIntent.setComponent(mIntentFilterVerifierComponent);
708            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
709
710            UserHandle user = new UserHandle(userId);
711            mContext.sendBroadcastAsUser(verificationIntent, user);
712            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
713                    "Sending IntentFilter verification broadcast");
714        }
715
716        public void receiveVerificationResponse(int verificationId) {
717            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
718
719            final boolean verified = ivs.isVerified();
720
721            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
722            final int count = filters.size();
723            if (DEBUG_DOMAIN_VERIFICATION) {
724                Slog.i(TAG, "Received verification response " + verificationId
725                        + " for " + count + " filters, verified=" + verified);
726            }
727            for (int n=0; n<count; n++) {
728                PackageParser.ActivityIntentInfo filter = filters.get(n);
729                filter.setVerified(verified);
730
731                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
732                        + " verified with result:" + verified + " and hosts:"
733                        + ivs.getHostsString());
734            }
735
736            mIntentFilterVerificationStates.remove(verificationId);
737
738            final String packageName = ivs.getPackageName();
739            IntentFilterVerificationInfo ivi = null;
740
741            synchronized (mPackages) {
742                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
743            }
744            if (ivi == null) {
745                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
746                        + verificationId + " packageName:" + packageName);
747                return;
748            }
749            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
750                    "Updating IntentFilterVerificationInfo for package " + packageName
751                            +" verificationId:" + verificationId);
752
753            synchronized (mPackages) {
754                if (verified) {
755                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
756                } else {
757                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
758                }
759                scheduleWriteSettingsLocked();
760
761                final int userId = ivs.getUserId();
762                if (userId != UserHandle.USER_ALL) {
763                    final int userStatus =
764                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
765
766                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
767                    boolean needUpdate = false;
768
769                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
770                    // already been set by the User thru the Disambiguation dialog
771                    switch (userStatus) {
772                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
773                            if (verified) {
774                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
775                            } else {
776                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
777                            }
778                            needUpdate = true;
779                            break;
780
781                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
782                            if (verified) {
783                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
784                                needUpdate = true;
785                            }
786                            break;
787
788                        default:
789                            // Nothing to do
790                    }
791
792                    if (needUpdate) {
793                        mSettings.updateIntentFilterVerificationStatusLPw(
794                                packageName, updatedStatus, userId);
795                        scheduleWritePackageRestrictionsLocked(userId);
796                    }
797                }
798            }
799        }
800
801        @Override
802        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
803                    ActivityIntentInfo filter, String packageName) {
804            if (!hasValidDomains(filter)) {
805                return false;
806            }
807            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
808            if (ivs == null) {
809                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
810                        packageName);
811            }
812            if (DEBUG_DOMAIN_VERIFICATION) {
813                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
814            }
815            ivs.addFilter(filter);
816            return true;
817        }
818
819        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
820                int userId, int verificationId, String packageName) {
821            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
822                    verifierUid, userId, packageName);
823            ivs.setPendingState();
824            synchronized (mPackages) {
825                mIntentFilterVerificationStates.append(verificationId, ivs);
826                mCurrentIntentFilterVerifications.add(verificationId);
827            }
828            return ivs;
829        }
830    }
831
832    private static boolean hasValidDomains(ActivityIntentInfo filter) {
833        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
834                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
835                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
836    }
837
838    private IntentFilterVerifier mIntentFilterVerifier;
839
840    // Set of pending broadcasts for aggregating enable/disable of components.
841    static class PendingPackageBroadcasts {
842        // for each user id, a map of <package name -> components within that package>
843        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
844
845        public PendingPackageBroadcasts() {
846            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
847        }
848
849        public ArrayList<String> get(int userId, String packageName) {
850            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
851            return packages.get(packageName);
852        }
853
854        public void put(int userId, String packageName, ArrayList<String> components) {
855            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
856            packages.put(packageName, components);
857        }
858
859        public void remove(int userId, String packageName) {
860            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
861            if (packages != null) {
862                packages.remove(packageName);
863            }
864        }
865
866        public void remove(int userId) {
867            mUidMap.remove(userId);
868        }
869
870        public int userIdCount() {
871            return mUidMap.size();
872        }
873
874        public int userIdAt(int n) {
875            return mUidMap.keyAt(n);
876        }
877
878        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
879            return mUidMap.get(userId);
880        }
881
882        public int size() {
883            // total number of pending broadcast entries across all userIds
884            int num = 0;
885            for (int i = 0; i< mUidMap.size(); i++) {
886                num += mUidMap.valueAt(i).size();
887            }
888            return num;
889        }
890
891        public void clear() {
892            mUidMap.clear();
893        }
894
895        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
896            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
897            if (map == null) {
898                map = new ArrayMap<String, ArrayList<String>>();
899                mUidMap.put(userId, map);
900            }
901            return map;
902        }
903    }
904    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
905
906    // Service Connection to remote media container service to copy
907    // package uri's from external media onto secure containers
908    // or internal storage.
909    private IMediaContainerService mContainerService = null;
910
911    static final int SEND_PENDING_BROADCAST = 1;
912    static final int MCS_BOUND = 3;
913    static final int END_COPY = 4;
914    static final int INIT_COPY = 5;
915    static final int MCS_UNBIND = 6;
916    static final int START_CLEANING_PACKAGE = 7;
917    static final int FIND_INSTALL_LOC = 8;
918    static final int POST_INSTALL = 9;
919    static final int MCS_RECONNECT = 10;
920    static final int MCS_GIVE_UP = 11;
921    static final int UPDATED_MEDIA_STATUS = 12;
922    static final int WRITE_SETTINGS = 13;
923    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
924    static final int PACKAGE_VERIFIED = 15;
925    static final int CHECK_PENDING_VERIFICATION = 16;
926    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
927    static final int INTENT_FILTER_VERIFIED = 18;
928
929    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
930
931    // Delay time in millisecs
932    static final int BROADCAST_DELAY = 10 * 1000;
933
934    static UserManagerService sUserManager;
935
936    // Stores a list of users whose package restrictions file needs to be updated
937    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
938
939    final private DefaultContainerConnection mDefContainerConn =
940            new DefaultContainerConnection();
941    class DefaultContainerConnection implements ServiceConnection {
942        public void onServiceConnected(ComponentName name, IBinder service) {
943            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
944            IMediaContainerService imcs =
945                IMediaContainerService.Stub.asInterface(service);
946            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
947        }
948
949        public void onServiceDisconnected(ComponentName name) {
950            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
951        }
952    }
953
954    // Recordkeeping of restore-after-install operations that are currently in flight
955    // between the Package Manager and the Backup Manager
956    class PostInstallData {
957        public InstallArgs args;
958        public PackageInstalledInfo res;
959
960        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
961            args = _a;
962            res = _r;
963        }
964    }
965
966    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
967    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
968
969    // XML tags for backup/restore of various bits of state
970    private static final String TAG_PREFERRED_BACKUP = "pa";
971    private static final String TAG_DEFAULT_APPS = "da";
972    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
973
974    final String mRequiredVerifierPackage;
975    final String mRequiredInstallerPackage;
976
977    private final PackageUsage mPackageUsage = new PackageUsage();
978
979    private class PackageUsage {
980        private static final int WRITE_INTERVAL
981            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
982
983        private final Object mFileLock = new Object();
984        private final AtomicLong mLastWritten = new AtomicLong(0);
985        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
986
987        private boolean mIsHistoricalPackageUsageAvailable = true;
988
989        boolean isHistoricalPackageUsageAvailable() {
990            return mIsHistoricalPackageUsageAvailable;
991        }
992
993        void write(boolean force) {
994            if (force) {
995                writeInternal();
996                return;
997            }
998            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
999                && !DEBUG_DEXOPT) {
1000                return;
1001            }
1002            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1003                new Thread("PackageUsage_DiskWriter") {
1004                    @Override
1005                    public void run() {
1006                        try {
1007                            writeInternal();
1008                        } finally {
1009                            mBackgroundWriteRunning.set(false);
1010                        }
1011                    }
1012                }.start();
1013            }
1014        }
1015
1016        private void writeInternal() {
1017            synchronized (mPackages) {
1018                synchronized (mFileLock) {
1019                    AtomicFile file = getFile();
1020                    FileOutputStream f = null;
1021                    try {
1022                        f = file.startWrite();
1023                        BufferedOutputStream out = new BufferedOutputStream(f);
1024                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1025                        StringBuilder sb = new StringBuilder();
1026                        for (PackageParser.Package pkg : mPackages.values()) {
1027                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1028                                continue;
1029                            }
1030                            sb.setLength(0);
1031                            sb.append(pkg.packageName);
1032                            sb.append(' ');
1033                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1034                            sb.append('\n');
1035                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1036                        }
1037                        out.flush();
1038                        file.finishWrite(f);
1039                    } catch (IOException e) {
1040                        if (f != null) {
1041                            file.failWrite(f);
1042                        }
1043                        Log.e(TAG, "Failed to write package usage times", e);
1044                    }
1045                }
1046            }
1047            mLastWritten.set(SystemClock.elapsedRealtime());
1048        }
1049
1050        void readLP() {
1051            synchronized (mFileLock) {
1052                AtomicFile file = getFile();
1053                BufferedInputStream in = null;
1054                try {
1055                    in = new BufferedInputStream(file.openRead());
1056                    StringBuffer sb = new StringBuffer();
1057                    while (true) {
1058                        String packageName = readToken(in, sb, ' ');
1059                        if (packageName == null) {
1060                            break;
1061                        }
1062                        String timeInMillisString = readToken(in, sb, '\n');
1063                        if (timeInMillisString == null) {
1064                            throw new IOException("Failed to find last usage time for package "
1065                                                  + packageName);
1066                        }
1067                        PackageParser.Package pkg = mPackages.get(packageName);
1068                        if (pkg == null) {
1069                            continue;
1070                        }
1071                        long timeInMillis;
1072                        try {
1073                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1074                        } catch (NumberFormatException e) {
1075                            throw new IOException("Failed to parse " + timeInMillisString
1076                                                  + " as a long.", e);
1077                        }
1078                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1079                    }
1080                } catch (FileNotFoundException expected) {
1081                    mIsHistoricalPackageUsageAvailable = false;
1082                } catch (IOException e) {
1083                    Log.w(TAG, "Failed to read package usage times", e);
1084                } finally {
1085                    IoUtils.closeQuietly(in);
1086                }
1087            }
1088            mLastWritten.set(SystemClock.elapsedRealtime());
1089        }
1090
1091        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1092                throws IOException {
1093            sb.setLength(0);
1094            while (true) {
1095                int ch = in.read();
1096                if (ch == -1) {
1097                    if (sb.length() == 0) {
1098                        return null;
1099                    }
1100                    throw new IOException("Unexpected EOF");
1101                }
1102                if (ch == endOfToken) {
1103                    return sb.toString();
1104                }
1105                sb.append((char)ch);
1106            }
1107        }
1108
1109        private AtomicFile getFile() {
1110            File dataDir = Environment.getDataDirectory();
1111            File systemDir = new File(dataDir, "system");
1112            File fname = new File(systemDir, "package-usage.list");
1113            return new AtomicFile(fname);
1114        }
1115    }
1116
1117    class PackageHandler extends Handler {
1118        private boolean mBound = false;
1119        final ArrayList<HandlerParams> mPendingInstalls =
1120            new ArrayList<HandlerParams>();
1121
1122        private boolean connectToService() {
1123            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1124                    " DefaultContainerService");
1125            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1126            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1127            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1128                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1129                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1130                mBound = true;
1131                return true;
1132            }
1133            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1134            return false;
1135        }
1136
1137        private void disconnectService() {
1138            mContainerService = null;
1139            mBound = false;
1140            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1141            mContext.unbindService(mDefContainerConn);
1142            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1143        }
1144
1145        PackageHandler(Looper looper) {
1146            super(looper);
1147        }
1148
1149        public void handleMessage(Message msg) {
1150            try {
1151                doHandleMessage(msg);
1152            } finally {
1153                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1154            }
1155        }
1156
1157        void doHandleMessage(Message msg) {
1158            switch (msg.what) {
1159                case INIT_COPY: {
1160                    HandlerParams params = (HandlerParams) msg.obj;
1161                    int idx = mPendingInstalls.size();
1162                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1163                    // If a bind was already initiated we dont really
1164                    // need to do anything. The pending install
1165                    // will be processed later on.
1166                    if (!mBound) {
1167                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1168                                System.identityHashCode(mHandler));
1169                        // If this is the only one pending we might
1170                        // have to bind to the service again.
1171                        if (!connectToService()) {
1172                            Slog.e(TAG, "Failed to bind to media container service");
1173                            params.serviceError();
1174                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1175                                    System.identityHashCode(mHandler));
1176                            if (params.traceMethod != null) {
1177                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1178                                        params.traceCookie);
1179                            }
1180                            return;
1181                        } else {
1182                            // Once we bind to the service, the first
1183                            // pending request will be processed.
1184                            mPendingInstalls.add(idx, params);
1185                        }
1186                    } else {
1187                        mPendingInstalls.add(idx, params);
1188                        // Already bound to the service. Just make
1189                        // sure we trigger off processing the first request.
1190                        if (idx == 0) {
1191                            mHandler.sendEmptyMessage(MCS_BOUND);
1192                        }
1193                    }
1194                    break;
1195                }
1196                case MCS_BOUND: {
1197                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1198                    if (msg.obj != null) {
1199                        mContainerService = (IMediaContainerService) msg.obj;
1200                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1201                                System.identityHashCode(mHandler));
1202                    }
1203                    if (mContainerService == null) {
1204                        if (!mBound) {
1205                            // Something seriously wrong since we are not bound and we are not
1206                            // waiting for connection. Bail out.
1207                            Slog.e(TAG, "Cannot bind to media container service");
1208                            for (HandlerParams params : mPendingInstalls) {
1209                                // Indicate service bind error
1210                                params.serviceError();
1211                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1212                                        System.identityHashCode(params));
1213                                if (params.traceMethod != null) {
1214                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1215                                            params.traceMethod, params.traceCookie);
1216                                }
1217                                return;
1218                            }
1219                            mPendingInstalls.clear();
1220                        } else {
1221                            Slog.w(TAG, "Waiting to connect to media container service");
1222                        }
1223                    } else if (mPendingInstalls.size() > 0) {
1224                        HandlerParams params = mPendingInstalls.get(0);
1225                        if (params != null) {
1226                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1227                                    System.identityHashCode(params));
1228                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1229                            if (params.startCopy()) {
1230                                // We are done...  look for more work or to
1231                                // go idle.
1232                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1233                                        "Checking for more work or unbind...");
1234                                // Delete pending install
1235                                if (mPendingInstalls.size() > 0) {
1236                                    mPendingInstalls.remove(0);
1237                                }
1238                                if (mPendingInstalls.size() == 0) {
1239                                    if (mBound) {
1240                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1241                                                "Posting delayed MCS_UNBIND");
1242                                        removeMessages(MCS_UNBIND);
1243                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1244                                        // Unbind after a little delay, to avoid
1245                                        // continual thrashing.
1246                                        sendMessageDelayed(ubmsg, 10000);
1247                                    }
1248                                } else {
1249                                    // There are more pending requests in queue.
1250                                    // Just post MCS_BOUND message to trigger processing
1251                                    // of next pending install.
1252                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1253                                            "Posting MCS_BOUND for next work");
1254                                    mHandler.sendEmptyMessage(MCS_BOUND);
1255                                }
1256                            }
1257                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1258                        }
1259                    } else {
1260                        // Should never happen ideally.
1261                        Slog.w(TAG, "Empty queue");
1262                    }
1263                    break;
1264                }
1265                case MCS_RECONNECT: {
1266                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1267                    if (mPendingInstalls.size() > 0) {
1268                        if (mBound) {
1269                            disconnectService();
1270                        }
1271                        if (!connectToService()) {
1272                            Slog.e(TAG, "Failed to bind to media container service");
1273                            for (HandlerParams params : mPendingInstalls) {
1274                                // Indicate service bind error
1275                                params.serviceError();
1276                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1277                                        System.identityHashCode(params));
1278                            }
1279                            mPendingInstalls.clear();
1280                        }
1281                    }
1282                    break;
1283                }
1284                case MCS_UNBIND: {
1285                    // If there is no actual work left, then time to unbind.
1286                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1287
1288                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1289                        if (mBound) {
1290                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1291
1292                            disconnectService();
1293                        }
1294                    } else if (mPendingInstalls.size() > 0) {
1295                        // There are more pending requests in queue.
1296                        // Just post MCS_BOUND message to trigger processing
1297                        // of next pending install.
1298                        mHandler.sendEmptyMessage(MCS_BOUND);
1299                    }
1300
1301                    break;
1302                }
1303                case MCS_GIVE_UP: {
1304                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1305                    HandlerParams params = mPendingInstalls.remove(0);
1306                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1307                            System.identityHashCode(params));
1308                    break;
1309                }
1310                case SEND_PENDING_BROADCAST: {
1311                    String packages[];
1312                    ArrayList<String> components[];
1313                    int size = 0;
1314                    int uids[];
1315                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1316                    synchronized (mPackages) {
1317                        if (mPendingBroadcasts == null) {
1318                            return;
1319                        }
1320                        size = mPendingBroadcasts.size();
1321                        if (size <= 0) {
1322                            // Nothing to be done. Just return
1323                            return;
1324                        }
1325                        packages = new String[size];
1326                        components = new ArrayList[size];
1327                        uids = new int[size];
1328                        int i = 0;  // filling out the above arrays
1329
1330                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1331                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1332                            Iterator<Map.Entry<String, ArrayList<String>>> it
1333                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1334                                            .entrySet().iterator();
1335                            while (it.hasNext() && i < size) {
1336                                Map.Entry<String, ArrayList<String>> ent = it.next();
1337                                packages[i] = ent.getKey();
1338                                components[i] = ent.getValue();
1339                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1340                                uids[i] = (ps != null)
1341                                        ? UserHandle.getUid(packageUserId, ps.appId)
1342                                        : -1;
1343                                i++;
1344                            }
1345                        }
1346                        size = i;
1347                        mPendingBroadcasts.clear();
1348                    }
1349                    // Send broadcasts
1350                    for (int i = 0; i < size; i++) {
1351                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1352                    }
1353                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1354                    break;
1355                }
1356                case START_CLEANING_PACKAGE: {
1357                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1358                    final String packageName = (String)msg.obj;
1359                    final int userId = msg.arg1;
1360                    final boolean andCode = msg.arg2 != 0;
1361                    synchronized (mPackages) {
1362                        if (userId == UserHandle.USER_ALL) {
1363                            int[] users = sUserManager.getUserIds();
1364                            for (int user : users) {
1365                                mSettings.addPackageToCleanLPw(
1366                                        new PackageCleanItem(user, packageName, andCode));
1367                            }
1368                        } else {
1369                            mSettings.addPackageToCleanLPw(
1370                                    new PackageCleanItem(userId, packageName, andCode));
1371                        }
1372                    }
1373                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1374                    startCleaningPackages();
1375                } break;
1376                case POST_INSTALL: {
1377                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1378
1379                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1380                    mRunningInstalls.delete(msg.arg1);
1381                    boolean deleteOld = false;
1382
1383                    if (data != null) {
1384                        InstallArgs args = data.args;
1385                        PackageInstalledInfo res = data.res;
1386
1387                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1388                            final String packageName = res.pkg.applicationInfo.packageName;
1389                            res.removedInfo.sendBroadcast(false, true, false);
1390                            Bundle extras = new Bundle(1);
1391                            extras.putInt(Intent.EXTRA_UID, res.uid);
1392
1393                            // Now that we successfully installed the package, grant runtime
1394                            // permissions if requested before broadcasting the install.
1395                            if ((args.installFlags
1396                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1397                                    && res.pkg.applicationInfo.targetSdkVersion
1398                                            >= Build.VERSION_CODES.M) {
1399                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1400                                        args.installGrantPermissions);
1401                            }
1402
1403                            synchronized (mPackages) {
1404                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1405                            }
1406
1407                            // Determine the set of users who are adding this
1408                            // package for the first time vs. those who are seeing
1409                            // an update.
1410                            int[] firstUsers;
1411                            int[] updateUsers = new int[0];
1412                            if (res.origUsers == null || res.origUsers.length == 0) {
1413                                firstUsers = res.newUsers;
1414                            } else {
1415                                firstUsers = new int[0];
1416                                for (int i=0; i<res.newUsers.length; i++) {
1417                                    int user = res.newUsers[i];
1418                                    boolean isNew = true;
1419                                    for (int j=0; j<res.origUsers.length; j++) {
1420                                        if (res.origUsers[j] == user) {
1421                                            isNew = false;
1422                                            break;
1423                                        }
1424                                    }
1425                                    if (isNew) {
1426                                        int[] newFirst = new int[firstUsers.length+1];
1427                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1428                                                firstUsers.length);
1429                                        newFirst[firstUsers.length] = user;
1430                                        firstUsers = newFirst;
1431                                    } else {
1432                                        int[] newUpdate = new int[updateUsers.length+1];
1433                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1434                                                updateUsers.length);
1435                                        newUpdate[updateUsers.length] = user;
1436                                        updateUsers = newUpdate;
1437                                    }
1438                                }
1439                            }
1440                            // don't broadcast for ephemeral installs/updates
1441                            final boolean isEphemeral = isEphemeral(res.pkg);
1442                            if (!isEphemeral) {
1443                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1444                                        extras, 0 /*flags*/, null /*targetPackage*/,
1445                                        null /*finishedReceiver*/, firstUsers);
1446                            }
1447                            final boolean update = res.removedInfo.removedPackage != null;
1448                            if (update) {
1449                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1450                            }
1451                            if (!isEphemeral) {
1452                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1453                                        extras, 0 /*flags*/, null /*targetPackage*/,
1454                                        null /*finishedReceiver*/, updateUsers);
1455                            }
1456                            if (update) {
1457                                if (!isEphemeral) {
1458                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1459                                            packageName, extras, 0 /*flags*/,
1460                                            null /*targetPackage*/, null /*finishedReceiver*/,
1461                                            updateUsers);
1462                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1463                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1464                                            packageName /*targetPackage*/,
1465                                            null /*finishedReceiver*/, updateUsers);
1466                                }
1467
1468                                // treat asec-hosted packages like removable media on upgrade
1469                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1470                                    if (DEBUG_INSTALL) {
1471                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1472                                                + " is ASEC-hosted -> AVAILABLE");
1473                                    }
1474                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1475                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1476                                    pkgList.add(packageName);
1477                                    sendResourcesChangedBroadcast(true, true,
1478                                            pkgList,uidArray, null);
1479                                }
1480                            }
1481                            if (res.removedInfo.args != null) {
1482                                // Remove the replaced package's older resources safely now
1483                                deleteOld = true;
1484                            }
1485
1486                            // If this app is a browser and it's newly-installed for some
1487                            // users, clear any default-browser state in those users
1488                            if (firstUsers.length > 0) {
1489                                // the app's nature doesn't depend on the user, so we can just
1490                                // check its browser nature in any user and generalize.
1491                                if (packageIsBrowser(packageName, firstUsers[0])) {
1492                                    synchronized (mPackages) {
1493                                        for (int userId : firstUsers) {
1494                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1495                                        }
1496                                    }
1497                                }
1498                            }
1499                            // Log current value of "unknown sources" setting
1500                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1501                                getUnknownSourcesSettings());
1502                        }
1503                        // Force a gc to clear up things
1504                        Runtime.getRuntime().gc();
1505                        // We delete after a gc for applications  on sdcard.
1506                        if (deleteOld) {
1507                            synchronized (mInstallLock) {
1508                                res.removedInfo.args.doPostDeleteLI(true);
1509                            }
1510                        }
1511                        if (args.observer != null) {
1512                            try {
1513                                Bundle extras = extrasForInstallResult(res);
1514                                args.observer.onPackageInstalled(res.name, res.returnCode,
1515                                        res.returnMsg, extras);
1516                            } catch (RemoteException e) {
1517                                Slog.i(TAG, "Observer no longer exists.");
1518                            }
1519                        }
1520                        if (args.traceMethod != null) {
1521                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1522                                    args.traceCookie);
1523                        }
1524                        return;
1525                    } else {
1526                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1527                    }
1528
1529                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1530                } break;
1531                case UPDATED_MEDIA_STATUS: {
1532                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1533                    boolean reportStatus = msg.arg1 == 1;
1534                    boolean doGc = msg.arg2 == 1;
1535                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1536                    if (doGc) {
1537                        // Force a gc to clear up stale containers.
1538                        Runtime.getRuntime().gc();
1539                    }
1540                    if (msg.obj != null) {
1541                        @SuppressWarnings("unchecked")
1542                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1543                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1544                        // Unload containers
1545                        unloadAllContainers(args);
1546                    }
1547                    if (reportStatus) {
1548                        try {
1549                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1550                            PackageHelper.getMountService().finishMediaUpdate();
1551                        } catch (RemoteException e) {
1552                            Log.e(TAG, "MountService not running?");
1553                        }
1554                    }
1555                } break;
1556                case WRITE_SETTINGS: {
1557                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1558                    synchronized (mPackages) {
1559                        removeMessages(WRITE_SETTINGS);
1560                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1561                        mSettings.writeLPr();
1562                        mDirtyUsers.clear();
1563                    }
1564                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1565                } break;
1566                case WRITE_PACKAGE_RESTRICTIONS: {
1567                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1568                    synchronized (mPackages) {
1569                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1570                        for (int userId : mDirtyUsers) {
1571                            mSettings.writePackageRestrictionsLPr(userId);
1572                        }
1573                        mDirtyUsers.clear();
1574                    }
1575                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1576                } break;
1577                case CHECK_PENDING_VERIFICATION: {
1578                    final int verificationId = msg.arg1;
1579                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1580
1581                    if ((state != null) && !state.timeoutExtended()) {
1582                        final InstallArgs args = state.getInstallArgs();
1583                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1584
1585                        Slog.i(TAG, "Verification timed out for " + originUri);
1586                        mPendingVerification.remove(verificationId);
1587
1588                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1589
1590                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1591                            Slog.i(TAG, "Continuing with installation of " + originUri);
1592                            state.setVerifierResponse(Binder.getCallingUid(),
1593                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1594                            broadcastPackageVerified(verificationId, originUri,
1595                                    PackageManager.VERIFICATION_ALLOW,
1596                                    state.getInstallArgs().getUser());
1597                            try {
1598                                ret = args.copyApk(mContainerService, true);
1599                            } catch (RemoteException e) {
1600                                Slog.e(TAG, "Could not contact the ContainerService");
1601                            }
1602                        } else {
1603                            broadcastPackageVerified(verificationId, originUri,
1604                                    PackageManager.VERIFICATION_REJECT,
1605                                    state.getInstallArgs().getUser());
1606                        }
1607
1608                        Trace.asyncTraceEnd(
1609                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1610
1611                        processPendingInstall(args, ret);
1612                        mHandler.sendEmptyMessage(MCS_UNBIND);
1613                    }
1614                    break;
1615                }
1616                case PACKAGE_VERIFIED: {
1617                    final int verificationId = msg.arg1;
1618
1619                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1620                    if (state == null) {
1621                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1622                        break;
1623                    }
1624
1625                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1626
1627                    state.setVerifierResponse(response.callerUid, response.code);
1628
1629                    if (state.isVerificationComplete()) {
1630                        mPendingVerification.remove(verificationId);
1631
1632                        final InstallArgs args = state.getInstallArgs();
1633                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1634
1635                        int ret;
1636                        if (state.isInstallAllowed()) {
1637                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1638                            broadcastPackageVerified(verificationId, originUri,
1639                                    response.code, state.getInstallArgs().getUser());
1640                            try {
1641                                ret = args.copyApk(mContainerService, true);
1642                            } catch (RemoteException e) {
1643                                Slog.e(TAG, "Could not contact the ContainerService");
1644                            }
1645                        } else {
1646                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1647                        }
1648
1649                        Trace.asyncTraceEnd(
1650                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1651
1652                        processPendingInstall(args, ret);
1653                        mHandler.sendEmptyMessage(MCS_UNBIND);
1654                    }
1655
1656                    break;
1657                }
1658                case START_INTENT_FILTER_VERIFICATIONS: {
1659                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1660                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1661                            params.replacing, params.pkg);
1662                    break;
1663                }
1664                case INTENT_FILTER_VERIFIED: {
1665                    final int verificationId = msg.arg1;
1666
1667                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1668                            verificationId);
1669                    if (state == null) {
1670                        Slog.w(TAG, "Invalid IntentFilter verification token "
1671                                + verificationId + " received");
1672                        break;
1673                    }
1674
1675                    final int userId = state.getUserId();
1676
1677                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1678                            "Processing IntentFilter verification with token:"
1679                            + verificationId + " and userId:" + userId);
1680
1681                    final IntentFilterVerificationResponse response =
1682                            (IntentFilterVerificationResponse) msg.obj;
1683
1684                    state.setVerifierResponse(response.callerUid, response.code);
1685
1686                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1687                            "IntentFilter verification with token:" + verificationId
1688                            + " and userId:" + userId
1689                            + " is settings verifier response with response code:"
1690                            + response.code);
1691
1692                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1693                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1694                                + response.getFailedDomainsString());
1695                    }
1696
1697                    if (state.isVerificationComplete()) {
1698                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1699                    } else {
1700                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1701                                "IntentFilter verification with token:" + verificationId
1702                                + " was not said to be complete");
1703                    }
1704
1705                    break;
1706                }
1707            }
1708        }
1709    }
1710
1711    private StorageEventListener mStorageListener = new StorageEventListener() {
1712        @Override
1713        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1714            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1715                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1716                    final String volumeUuid = vol.getFsUuid();
1717
1718                    // Clean up any users or apps that were removed or recreated
1719                    // while this volume was missing
1720                    reconcileUsers(volumeUuid);
1721                    reconcileApps(volumeUuid);
1722
1723                    // Clean up any install sessions that expired or were
1724                    // cancelled while this volume was missing
1725                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1726
1727                    loadPrivatePackages(vol);
1728
1729                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1730                    unloadPrivatePackages(vol);
1731                }
1732            }
1733
1734            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1735                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1736                    updateExternalMediaStatus(true, false);
1737                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1738                    updateExternalMediaStatus(false, false);
1739                }
1740            }
1741        }
1742
1743        @Override
1744        public void onVolumeForgotten(String fsUuid) {
1745            if (TextUtils.isEmpty(fsUuid)) {
1746                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1747                return;
1748            }
1749
1750            // Remove any apps installed on the forgotten volume
1751            synchronized (mPackages) {
1752                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1753                for (PackageSetting ps : packages) {
1754                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1755                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1756                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1757                }
1758
1759                mSettings.onVolumeForgotten(fsUuid);
1760                mSettings.writeLPr();
1761            }
1762        }
1763    };
1764
1765    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1766            String[] grantedPermissions) {
1767        if (userId >= UserHandle.USER_SYSTEM) {
1768            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1769        } else if (userId == UserHandle.USER_ALL) {
1770            final int[] userIds;
1771            synchronized (mPackages) {
1772                userIds = UserManagerService.getInstance().getUserIds();
1773            }
1774            for (int someUserId : userIds) {
1775                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1776            }
1777        }
1778
1779        // We could have touched GID membership, so flush out packages.list
1780        synchronized (mPackages) {
1781            mSettings.writePackageListLPr();
1782        }
1783    }
1784
1785    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1786            String[] grantedPermissions) {
1787        SettingBase sb = (SettingBase) pkg.mExtras;
1788        if (sb == null) {
1789            return;
1790        }
1791
1792        PermissionsState permissionsState = sb.getPermissionsState();
1793
1794        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1795                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1796
1797        synchronized (mPackages) {
1798            for (String permission : pkg.requestedPermissions) {
1799                BasePermission bp = mSettings.mPermissions.get(permission);
1800                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1801                        && (grantedPermissions == null
1802                               || ArrayUtils.contains(grantedPermissions, permission))) {
1803                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1804                    // Installer cannot change immutable permissions.
1805                    if ((flags & immutableFlags) == 0) {
1806                        grantRuntimePermission(pkg.packageName, permission, userId);
1807                    }
1808                }
1809            }
1810        }
1811    }
1812
1813    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1814        Bundle extras = null;
1815        switch (res.returnCode) {
1816            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1817                extras = new Bundle();
1818                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1819                        res.origPermission);
1820                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1821                        res.origPackage);
1822                break;
1823            }
1824            case PackageManager.INSTALL_SUCCEEDED: {
1825                extras = new Bundle();
1826                extras.putBoolean(Intent.EXTRA_REPLACING,
1827                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1828                break;
1829            }
1830        }
1831        return extras;
1832    }
1833
1834    void scheduleWriteSettingsLocked() {
1835        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1836            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1837        }
1838    }
1839
1840    void scheduleWritePackageRestrictionsLocked(int userId) {
1841        if (!sUserManager.exists(userId)) return;
1842        mDirtyUsers.add(userId);
1843        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1844            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1845        }
1846    }
1847
1848    public static PackageManagerService main(Context context, Installer installer,
1849            boolean factoryTest, boolean onlyCore) {
1850        PackageManagerService m = new PackageManagerService(context, installer,
1851                factoryTest, onlyCore);
1852        m.enableSystemUserApps();
1853        ServiceManager.addService("package", m);
1854        return m;
1855    }
1856
1857    private void enableSystemUserApps() {
1858        if (!UserManager.isSplitSystemUser()) {
1859            return;
1860        }
1861        // For system user, enable apps based on the following conditions:
1862        // - app is whitelisted or belong to one of these groups:
1863        //   -- system app which has no launcher icons
1864        //   -- system app which has INTERACT_ACROSS_USERS permission
1865        //   -- system IME app
1866        // - app is not in the blacklist
1867        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1868        Set<String> enableApps = new ArraySet<>();
1869        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1870                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1871                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1872        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1873        enableApps.addAll(wlApps);
1874        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1875        enableApps.removeAll(blApps);
1876
1877        List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true,
1878                UserHandle.SYSTEM);
1879        final int systemAppsSize = systemApps.size();
1880        synchronized (mPackages) {
1881            for (int i = 0; i < systemAppsSize; i++) {
1882                String pName = systemApps.get(i);
1883                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1884                // Should not happen, but we shouldn't be failing if it does
1885                if (pkgSetting == null) {
1886                    continue;
1887                }
1888                boolean installed = enableApps.contains(pName);
1889                pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM);
1890            }
1891        }
1892    }
1893
1894    static String[] splitString(String str, char sep) {
1895        int count = 1;
1896        int i = 0;
1897        while ((i=str.indexOf(sep, i)) >= 0) {
1898            count++;
1899            i++;
1900        }
1901
1902        String[] res = new String[count];
1903        i=0;
1904        count = 0;
1905        int lastI=0;
1906        while ((i=str.indexOf(sep, i)) >= 0) {
1907            res[count] = str.substring(lastI, i);
1908            count++;
1909            i++;
1910            lastI = i;
1911        }
1912        res[count] = str.substring(lastI, str.length());
1913        return res;
1914    }
1915
1916    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1917        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1918                Context.DISPLAY_SERVICE);
1919        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1920    }
1921
1922    public PackageManagerService(Context context, Installer installer,
1923            boolean factoryTest, boolean onlyCore) {
1924        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1925                SystemClock.uptimeMillis());
1926
1927        if (mSdkVersion <= 0) {
1928            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1929        }
1930
1931        mContext = context;
1932        mFactoryTest = factoryTest;
1933        mOnlyCore = onlyCore;
1934        mMetrics = new DisplayMetrics();
1935        mSettings = new Settings(mPackages);
1936        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1937                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1938        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1939                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1940        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1941                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1942        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1943                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1944        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1945                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1946        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1947                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1948
1949        String separateProcesses = SystemProperties.get("debug.separate_processes");
1950        if (separateProcesses != null && separateProcesses.length() > 0) {
1951            if ("*".equals(separateProcesses)) {
1952                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1953                mSeparateProcesses = null;
1954                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1955            } else {
1956                mDefParseFlags = 0;
1957                mSeparateProcesses = separateProcesses.split(",");
1958                Slog.w(TAG, "Running with debug.separate_processes: "
1959                        + separateProcesses);
1960            }
1961        } else {
1962            mDefParseFlags = 0;
1963            mSeparateProcesses = null;
1964        }
1965
1966        mInstaller = installer;
1967        mPackageDexOptimizer = new PackageDexOptimizer(this);
1968        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1969
1970        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1971                FgThread.get().getLooper());
1972
1973        getDefaultDisplayMetrics(context, mMetrics);
1974
1975        SystemConfig systemConfig = SystemConfig.getInstance();
1976        mGlobalGids = systemConfig.getGlobalGids();
1977        mSystemPermissions = systemConfig.getSystemPermissions();
1978        mAvailableFeatures = systemConfig.getAvailableFeatures();
1979
1980        synchronized (mInstallLock) {
1981        // writer
1982        synchronized (mPackages) {
1983            mHandlerThread = new ServiceThread(TAG,
1984                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1985            mHandlerThread.start();
1986            mHandler = new PackageHandler(mHandlerThread.getLooper());
1987            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1988
1989            File dataDir = Environment.getDataDirectory();
1990            mAppDataDir = new File(dataDir, "data");
1991            mAppInstallDir = new File(dataDir, "app");
1992            mAppLib32InstallDir = new File(dataDir, "app-lib");
1993            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1994            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1995            mUserAppDataDir = new File(dataDir, "user");
1996            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1997
1998            sUserManager = new UserManagerService(context, this, mPackages);
1999
2000            // Propagate permission configuration in to package manager.
2001            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2002                    = systemConfig.getPermissions();
2003            for (int i=0; i<permConfig.size(); i++) {
2004                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2005                BasePermission bp = mSettings.mPermissions.get(perm.name);
2006                if (bp == null) {
2007                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2008                    mSettings.mPermissions.put(perm.name, bp);
2009                }
2010                if (perm.gids != null) {
2011                    bp.setGids(perm.gids, perm.perUser);
2012                }
2013            }
2014
2015            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2016            for (int i=0; i<libConfig.size(); i++) {
2017                mSharedLibraries.put(libConfig.keyAt(i),
2018                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2019            }
2020
2021            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2022
2023            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2024
2025            String customResolverActivity = Resources.getSystem().getString(
2026                    R.string.config_customResolverActivity);
2027            if (TextUtils.isEmpty(customResolverActivity)) {
2028                customResolverActivity = null;
2029            } else {
2030                mCustomResolverComponentName = ComponentName.unflattenFromString(
2031                        customResolverActivity);
2032            }
2033
2034            long startTime = SystemClock.uptimeMillis();
2035
2036            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2037                    startTime);
2038
2039            // Set flag to monitor and not change apk file paths when
2040            // scanning install directories.
2041            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2042
2043            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2044            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2045
2046            if (bootClassPath == null) {
2047                Slog.w(TAG, "No BOOTCLASSPATH found!");
2048            }
2049
2050            if (systemServerClassPath == null) {
2051                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2052            }
2053
2054            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2055            final String[] dexCodeInstructionSets =
2056                    getDexCodeInstructionSets(
2057                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2058
2059            /**
2060             * Ensure all external libraries have had dexopt run on them.
2061             */
2062            if (mSharedLibraries.size() > 0) {
2063                // NOTE: For now, we're compiling these system "shared libraries"
2064                // (and framework jars) into all available architectures. It's possible
2065                // to compile them only when we come across an app that uses them (there's
2066                // already logic for that in scanPackageLI) but that adds some complexity.
2067                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2068                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2069                        final String lib = libEntry.path;
2070                        if (lib == null) {
2071                            continue;
2072                        }
2073
2074                        try {
2075                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2076                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2077                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2078                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2079                            }
2080                        } catch (FileNotFoundException e) {
2081                            Slog.w(TAG, "Library not found: " + lib);
2082                        } catch (IOException e) {
2083                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2084                                    + e.getMessage());
2085                        }
2086                    }
2087                }
2088            }
2089
2090            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2091
2092            final VersionInfo ver = mSettings.getInternalVersion();
2093            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2094            // when upgrading from pre-M, promote system app permissions from install to runtime
2095            mPromoteSystemApps =
2096                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2097
2098            // save off the names of pre-existing system packages prior to scanning; we don't
2099            // want to automatically grant runtime permissions for new system apps
2100            if (mPromoteSystemApps) {
2101                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2102                while (pkgSettingIter.hasNext()) {
2103                    PackageSetting ps = pkgSettingIter.next();
2104                    if (isSystemApp(ps)) {
2105                        mExistingSystemPackages.add(ps.name);
2106                    }
2107                }
2108            }
2109
2110            // Collect vendor overlay packages.
2111            // (Do this before scanning any apps.)
2112            // For security and version matching reason, only consider
2113            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2114            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2115            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2116                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2117
2118            // Find base frameworks (resource packages without code).
2119            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2120                    | PackageParser.PARSE_IS_SYSTEM_DIR
2121                    | PackageParser.PARSE_IS_PRIVILEGED,
2122                    scanFlags | SCAN_NO_DEX, 0);
2123
2124            // Collected privileged system packages.
2125            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2126            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2127                    | PackageParser.PARSE_IS_SYSTEM_DIR
2128                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2129
2130            // Collect ordinary system packages.
2131            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2132            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2133                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2134
2135            // Collect all vendor packages.
2136            File vendorAppDir = new File("/vendor/app");
2137            try {
2138                vendorAppDir = vendorAppDir.getCanonicalFile();
2139            } catch (IOException e) {
2140                // failed to look up canonical path, continue with original one
2141            }
2142            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2143                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2144
2145            // Collect all OEM packages.
2146            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2147            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2148                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2149
2150            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2151            mInstaller.moveFiles();
2152
2153            // Prune any system packages that no longer exist.
2154            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2155            if (!mOnlyCore) {
2156                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2157                while (psit.hasNext()) {
2158                    PackageSetting ps = psit.next();
2159
2160                    /*
2161                     * If this is not a system app, it can't be a
2162                     * disable system app.
2163                     */
2164                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2165                        continue;
2166                    }
2167
2168                    /*
2169                     * If the package is scanned, it's not erased.
2170                     */
2171                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2172                    if (scannedPkg != null) {
2173                        /*
2174                         * If the system app is both scanned and in the
2175                         * disabled packages list, then it must have been
2176                         * added via OTA. Remove it from the currently
2177                         * scanned package so the previously user-installed
2178                         * application can be scanned.
2179                         */
2180                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2181                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2182                                    + ps.name + "; removing system app.  Last known codePath="
2183                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2184                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2185                                    + scannedPkg.mVersionCode);
2186                            removePackageLI(ps, true);
2187                            mExpectingBetter.put(ps.name, ps.codePath);
2188                        }
2189
2190                        continue;
2191                    }
2192
2193                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2194                        psit.remove();
2195                        logCriticalInfo(Log.WARN, "System package " + ps.name
2196                                + " no longer exists; wiping its data");
2197                        removeDataDirsLI(null, ps.name);
2198                    } else {
2199                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2200                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2201                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2202                        }
2203                    }
2204                }
2205            }
2206
2207            //look for any incomplete package installations
2208            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2209            //clean up list
2210            for(int i = 0; i < deletePkgsList.size(); i++) {
2211                //clean up here
2212                cleanupInstallFailedPackage(deletePkgsList.get(i));
2213            }
2214            //delete tmp files
2215            deleteTempPackageFiles();
2216
2217            // Remove any shared userIDs that have no associated packages
2218            mSettings.pruneSharedUsersLPw();
2219
2220            if (!mOnlyCore) {
2221                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2222                        SystemClock.uptimeMillis());
2223                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2224
2225                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2226                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2227
2228                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2229                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2230
2231                /**
2232                 * Remove disable package settings for any updated system
2233                 * apps that were removed via an OTA. If they're not a
2234                 * previously-updated app, remove them completely.
2235                 * Otherwise, just revoke their system-level permissions.
2236                 */
2237                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2238                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2239                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2240
2241                    String msg;
2242                    if (deletedPkg == null) {
2243                        msg = "Updated system package " + deletedAppName
2244                                + " no longer exists; wiping its data";
2245                        removeDataDirsLI(null, deletedAppName);
2246                    } else {
2247                        msg = "Updated system app + " + deletedAppName
2248                                + " no longer present; removing system privileges for "
2249                                + deletedAppName;
2250
2251                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2252
2253                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2254                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2255                    }
2256                    logCriticalInfo(Log.WARN, msg);
2257                }
2258
2259                /**
2260                 * Make sure all system apps that we expected to appear on
2261                 * the userdata partition actually showed up. If they never
2262                 * appeared, crawl back and revive the system version.
2263                 */
2264                for (int i = 0; i < mExpectingBetter.size(); i++) {
2265                    final String packageName = mExpectingBetter.keyAt(i);
2266                    if (!mPackages.containsKey(packageName)) {
2267                        final File scanFile = mExpectingBetter.valueAt(i);
2268
2269                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2270                                + " but never showed up; reverting to system");
2271
2272                        final int reparseFlags;
2273                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2274                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2275                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2276                                    | PackageParser.PARSE_IS_PRIVILEGED;
2277                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2278                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2279                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2280                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2281                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2282                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2283                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2284                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2285                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2286                        } else {
2287                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2288                            continue;
2289                        }
2290
2291                        mSettings.enableSystemPackageLPw(packageName);
2292
2293                        try {
2294                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2295                        } catch (PackageManagerException e) {
2296                            Slog.e(TAG, "Failed to parse original system package: "
2297                                    + e.getMessage());
2298                        }
2299                    }
2300                }
2301            }
2302            mExpectingBetter.clear();
2303
2304            // Now that we know all of the shared libraries, update all clients to have
2305            // the correct library paths.
2306            updateAllSharedLibrariesLPw();
2307
2308            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2309                // NOTE: We ignore potential failures here during a system scan (like
2310                // the rest of the commands above) because there's precious little we
2311                // can do about it. A settings error is reported, though.
2312                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2313                        false /* boot complete */);
2314            }
2315
2316            // Now that we know all the packages we are keeping,
2317            // read and update their last usage times.
2318            mPackageUsage.readLP();
2319
2320            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2321                    SystemClock.uptimeMillis());
2322            Slog.i(TAG, "Time to scan packages: "
2323                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2324                    + " seconds");
2325
2326            // If the platform SDK has changed since the last time we booted,
2327            // we need to re-grant app permission to catch any new ones that
2328            // appear.  This is really a hack, and means that apps can in some
2329            // cases get permissions that the user didn't initially explicitly
2330            // allow...  it would be nice to have some better way to handle
2331            // this situation.
2332            int updateFlags = UPDATE_PERMISSIONS_ALL;
2333            if (ver.sdkVersion != mSdkVersion) {
2334                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2335                        + mSdkVersion + "; regranting permissions for internal storage");
2336                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2337            }
2338            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2339            ver.sdkVersion = mSdkVersion;
2340
2341            // If this is the first boot or an update from pre-M, and it is a normal
2342            // boot, then we need to initialize the default preferred apps across
2343            // all defined users.
2344            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2345                for (UserInfo user : sUserManager.getUsers(true)) {
2346                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2347                    applyFactoryDefaultBrowserLPw(user.id);
2348                    primeDomainVerificationsLPw(user.id);
2349                }
2350            }
2351
2352            // If this is first boot after an OTA, and a normal boot, then
2353            // we need to clear code cache directories.
2354            if (mIsUpgrade && !onlyCore) {
2355                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2356                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2357                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2358                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2359                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2360                    }
2361                }
2362                ver.fingerprint = Build.FINGERPRINT;
2363            }
2364
2365            checkDefaultBrowser();
2366
2367            // clear only after permissions and other defaults have been updated
2368            mExistingSystemPackages.clear();
2369            mPromoteSystemApps = false;
2370
2371            // All the changes are done during package scanning.
2372            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2373
2374            // can downgrade to reader
2375            mSettings.writeLPr();
2376
2377            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2378                    SystemClock.uptimeMillis());
2379
2380            mRequiredVerifierPackage = getRequiredVerifierLPr();
2381            mRequiredInstallerPackage = getRequiredInstallerLPr();
2382
2383            mInstallerService = new PackageInstallerService(context, this);
2384
2385            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2386            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2387                    mIntentFilterVerifierComponent);
2388
2389            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2390            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2391            // both the installer and resolver must be present to enable ephemeral
2392            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2393                if (DEBUG_EPHEMERAL) {
2394                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2395                            + " installer:" + ephemeralInstallerComponent);
2396                }
2397                mEphemeralResolverComponent = ephemeralResolverComponent;
2398                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2399                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2400                mEphemeralResolverConnection =
2401                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2402            } else {
2403                if (DEBUG_EPHEMERAL) {
2404                    final String missingComponent =
2405                            (ephemeralResolverComponent == null)
2406                            ? (ephemeralInstallerComponent == null)
2407                                    ? "resolver and installer"
2408                                    : "resolver"
2409                            : "installer";
2410                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2411                }
2412                mEphemeralResolverComponent = null;
2413                mEphemeralInstallerComponent = null;
2414                mEphemeralResolverConnection = null;
2415            }
2416
2417            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2418        } // synchronized (mPackages)
2419        } // synchronized (mInstallLock)
2420
2421        // Now after opening every single application zip, make sure they
2422        // are all flushed.  Not really needed, but keeps things nice and
2423        // tidy.
2424        Runtime.getRuntime().gc();
2425
2426        // The initial scanning above does many calls into installd while
2427        // holding the mPackages lock, but we're mostly interested in yelling
2428        // once we have a booted system.
2429        mInstaller.setWarnIfHeld(mPackages);
2430
2431        // Expose private service for system components to use.
2432        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2433    }
2434
2435    @Override
2436    public boolean isFirstBoot() {
2437        return !mRestoredSettings;
2438    }
2439
2440    @Override
2441    public boolean isOnlyCoreApps() {
2442        return mOnlyCore;
2443    }
2444
2445    @Override
2446    public boolean isUpgrade() {
2447        return mIsUpgrade;
2448    }
2449
2450    private String getRequiredVerifierLPr() {
2451        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2452        // We only care about verifier that's installed under system user.
2453        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2454                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2455
2456        String requiredVerifier = null;
2457
2458        final int N = receivers.size();
2459        for (int i = 0; i < N; i++) {
2460            final ResolveInfo info = receivers.get(i);
2461
2462            if (info.activityInfo == null) {
2463                continue;
2464            }
2465
2466            final String packageName = info.activityInfo.packageName;
2467
2468            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2469                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2470                continue;
2471            }
2472
2473            if (requiredVerifier != null) {
2474                throw new RuntimeException("There can be only one required verifier");
2475            }
2476
2477            requiredVerifier = packageName;
2478        }
2479
2480        return requiredVerifier;
2481    }
2482
2483    private String getRequiredInstallerLPr() {
2484        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2485        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2486        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2487
2488        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2489                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2490
2491        String requiredInstaller = null;
2492
2493        final int N = installers.size();
2494        for (int i = 0; i < N; i++) {
2495            final ResolveInfo info = installers.get(i);
2496            final String packageName = info.activityInfo.packageName;
2497
2498            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2499                continue;
2500            }
2501
2502            if (requiredInstaller != null) {
2503                throw new RuntimeException("There must be one required installer");
2504            }
2505
2506            requiredInstaller = packageName;
2507        }
2508
2509        if (requiredInstaller == null) {
2510            throw new RuntimeException("There must be one required installer");
2511        }
2512
2513        return requiredInstaller;
2514    }
2515
2516    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2517        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2518        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2519                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2520
2521        ComponentName verifierComponentName = null;
2522
2523        int priority = -1000;
2524        final int N = receivers.size();
2525        for (int i = 0; i < N; i++) {
2526            final ResolveInfo info = receivers.get(i);
2527
2528            if (info.activityInfo == null) {
2529                continue;
2530            }
2531
2532            final String packageName = info.activityInfo.packageName;
2533
2534            final PackageSetting ps = mSettings.mPackages.get(packageName);
2535            if (ps == null) {
2536                continue;
2537            }
2538
2539            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2540                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2541                continue;
2542            }
2543
2544            // Select the IntentFilterVerifier with the highest priority
2545            if (priority < info.priority) {
2546                priority = info.priority;
2547                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2548                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2549                        + verifierComponentName + " with priority: " + info.priority);
2550            }
2551        }
2552
2553        return verifierComponentName;
2554    }
2555
2556    private ComponentName getEphemeralResolverLPr() {
2557        final String[] packageArray =
2558                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2559        if (packageArray.length == 0) {
2560            if (DEBUG_EPHEMERAL) {
2561                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2562            }
2563            return null;
2564        }
2565
2566        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2567        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2568                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2569
2570        final int N = resolvers.size();
2571        if (N == 0) {
2572            if (DEBUG_EPHEMERAL) {
2573                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2574            }
2575            return null;
2576        }
2577
2578        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2579        for (int i = 0; i < N; i++) {
2580            final ResolveInfo info = resolvers.get(i);
2581
2582            if (info.serviceInfo == null) {
2583                continue;
2584            }
2585
2586            final String packageName = info.serviceInfo.packageName;
2587            if (!possiblePackages.contains(packageName)) {
2588                if (DEBUG_EPHEMERAL) {
2589                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2590                            + " pkg: " + packageName + ", info:" + info);
2591                }
2592                continue;
2593            }
2594
2595            if (DEBUG_EPHEMERAL) {
2596                Slog.v(TAG, "Ephemeral resolver found;"
2597                        + " pkg: " + packageName + ", info:" + info);
2598            }
2599            return new ComponentName(packageName, info.serviceInfo.name);
2600        }
2601        if (DEBUG_EPHEMERAL) {
2602            Slog.v(TAG, "Ephemeral resolver NOT found");
2603        }
2604        return null;
2605    }
2606
2607    private ComponentName getEphemeralInstallerLPr() {
2608        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2609        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2610        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2611        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2612                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2613
2614        ComponentName ephemeralInstaller = null;
2615
2616        final int N = installers.size();
2617        for (int i = 0; i < N; i++) {
2618            final ResolveInfo info = installers.get(i);
2619            final String packageName = info.activityInfo.packageName;
2620
2621            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2622                if (DEBUG_EPHEMERAL) {
2623                    Slog.d(TAG, "Ephemeral installer is not system app;"
2624                            + " pkg: " + packageName + ", info:" + info);
2625                }
2626                continue;
2627            }
2628
2629            if (ephemeralInstaller != null) {
2630                throw new RuntimeException("There must only be one ephemeral installer");
2631            }
2632
2633            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2634        }
2635
2636        return ephemeralInstaller;
2637    }
2638
2639    private void primeDomainVerificationsLPw(int userId) {
2640        if (DEBUG_DOMAIN_VERIFICATION) {
2641            Slog.d(TAG, "Priming domain verifications in user " + userId);
2642        }
2643
2644        SystemConfig systemConfig = SystemConfig.getInstance();
2645        ArraySet<String> packages = systemConfig.getLinkedApps();
2646        ArraySet<String> domains = new ArraySet<String>();
2647
2648        for (String packageName : packages) {
2649            PackageParser.Package pkg = mPackages.get(packageName);
2650            if (pkg != null) {
2651                if (!pkg.isSystemApp()) {
2652                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2653                    continue;
2654                }
2655
2656                domains.clear();
2657                for (PackageParser.Activity a : pkg.activities) {
2658                    for (ActivityIntentInfo filter : a.intents) {
2659                        if (hasValidDomains(filter)) {
2660                            domains.addAll(filter.getHostsList());
2661                        }
2662                    }
2663                }
2664
2665                if (domains.size() > 0) {
2666                    if (DEBUG_DOMAIN_VERIFICATION) {
2667                        Slog.v(TAG, "      + " + packageName);
2668                    }
2669                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2670                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2671                    // and then 'always' in the per-user state actually used for intent resolution.
2672                    final IntentFilterVerificationInfo ivi;
2673                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2674                            new ArrayList<String>(domains));
2675                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2676                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2677                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2678                } else {
2679                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2680                            + "' does not handle web links");
2681                }
2682            } else {
2683                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2684            }
2685        }
2686
2687        scheduleWritePackageRestrictionsLocked(userId);
2688        scheduleWriteSettingsLocked();
2689    }
2690
2691    private void applyFactoryDefaultBrowserLPw(int userId) {
2692        // The default browser app's package name is stored in a string resource,
2693        // with a product-specific overlay used for vendor customization.
2694        String browserPkg = mContext.getResources().getString(
2695                com.android.internal.R.string.default_browser);
2696        if (!TextUtils.isEmpty(browserPkg)) {
2697            // non-empty string => required to be a known package
2698            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2699            if (ps == null) {
2700                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2701                browserPkg = null;
2702            } else {
2703                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2704            }
2705        }
2706
2707        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2708        // default.  If there's more than one, just leave everything alone.
2709        if (browserPkg == null) {
2710            calculateDefaultBrowserLPw(userId);
2711        }
2712    }
2713
2714    private void calculateDefaultBrowserLPw(int userId) {
2715        List<String> allBrowsers = resolveAllBrowserApps(userId);
2716        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2717        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2718    }
2719
2720    private List<String> resolveAllBrowserApps(int userId) {
2721        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2722        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2723                PackageManager.MATCH_ALL, userId);
2724
2725        final int count = list.size();
2726        List<String> result = new ArrayList<String>(count);
2727        for (int i=0; i<count; i++) {
2728            ResolveInfo info = list.get(i);
2729            if (info.activityInfo == null
2730                    || !info.handleAllWebDataURI
2731                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2732                    || result.contains(info.activityInfo.packageName)) {
2733                continue;
2734            }
2735            result.add(info.activityInfo.packageName);
2736        }
2737
2738        return result;
2739    }
2740
2741    private boolean packageIsBrowser(String packageName, int userId) {
2742        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2743                PackageManager.MATCH_ALL, userId);
2744        final int N = list.size();
2745        for (int i = 0; i < N; i++) {
2746            ResolveInfo info = list.get(i);
2747            if (packageName.equals(info.activityInfo.packageName)) {
2748                return true;
2749            }
2750        }
2751        return false;
2752    }
2753
2754    private void checkDefaultBrowser() {
2755        final int myUserId = UserHandle.myUserId();
2756        final String packageName = getDefaultBrowserPackageName(myUserId);
2757        if (packageName != null) {
2758            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2759            if (info == null) {
2760                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2761                synchronized (mPackages) {
2762                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2763                }
2764            }
2765        }
2766    }
2767
2768    @Override
2769    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2770            throws RemoteException {
2771        try {
2772            return super.onTransact(code, data, reply, flags);
2773        } catch (RuntimeException e) {
2774            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2775                Slog.wtf(TAG, "Package Manager Crash", e);
2776            }
2777            throw e;
2778        }
2779    }
2780
2781    void cleanupInstallFailedPackage(PackageSetting ps) {
2782        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2783
2784        removeDataDirsLI(ps.volumeUuid, ps.name);
2785        if (ps.codePath != null) {
2786            if (ps.codePath.isDirectory()) {
2787                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2788            } else {
2789                ps.codePath.delete();
2790            }
2791        }
2792        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2793            if (ps.resourcePath.isDirectory()) {
2794                FileUtils.deleteContents(ps.resourcePath);
2795            }
2796            ps.resourcePath.delete();
2797        }
2798        mSettings.removePackageLPw(ps.name);
2799    }
2800
2801    static int[] appendInts(int[] cur, int[] add) {
2802        if (add == null) return cur;
2803        if (cur == null) return add;
2804        final int N = add.length;
2805        for (int i=0; i<N; i++) {
2806            cur = appendInt(cur, add[i]);
2807        }
2808        return cur;
2809    }
2810
2811    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2812        if (!sUserManager.exists(userId)) return null;
2813        final PackageSetting ps = (PackageSetting) p.mExtras;
2814        if (ps == null) {
2815            return null;
2816        }
2817
2818        final PermissionsState permissionsState = ps.getPermissionsState();
2819
2820        final int[] gids = permissionsState.computeGids(userId);
2821        final Set<String> permissions = permissionsState.getPermissions(userId);
2822        final PackageUserState state = ps.readUserState(userId);
2823
2824        return PackageParser.generatePackageInfo(p, gids, flags,
2825                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2826    }
2827
2828    @Override
2829    public void checkPackageStartable(String packageName, int userId) {
2830        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2831
2832        synchronized (mPackages) {
2833            final PackageSetting ps = mSettings.mPackages.get(packageName);
2834            if (ps == null) {
2835                throw new SecurityException("Package " + packageName + " was not found!");
2836            }
2837
2838            if (ps.frozen) {
2839                throw new SecurityException("Package " + packageName + " is currently frozen!");
2840            }
2841
2842            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2843                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2844                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2845            }
2846        }
2847    }
2848
2849    @Override
2850    public boolean isPackageAvailable(String packageName, int userId) {
2851        if (!sUserManager.exists(userId)) return false;
2852        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2853        synchronized (mPackages) {
2854            PackageParser.Package p = mPackages.get(packageName);
2855            if (p != null) {
2856                final PackageSetting ps = (PackageSetting) p.mExtras;
2857                if (ps != null) {
2858                    final PackageUserState state = ps.readUserState(userId);
2859                    if (state != null) {
2860                        return PackageParser.isAvailable(state);
2861                    }
2862                }
2863            }
2864        }
2865        return false;
2866    }
2867
2868    @Override
2869    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2870        if (!sUserManager.exists(userId)) return null;
2871        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2872        // reader
2873        synchronized (mPackages) {
2874            PackageParser.Package p = mPackages.get(packageName);
2875            if (DEBUG_PACKAGE_INFO)
2876                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2877            if (p != null) {
2878                return generatePackageInfo(p, flags, userId);
2879            }
2880            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2881                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2882            }
2883        }
2884        return null;
2885    }
2886
2887    @Override
2888    public String[] currentToCanonicalPackageNames(String[] names) {
2889        String[] out = new String[names.length];
2890        // reader
2891        synchronized (mPackages) {
2892            for (int i=names.length-1; i>=0; i--) {
2893                PackageSetting ps = mSettings.mPackages.get(names[i]);
2894                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2895            }
2896        }
2897        return out;
2898    }
2899
2900    @Override
2901    public String[] canonicalToCurrentPackageNames(String[] names) {
2902        String[] out = new String[names.length];
2903        // reader
2904        synchronized (mPackages) {
2905            for (int i=names.length-1; i>=0; i--) {
2906                String cur = mSettings.mRenamedPackages.get(names[i]);
2907                out[i] = cur != null ? cur : names[i];
2908            }
2909        }
2910        return out;
2911    }
2912
2913    @Override
2914    public int getPackageUid(String packageName, int userId) {
2915        return getPackageUidEtc(packageName, 0, userId);
2916    }
2917
2918    @Override
2919    public int getPackageUidEtc(String packageName, int flags, int userId) {
2920        if (!sUserManager.exists(userId)) return -1;
2921        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2922
2923        // reader
2924        synchronized (mPackages) {
2925            final PackageParser.Package p = mPackages.get(packageName);
2926            if (p != null) {
2927                return UserHandle.getUid(userId, p.applicationInfo.uid);
2928            }
2929            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2930                final PackageSetting ps = mSettings.mPackages.get(packageName);
2931                if (ps != null) {
2932                    return UserHandle.getUid(userId, ps.appId);
2933                }
2934            }
2935        }
2936
2937        return -1;
2938    }
2939
2940    @Override
2941    public int[] getPackageGids(String packageName, int userId) {
2942        return getPackageGidsEtc(packageName, 0, userId);
2943    }
2944
2945    @Override
2946    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2947        if (!sUserManager.exists(userId)) {
2948            return null;
2949        }
2950
2951        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2952                "getPackageGids");
2953
2954        // reader
2955        synchronized (mPackages) {
2956            final PackageParser.Package p = mPackages.get(packageName);
2957            if (p != null) {
2958                PackageSetting ps = (PackageSetting) p.mExtras;
2959                return ps.getPermissionsState().computeGids(userId);
2960            }
2961            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2962                final PackageSetting ps = mSettings.mPackages.get(packageName);
2963                if (ps != null) {
2964                    return ps.getPermissionsState().computeGids(userId);
2965                }
2966            }
2967        }
2968
2969        return null;
2970    }
2971
2972    static PermissionInfo generatePermissionInfo(
2973            BasePermission bp, int flags) {
2974        if (bp.perm != null) {
2975            return PackageParser.generatePermissionInfo(bp.perm, flags);
2976        }
2977        PermissionInfo pi = new PermissionInfo();
2978        pi.name = bp.name;
2979        pi.packageName = bp.sourcePackage;
2980        pi.nonLocalizedLabel = bp.name;
2981        pi.protectionLevel = bp.protectionLevel;
2982        return pi;
2983    }
2984
2985    @Override
2986    public PermissionInfo getPermissionInfo(String name, int flags) {
2987        // reader
2988        synchronized (mPackages) {
2989            final BasePermission p = mSettings.mPermissions.get(name);
2990            if (p != null) {
2991                return generatePermissionInfo(p, flags);
2992            }
2993            return null;
2994        }
2995    }
2996
2997    @Override
2998    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2999        // reader
3000        synchronized (mPackages) {
3001            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3002            for (BasePermission p : mSettings.mPermissions.values()) {
3003                if (group == null) {
3004                    if (p.perm == null || p.perm.info.group == null) {
3005                        out.add(generatePermissionInfo(p, flags));
3006                    }
3007                } else {
3008                    if (p.perm != null && group.equals(p.perm.info.group)) {
3009                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3010                    }
3011                }
3012            }
3013
3014            if (out.size() > 0) {
3015                return out;
3016            }
3017            return mPermissionGroups.containsKey(group) ? out : null;
3018        }
3019    }
3020
3021    @Override
3022    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3023        // reader
3024        synchronized (mPackages) {
3025            return PackageParser.generatePermissionGroupInfo(
3026                    mPermissionGroups.get(name), flags);
3027        }
3028    }
3029
3030    @Override
3031    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3032        // reader
3033        synchronized (mPackages) {
3034            final int N = mPermissionGroups.size();
3035            ArrayList<PermissionGroupInfo> out
3036                    = new ArrayList<PermissionGroupInfo>(N);
3037            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3038                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3039            }
3040            return out;
3041        }
3042    }
3043
3044    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3045            int userId) {
3046        if (!sUserManager.exists(userId)) return null;
3047        PackageSetting ps = mSettings.mPackages.get(packageName);
3048        if (ps != null) {
3049            if (ps.pkg == null) {
3050                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3051                        flags, userId);
3052                if (pInfo != null) {
3053                    return pInfo.applicationInfo;
3054                }
3055                return null;
3056            }
3057            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3058                    ps.readUserState(userId), userId);
3059        }
3060        return null;
3061    }
3062
3063    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3064            int userId) {
3065        if (!sUserManager.exists(userId)) return null;
3066        PackageSetting ps = mSettings.mPackages.get(packageName);
3067        if (ps != null) {
3068            PackageParser.Package pkg = ps.pkg;
3069            if (pkg == null) {
3070                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3071                    return null;
3072                }
3073                // Only data remains, so we aren't worried about code paths
3074                pkg = new PackageParser.Package(packageName);
3075                pkg.applicationInfo.packageName = packageName;
3076                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3077                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3078                pkg.applicationInfo.uid = ps.appId;
3079                pkg.applicationInfo.initForUser(userId);
3080                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3081                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3082            }
3083            return generatePackageInfo(pkg, flags, userId);
3084        }
3085        return null;
3086    }
3087
3088    @Override
3089    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3090        if (!sUserManager.exists(userId)) return null;
3091        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3092        // writer
3093        synchronized (mPackages) {
3094            PackageParser.Package p = mPackages.get(packageName);
3095            if (DEBUG_PACKAGE_INFO) Log.v(
3096                    TAG, "getApplicationInfo " + packageName
3097                    + ": " + p);
3098            if (p != null) {
3099                PackageSetting ps = mSettings.mPackages.get(packageName);
3100                if (ps == null) return null;
3101                // Note: isEnabledLP() does not apply here - always return info
3102                return PackageParser.generateApplicationInfo(
3103                        p, flags, ps.readUserState(userId), userId);
3104            }
3105            if ("android".equals(packageName)||"system".equals(packageName)) {
3106                return mAndroidApplication;
3107            }
3108            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3109                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3110            }
3111        }
3112        return null;
3113    }
3114
3115    @Override
3116    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3117            final IPackageDataObserver observer) {
3118        mContext.enforceCallingOrSelfPermission(
3119                android.Manifest.permission.CLEAR_APP_CACHE, null);
3120        // Queue up an async operation since clearing cache may take a little while.
3121        mHandler.post(new Runnable() {
3122            public void run() {
3123                mHandler.removeCallbacks(this);
3124                int retCode = -1;
3125                synchronized (mInstallLock) {
3126                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3127                    if (retCode < 0) {
3128                        Slog.w(TAG, "Couldn't clear application caches");
3129                    }
3130                }
3131                if (observer != null) {
3132                    try {
3133                        observer.onRemoveCompleted(null, (retCode >= 0));
3134                    } catch (RemoteException e) {
3135                        Slog.w(TAG, "RemoveException when invoking call back");
3136                    }
3137                }
3138            }
3139        });
3140    }
3141
3142    @Override
3143    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3144            final IntentSender pi) {
3145        mContext.enforceCallingOrSelfPermission(
3146                android.Manifest.permission.CLEAR_APP_CACHE, null);
3147        // Queue up an async operation since clearing cache may take a little while.
3148        mHandler.post(new Runnable() {
3149            public void run() {
3150                mHandler.removeCallbacks(this);
3151                int retCode = -1;
3152                synchronized (mInstallLock) {
3153                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3154                    if (retCode < 0) {
3155                        Slog.w(TAG, "Couldn't clear application caches");
3156                    }
3157                }
3158                if(pi != null) {
3159                    try {
3160                        // Callback via pending intent
3161                        int code = (retCode >= 0) ? 1 : 0;
3162                        pi.sendIntent(null, code, null,
3163                                null, null);
3164                    } catch (SendIntentException e1) {
3165                        Slog.i(TAG, "Failed to send pending intent");
3166                    }
3167                }
3168            }
3169        });
3170    }
3171
3172    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3173        synchronized (mInstallLock) {
3174            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3175                throw new IOException("Failed to free enough space");
3176            }
3177        }
3178    }
3179
3180    /**
3181     * Return if the user key is currently unlocked.
3182     */
3183    private boolean isUserKeyUnlocked(int userId) {
3184        if (StorageManager.isFileBasedEncryptionEnabled()) {
3185            final IMountService mount = IMountService.Stub
3186                    .asInterface(ServiceManager.getService("mount"));
3187            if (mount == null) {
3188                Slog.w(TAG, "Early during boot, assuming locked");
3189                return false;
3190            }
3191            final long token = Binder.clearCallingIdentity();
3192            try {
3193                return mount.isUserKeyUnlocked(userId);
3194            } catch (RemoteException e) {
3195                throw e.rethrowAsRuntimeException();
3196            } finally {
3197                Binder.restoreCallingIdentity(token);
3198            }
3199        } else {
3200            return true;
3201        }
3202    }
3203
3204    /**
3205     * Augment the given flags depending on current user running state. This is
3206     * purposefully done before acquiring {@link #mPackages} lock.
3207     */
3208    private int augmentFlagsForUser(int flags, int userId) {
3209        if (!isUserKeyUnlocked(userId)) {
3210            flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3211        }
3212        return flags;
3213    }
3214
3215    @Override
3216    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3217        if (!sUserManager.exists(userId)) return null;
3218        flags = augmentFlagsForUser(flags, userId);
3219        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3220        synchronized (mPackages) {
3221            PackageParser.Activity a = mActivities.mActivities.get(component);
3222
3223            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3224            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3225                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3226                if (ps == null) return null;
3227                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3228                        userId);
3229            }
3230            if (mResolveComponentName.equals(component)) {
3231                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3232                        new PackageUserState(), userId);
3233            }
3234        }
3235        return null;
3236    }
3237
3238    @Override
3239    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3240            String resolvedType) {
3241        synchronized (mPackages) {
3242            if (component.equals(mResolveComponentName)) {
3243                // The resolver supports EVERYTHING!
3244                return true;
3245            }
3246            PackageParser.Activity a = mActivities.mActivities.get(component);
3247            if (a == null) {
3248                return false;
3249            }
3250            for (int i=0; i<a.intents.size(); i++) {
3251                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3252                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3253                    return true;
3254                }
3255            }
3256            return false;
3257        }
3258    }
3259
3260    @Override
3261    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3262        if (!sUserManager.exists(userId)) return null;
3263        flags = augmentFlagsForUser(flags, userId);
3264        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3265        synchronized (mPackages) {
3266            PackageParser.Activity a = mReceivers.mActivities.get(component);
3267            if (DEBUG_PACKAGE_INFO) Log.v(
3268                TAG, "getReceiverInfo " + component + ": " + a);
3269            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3270                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3271                if (ps == null) return null;
3272                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3273                        userId);
3274            }
3275        }
3276        return null;
3277    }
3278
3279    @Override
3280    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3281        if (!sUserManager.exists(userId)) return null;
3282        flags = augmentFlagsForUser(flags, userId);
3283        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3284        synchronized (mPackages) {
3285            PackageParser.Service s = mServices.mServices.get(component);
3286            if (DEBUG_PACKAGE_INFO) Log.v(
3287                TAG, "getServiceInfo " + component + ": " + s);
3288            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3289                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3290                if (ps == null) return null;
3291                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3292                        userId);
3293            }
3294        }
3295        return null;
3296    }
3297
3298    @Override
3299    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3300        if (!sUserManager.exists(userId)) return null;
3301        flags = augmentFlagsForUser(flags, userId);
3302        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3303        synchronized (mPackages) {
3304            PackageParser.Provider p = mProviders.mProviders.get(component);
3305            if (DEBUG_PACKAGE_INFO) Log.v(
3306                TAG, "getProviderInfo " + component + ": " + p);
3307            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3308                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3309                if (ps == null) return null;
3310                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3311                        userId);
3312            }
3313        }
3314        return null;
3315    }
3316
3317    @Override
3318    public String[] getSystemSharedLibraryNames() {
3319        Set<String> libSet;
3320        synchronized (mPackages) {
3321            libSet = mSharedLibraries.keySet();
3322            int size = libSet.size();
3323            if (size > 0) {
3324                String[] libs = new String[size];
3325                libSet.toArray(libs);
3326                return libs;
3327            }
3328        }
3329        return null;
3330    }
3331
3332    /**
3333     * @hide
3334     */
3335    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3336        synchronized (mPackages) {
3337            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3338            if (lib != null && lib.apk != null) {
3339                return mPackages.get(lib.apk);
3340            }
3341        }
3342        return null;
3343    }
3344
3345    @Override
3346    public FeatureInfo[] getSystemAvailableFeatures() {
3347        Collection<FeatureInfo> featSet;
3348        synchronized (mPackages) {
3349            featSet = mAvailableFeatures.values();
3350            int size = featSet.size();
3351            if (size > 0) {
3352                FeatureInfo[] features = new FeatureInfo[size+1];
3353                featSet.toArray(features);
3354                FeatureInfo fi = new FeatureInfo();
3355                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3356                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3357                features[size] = fi;
3358                return features;
3359            }
3360        }
3361        return null;
3362    }
3363
3364    @Override
3365    public boolean hasSystemFeature(String name) {
3366        synchronized (mPackages) {
3367            return mAvailableFeatures.containsKey(name);
3368        }
3369    }
3370
3371    private void checkValidCaller(int uid, int userId) {
3372        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3373            return;
3374
3375        throw new SecurityException("Caller uid=" + uid
3376                + " is not privileged to communicate with user=" + userId);
3377    }
3378
3379    @Override
3380    public int checkPermission(String permName, String pkgName, int userId) {
3381        if (!sUserManager.exists(userId)) {
3382            return PackageManager.PERMISSION_DENIED;
3383        }
3384
3385        synchronized (mPackages) {
3386            final PackageParser.Package p = mPackages.get(pkgName);
3387            if (p != null && p.mExtras != null) {
3388                final PackageSetting ps = (PackageSetting) p.mExtras;
3389                final PermissionsState permissionsState = ps.getPermissionsState();
3390                if (permissionsState.hasPermission(permName, userId)) {
3391                    return PackageManager.PERMISSION_GRANTED;
3392                }
3393                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3394                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3395                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3396                    return PackageManager.PERMISSION_GRANTED;
3397                }
3398            }
3399        }
3400
3401        return PackageManager.PERMISSION_DENIED;
3402    }
3403
3404    @Override
3405    public int checkUidPermission(String permName, int uid) {
3406        final int userId = UserHandle.getUserId(uid);
3407
3408        if (!sUserManager.exists(userId)) {
3409            return PackageManager.PERMISSION_DENIED;
3410        }
3411
3412        synchronized (mPackages) {
3413            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3414            if (obj != null) {
3415                final SettingBase ps = (SettingBase) obj;
3416                final PermissionsState permissionsState = ps.getPermissionsState();
3417                if (permissionsState.hasPermission(permName, userId)) {
3418                    return PackageManager.PERMISSION_GRANTED;
3419                }
3420                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3421                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3422                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3423                    return PackageManager.PERMISSION_GRANTED;
3424                }
3425            } else {
3426                ArraySet<String> perms = mSystemPermissions.get(uid);
3427                if (perms != null) {
3428                    if (perms.contains(permName)) {
3429                        return PackageManager.PERMISSION_GRANTED;
3430                    }
3431                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3432                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3433                        return PackageManager.PERMISSION_GRANTED;
3434                    }
3435                }
3436            }
3437        }
3438
3439        return PackageManager.PERMISSION_DENIED;
3440    }
3441
3442    @Override
3443    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3444        if (UserHandle.getCallingUserId() != userId) {
3445            mContext.enforceCallingPermission(
3446                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3447                    "isPermissionRevokedByPolicy for user " + userId);
3448        }
3449
3450        if (checkPermission(permission, packageName, userId)
3451                == PackageManager.PERMISSION_GRANTED) {
3452            return false;
3453        }
3454
3455        final long identity = Binder.clearCallingIdentity();
3456        try {
3457            final int flags = getPermissionFlags(permission, packageName, userId);
3458            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3459        } finally {
3460            Binder.restoreCallingIdentity(identity);
3461        }
3462    }
3463
3464    @Override
3465    public String getPermissionControllerPackageName() {
3466        synchronized (mPackages) {
3467            return mRequiredInstallerPackage;
3468        }
3469    }
3470
3471    /**
3472     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3473     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3474     * @param checkShell TODO(yamasani):
3475     * @param message the message to log on security exception
3476     */
3477    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3478            boolean checkShell, String message) {
3479        if (userId < 0) {
3480            throw new IllegalArgumentException("Invalid userId " + userId);
3481        }
3482        if (checkShell) {
3483            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3484        }
3485        if (userId == UserHandle.getUserId(callingUid)) return;
3486        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3487            if (requireFullPermission) {
3488                mContext.enforceCallingOrSelfPermission(
3489                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3490            } else {
3491                try {
3492                    mContext.enforceCallingOrSelfPermission(
3493                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3494                } catch (SecurityException se) {
3495                    mContext.enforceCallingOrSelfPermission(
3496                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3497                }
3498            }
3499        }
3500    }
3501
3502    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3503        if (callingUid == Process.SHELL_UID) {
3504            if (userHandle >= 0
3505                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3506                throw new SecurityException("Shell does not have permission to access user "
3507                        + userHandle);
3508            } else if (userHandle < 0) {
3509                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3510                        + Debug.getCallers(3));
3511            }
3512        }
3513    }
3514
3515    private BasePermission findPermissionTreeLP(String permName) {
3516        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3517            if (permName.startsWith(bp.name) &&
3518                    permName.length() > bp.name.length() &&
3519                    permName.charAt(bp.name.length()) == '.') {
3520                return bp;
3521            }
3522        }
3523        return null;
3524    }
3525
3526    private BasePermission checkPermissionTreeLP(String permName) {
3527        if (permName != null) {
3528            BasePermission bp = findPermissionTreeLP(permName);
3529            if (bp != null) {
3530                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3531                    return bp;
3532                }
3533                throw new SecurityException("Calling uid "
3534                        + Binder.getCallingUid()
3535                        + " is not allowed to add to permission tree "
3536                        + bp.name + " owned by uid " + bp.uid);
3537            }
3538        }
3539        throw new SecurityException("No permission tree found for " + permName);
3540    }
3541
3542    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3543        if (s1 == null) {
3544            return s2 == null;
3545        }
3546        if (s2 == null) {
3547            return false;
3548        }
3549        if (s1.getClass() != s2.getClass()) {
3550            return false;
3551        }
3552        return s1.equals(s2);
3553    }
3554
3555    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3556        if (pi1.icon != pi2.icon) return false;
3557        if (pi1.logo != pi2.logo) return false;
3558        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3559        if (!compareStrings(pi1.name, pi2.name)) return false;
3560        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3561        // We'll take care of setting this one.
3562        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3563        // These are not currently stored in settings.
3564        //if (!compareStrings(pi1.group, pi2.group)) return false;
3565        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3566        //if (pi1.labelRes != pi2.labelRes) return false;
3567        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3568        return true;
3569    }
3570
3571    int permissionInfoFootprint(PermissionInfo info) {
3572        int size = info.name.length();
3573        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3574        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3575        return size;
3576    }
3577
3578    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3579        int size = 0;
3580        for (BasePermission perm : mSettings.mPermissions.values()) {
3581            if (perm.uid == tree.uid) {
3582                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3583            }
3584        }
3585        return size;
3586    }
3587
3588    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3589        // We calculate the max size of permissions defined by this uid and throw
3590        // if that plus the size of 'info' would exceed our stated maximum.
3591        if (tree.uid != Process.SYSTEM_UID) {
3592            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3593            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3594                throw new SecurityException("Permission tree size cap exceeded");
3595            }
3596        }
3597    }
3598
3599    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3600        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3601            throw new SecurityException("Label must be specified in permission");
3602        }
3603        BasePermission tree = checkPermissionTreeLP(info.name);
3604        BasePermission bp = mSettings.mPermissions.get(info.name);
3605        boolean added = bp == null;
3606        boolean changed = true;
3607        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3608        if (added) {
3609            enforcePermissionCapLocked(info, tree);
3610            bp = new BasePermission(info.name, tree.sourcePackage,
3611                    BasePermission.TYPE_DYNAMIC);
3612        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3613            throw new SecurityException(
3614                    "Not allowed to modify non-dynamic permission "
3615                    + info.name);
3616        } else {
3617            if (bp.protectionLevel == fixedLevel
3618                    && bp.perm.owner.equals(tree.perm.owner)
3619                    && bp.uid == tree.uid
3620                    && comparePermissionInfos(bp.perm.info, info)) {
3621                changed = false;
3622            }
3623        }
3624        bp.protectionLevel = fixedLevel;
3625        info = new PermissionInfo(info);
3626        info.protectionLevel = fixedLevel;
3627        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3628        bp.perm.info.packageName = tree.perm.info.packageName;
3629        bp.uid = tree.uid;
3630        if (added) {
3631            mSettings.mPermissions.put(info.name, bp);
3632        }
3633        if (changed) {
3634            if (!async) {
3635                mSettings.writeLPr();
3636            } else {
3637                scheduleWriteSettingsLocked();
3638            }
3639        }
3640        return added;
3641    }
3642
3643    @Override
3644    public boolean addPermission(PermissionInfo info) {
3645        synchronized (mPackages) {
3646            return addPermissionLocked(info, false);
3647        }
3648    }
3649
3650    @Override
3651    public boolean addPermissionAsync(PermissionInfo info) {
3652        synchronized (mPackages) {
3653            return addPermissionLocked(info, true);
3654        }
3655    }
3656
3657    @Override
3658    public void removePermission(String name) {
3659        synchronized (mPackages) {
3660            checkPermissionTreeLP(name);
3661            BasePermission bp = mSettings.mPermissions.get(name);
3662            if (bp != null) {
3663                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3664                    throw new SecurityException(
3665                            "Not allowed to modify non-dynamic permission "
3666                            + name);
3667                }
3668                mSettings.mPermissions.remove(name);
3669                mSettings.writeLPr();
3670            }
3671        }
3672    }
3673
3674    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3675            BasePermission bp) {
3676        int index = pkg.requestedPermissions.indexOf(bp.name);
3677        if (index == -1) {
3678            throw new SecurityException("Package " + pkg.packageName
3679                    + " has not requested permission " + bp.name);
3680        }
3681        if (!bp.isRuntime() && !bp.isDevelopment()) {
3682            throw new SecurityException("Permission " + bp.name
3683                    + " is not a changeable permission type");
3684        }
3685    }
3686
3687    @Override
3688    public void grantRuntimePermission(String packageName, String name, final int userId) {
3689        if (!sUserManager.exists(userId)) {
3690            Log.e(TAG, "No such user:" + userId);
3691            return;
3692        }
3693
3694        mContext.enforceCallingOrSelfPermission(
3695                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3696                "grantRuntimePermission");
3697
3698        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3699                "grantRuntimePermission");
3700
3701        final int uid;
3702        final SettingBase sb;
3703
3704        synchronized (mPackages) {
3705            final PackageParser.Package pkg = mPackages.get(packageName);
3706            if (pkg == null) {
3707                throw new IllegalArgumentException("Unknown package: " + packageName);
3708            }
3709
3710            final BasePermission bp = mSettings.mPermissions.get(name);
3711            if (bp == null) {
3712                throw new IllegalArgumentException("Unknown permission: " + name);
3713            }
3714
3715            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3716
3717            // If a permission review is required for legacy apps we represent
3718            // their permissions as always granted runtime ones since we need
3719            // to keep the review required permission flag per user while an
3720            // install permission's state is shared across all users.
3721            if (Build.PERMISSIONS_REVIEW_REQUIRED
3722                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3723                    && bp.isRuntime()) {
3724                return;
3725            }
3726
3727            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3728            sb = (SettingBase) pkg.mExtras;
3729            if (sb == null) {
3730                throw new IllegalArgumentException("Unknown package: " + packageName);
3731            }
3732
3733            final PermissionsState permissionsState = sb.getPermissionsState();
3734
3735            final int flags = permissionsState.getPermissionFlags(name, userId);
3736            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3737                throw new SecurityException("Cannot grant system fixed permission: "
3738                        + name + " for package: " + packageName);
3739            }
3740
3741            if (bp.isDevelopment()) {
3742                // Development permissions must be handled specially, since they are not
3743                // normal runtime permissions.  For now they apply to all users.
3744                if (permissionsState.grantInstallPermission(bp) !=
3745                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3746                    scheduleWriteSettingsLocked();
3747                }
3748                return;
3749            }
3750
3751            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3752                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3753                return;
3754            }
3755
3756            final int result = permissionsState.grantRuntimePermission(bp, userId);
3757            switch (result) {
3758                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3759                    return;
3760                }
3761
3762                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3763                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3764                    mHandler.post(new Runnable() {
3765                        @Override
3766                        public void run() {
3767                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3768                        }
3769                    });
3770                }
3771                break;
3772            }
3773
3774            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3775
3776            // Not critical if that is lost - app has to request again.
3777            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3778        }
3779
3780        // Only need to do this if user is initialized. Otherwise it's a new user
3781        // and there are no processes running as the user yet and there's no need
3782        // to make an expensive call to remount processes for the changed permissions.
3783        if (READ_EXTERNAL_STORAGE.equals(name)
3784                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3785            final long token = Binder.clearCallingIdentity();
3786            try {
3787                if (sUserManager.isInitialized(userId)) {
3788                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3789                            MountServiceInternal.class);
3790                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3791                }
3792            } finally {
3793                Binder.restoreCallingIdentity(token);
3794            }
3795        }
3796    }
3797
3798    @Override
3799    public void revokeRuntimePermission(String packageName, String name, int userId) {
3800        if (!sUserManager.exists(userId)) {
3801            Log.e(TAG, "No such user:" + userId);
3802            return;
3803        }
3804
3805        mContext.enforceCallingOrSelfPermission(
3806                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3807                "revokeRuntimePermission");
3808
3809        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3810                "revokeRuntimePermission");
3811
3812        final int appId;
3813
3814        synchronized (mPackages) {
3815            final PackageParser.Package pkg = mPackages.get(packageName);
3816            if (pkg == null) {
3817                throw new IllegalArgumentException("Unknown package: " + packageName);
3818            }
3819
3820            final BasePermission bp = mSettings.mPermissions.get(name);
3821            if (bp == null) {
3822                throw new IllegalArgumentException("Unknown permission: " + name);
3823            }
3824
3825            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3826
3827            // If a permission review is required for legacy apps we represent
3828            // their permissions as always granted runtime ones since we need
3829            // to keep the review required permission flag per user while an
3830            // install permission's state is shared across all users.
3831            if (Build.PERMISSIONS_REVIEW_REQUIRED
3832                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3833                    && bp.isRuntime()) {
3834                return;
3835            }
3836
3837            SettingBase sb = (SettingBase) pkg.mExtras;
3838            if (sb == null) {
3839                throw new IllegalArgumentException("Unknown package: " + packageName);
3840            }
3841
3842            final PermissionsState permissionsState = sb.getPermissionsState();
3843
3844            final int flags = permissionsState.getPermissionFlags(name, userId);
3845            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3846                throw new SecurityException("Cannot revoke system fixed permission: "
3847                        + name + " for package: " + packageName);
3848            }
3849
3850            if (bp.isDevelopment()) {
3851                // Development permissions must be handled specially, since they are not
3852                // normal runtime permissions.  For now they apply to all users.
3853                if (permissionsState.revokeInstallPermission(bp) !=
3854                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3855                    scheduleWriteSettingsLocked();
3856                }
3857                return;
3858            }
3859
3860            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3861                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3862                return;
3863            }
3864
3865            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3866
3867            // Critical, after this call app should never have the permission.
3868            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3869
3870            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3871        }
3872
3873        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3874    }
3875
3876    @Override
3877    public void resetRuntimePermissions() {
3878        mContext.enforceCallingOrSelfPermission(
3879                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3880                "revokeRuntimePermission");
3881
3882        int callingUid = Binder.getCallingUid();
3883        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3884            mContext.enforceCallingOrSelfPermission(
3885                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3886                    "resetRuntimePermissions");
3887        }
3888
3889        synchronized (mPackages) {
3890            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3891            for (int userId : UserManagerService.getInstance().getUserIds()) {
3892                final int packageCount = mPackages.size();
3893                for (int i = 0; i < packageCount; i++) {
3894                    PackageParser.Package pkg = mPackages.valueAt(i);
3895                    if (!(pkg.mExtras instanceof PackageSetting)) {
3896                        continue;
3897                    }
3898                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3899                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3900                }
3901            }
3902        }
3903    }
3904
3905    @Override
3906    public int getPermissionFlags(String name, String packageName, int userId) {
3907        if (!sUserManager.exists(userId)) {
3908            return 0;
3909        }
3910
3911        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3912
3913        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3914                "getPermissionFlags");
3915
3916        synchronized (mPackages) {
3917            final PackageParser.Package pkg = mPackages.get(packageName);
3918            if (pkg == null) {
3919                throw new IllegalArgumentException("Unknown package: " + packageName);
3920            }
3921
3922            final BasePermission bp = mSettings.mPermissions.get(name);
3923            if (bp == null) {
3924                throw new IllegalArgumentException("Unknown permission: " + name);
3925            }
3926
3927            SettingBase sb = (SettingBase) pkg.mExtras;
3928            if (sb == null) {
3929                throw new IllegalArgumentException("Unknown package: " + packageName);
3930            }
3931
3932            PermissionsState permissionsState = sb.getPermissionsState();
3933            return permissionsState.getPermissionFlags(name, userId);
3934        }
3935    }
3936
3937    @Override
3938    public void updatePermissionFlags(String name, String packageName, int flagMask,
3939            int flagValues, int userId) {
3940        if (!sUserManager.exists(userId)) {
3941            return;
3942        }
3943
3944        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3945
3946        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3947                "updatePermissionFlags");
3948
3949        // Only the system can change these flags and nothing else.
3950        if (getCallingUid() != Process.SYSTEM_UID) {
3951            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3952            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3953            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3954            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3955            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3956        }
3957
3958        synchronized (mPackages) {
3959            final PackageParser.Package pkg = mPackages.get(packageName);
3960            if (pkg == null) {
3961                throw new IllegalArgumentException("Unknown package: " + packageName);
3962            }
3963
3964            final BasePermission bp = mSettings.mPermissions.get(name);
3965            if (bp == null) {
3966                throw new IllegalArgumentException("Unknown permission: " + name);
3967            }
3968
3969            SettingBase sb = (SettingBase) pkg.mExtras;
3970            if (sb == null) {
3971                throw new IllegalArgumentException("Unknown package: " + packageName);
3972            }
3973
3974            PermissionsState permissionsState = sb.getPermissionsState();
3975
3976            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3977
3978            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3979                // Install and runtime permissions are stored in different places,
3980                // so figure out what permission changed and persist the change.
3981                if (permissionsState.getInstallPermissionState(name) != null) {
3982                    scheduleWriteSettingsLocked();
3983                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3984                        || hadState) {
3985                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3986                }
3987            }
3988        }
3989    }
3990
3991    /**
3992     * Update the permission flags for all packages and runtime permissions of a user in order
3993     * to allow device or profile owner to remove POLICY_FIXED.
3994     */
3995    @Override
3996    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3997        if (!sUserManager.exists(userId)) {
3998            return;
3999        }
4000
4001        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4002
4003        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4004                "updatePermissionFlagsForAllApps");
4005
4006        // Only the system can change system fixed flags.
4007        if (getCallingUid() != Process.SYSTEM_UID) {
4008            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4009            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4010        }
4011
4012        synchronized (mPackages) {
4013            boolean changed = false;
4014            final int packageCount = mPackages.size();
4015            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4016                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4017                SettingBase sb = (SettingBase) pkg.mExtras;
4018                if (sb == null) {
4019                    continue;
4020                }
4021                PermissionsState permissionsState = sb.getPermissionsState();
4022                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4023                        userId, flagMask, flagValues);
4024            }
4025            if (changed) {
4026                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4027            }
4028        }
4029    }
4030
4031    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4032        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4033                != PackageManager.PERMISSION_GRANTED
4034            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4035                != PackageManager.PERMISSION_GRANTED) {
4036            throw new SecurityException(message + " requires "
4037                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4038                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4039        }
4040    }
4041
4042    @Override
4043    public boolean shouldShowRequestPermissionRationale(String permissionName,
4044            String packageName, int userId) {
4045        if (UserHandle.getCallingUserId() != userId) {
4046            mContext.enforceCallingPermission(
4047                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4048                    "canShowRequestPermissionRationale for user " + userId);
4049        }
4050
4051        final int uid = getPackageUid(packageName, userId);
4052        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4053            return false;
4054        }
4055
4056        if (checkPermission(permissionName, packageName, userId)
4057                == PackageManager.PERMISSION_GRANTED) {
4058            return false;
4059        }
4060
4061        final int flags;
4062
4063        final long identity = Binder.clearCallingIdentity();
4064        try {
4065            flags = getPermissionFlags(permissionName,
4066                    packageName, userId);
4067        } finally {
4068            Binder.restoreCallingIdentity(identity);
4069        }
4070
4071        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4072                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4073                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4074
4075        if ((flags & fixedFlags) != 0) {
4076            return false;
4077        }
4078
4079        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4080    }
4081
4082    @Override
4083    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4084        mContext.enforceCallingOrSelfPermission(
4085                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4086                "addOnPermissionsChangeListener");
4087
4088        synchronized (mPackages) {
4089            mOnPermissionChangeListeners.addListenerLocked(listener);
4090        }
4091    }
4092
4093    @Override
4094    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4095        synchronized (mPackages) {
4096            mOnPermissionChangeListeners.removeListenerLocked(listener);
4097        }
4098    }
4099
4100    @Override
4101    public boolean isProtectedBroadcast(String actionName) {
4102        synchronized (mPackages) {
4103            if (mProtectedBroadcasts.contains(actionName)) {
4104                return true;
4105            } else if (actionName != null
4106                    && actionName.startsWith("android.net.netmon.lingerExpired")) {
4107                // TODO: remove this terrible hack
4108                return true;
4109            }
4110        }
4111        return false;
4112    }
4113
4114    @Override
4115    public int checkSignatures(String pkg1, String pkg2) {
4116        synchronized (mPackages) {
4117            final PackageParser.Package p1 = mPackages.get(pkg1);
4118            final PackageParser.Package p2 = mPackages.get(pkg2);
4119            if (p1 == null || p1.mExtras == null
4120                    || p2 == null || p2.mExtras == null) {
4121                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4122            }
4123            return compareSignatures(p1.mSignatures, p2.mSignatures);
4124        }
4125    }
4126
4127    @Override
4128    public int checkUidSignatures(int uid1, int uid2) {
4129        // Map to base uids.
4130        uid1 = UserHandle.getAppId(uid1);
4131        uid2 = UserHandle.getAppId(uid2);
4132        // reader
4133        synchronized (mPackages) {
4134            Signature[] s1;
4135            Signature[] s2;
4136            Object obj = mSettings.getUserIdLPr(uid1);
4137            if (obj != null) {
4138                if (obj instanceof SharedUserSetting) {
4139                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4140                } else if (obj instanceof PackageSetting) {
4141                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4142                } else {
4143                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4144                }
4145            } else {
4146                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4147            }
4148            obj = mSettings.getUserIdLPr(uid2);
4149            if (obj != null) {
4150                if (obj instanceof SharedUserSetting) {
4151                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4152                } else if (obj instanceof PackageSetting) {
4153                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4154                } else {
4155                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4156                }
4157            } else {
4158                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4159            }
4160            return compareSignatures(s1, s2);
4161        }
4162    }
4163
4164    private void killUid(int appId, int userId, String reason) {
4165        final long identity = Binder.clearCallingIdentity();
4166        try {
4167            IActivityManager am = ActivityManagerNative.getDefault();
4168            if (am != null) {
4169                try {
4170                    am.killUid(appId, userId, reason);
4171                } catch (RemoteException e) {
4172                    /* ignore - same process */
4173                }
4174            }
4175        } finally {
4176            Binder.restoreCallingIdentity(identity);
4177        }
4178    }
4179
4180    /**
4181     * Compares two sets of signatures. Returns:
4182     * <br />
4183     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4184     * <br />
4185     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4186     * <br />
4187     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4188     * <br />
4189     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4190     * <br />
4191     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4192     */
4193    static int compareSignatures(Signature[] s1, Signature[] s2) {
4194        if (s1 == null) {
4195            return s2 == null
4196                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4197                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4198        }
4199
4200        if (s2 == null) {
4201            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4202        }
4203
4204        if (s1.length != s2.length) {
4205            return PackageManager.SIGNATURE_NO_MATCH;
4206        }
4207
4208        // Since both signature sets are of size 1, we can compare without HashSets.
4209        if (s1.length == 1) {
4210            return s1[0].equals(s2[0]) ?
4211                    PackageManager.SIGNATURE_MATCH :
4212                    PackageManager.SIGNATURE_NO_MATCH;
4213        }
4214
4215        ArraySet<Signature> set1 = new ArraySet<Signature>();
4216        for (Signature sig : s1) {
4217            set1.add(sig);
4218        }
4219        ArraySet<Signature> set2 = new ArraySet<Signature>();
4220        for (Signature sig : s2) {
4221            set2.add(sig);
4222        }
4223        // Make sure s2 contains all signatures in s1.
4224        if (set1.equals(set2)) {
4225            return PackageManager.SIGNATURE_MATCH;
4226        }
4227        return PackageManager.SIGNATURE_NO_MATCH;
4228    }
4229
4230    /**
4231     * If the database version for this type of package (internal storage or
4232     * external storage) is less than the version where package signatures
4233     * were updated, return true.
4234     */
4235    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4236        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4237        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4238    }
4239
4240    /**
4241     * Used for backward compatibility to make sure any packages with
4242     * certificate chains get upgraded to the new style. {@code existingSigs}
4243     * will be in the old format (since they were stored on disk from before the
4244     * system upgrade) and {@code scannedSigs} will be in the newer format.
4245     */
4246    private int compareSignaturesCompat(PackageSignatures existingSigs,
4247            PackageParser.Package scannedPkg) {
4248        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4249            return PackageManager.SIGNATURE_NO_MATCH;
4250        }
4251
4252        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4253        for (Signature sig : existingSigs.mSignatures) {
4254            existingSet.add(sig);
4255        }
4256        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4257        for (Signature sig : scannedPkg.mSignatures) {
4258            try {
4259                Signature[] chainSignatures = sig.getChainSignatures();
4260                for (Signature chainSig : chainSignatures) {
4261                    scannedCompatSet.add(chainSig);
4262                }
4263            } catch (CertificateEncodingException e) {
4264                scannedCompatSet.add(sig);
4265            }
4266        }
4267        /*
4268         * Make sure the expanded scanned set contains all signatures in the
4269         * existing one.
4270         */
4271        if (scannedCompatSet.equals(existingSet)) {
4272            // Migrate the old signatures to the new scheme.
4273            existingSigs.assignSignatures(scannedPkg.mSignatures);
4274            // The new KeySets will be re-added later in the scanning process.
4275            synchronized (mPackages) {
4276                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4277            }
4278            return PackageManager.SIGNATURE_MATCH;
4279        }
4280        return PackageManager.SIGNATURE_NO_MATCH;
4281    }
4282
4283    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4284        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4285        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4286    }
4287
4288    private int compareSignaturesRecover(PackageSignatures existingSigs,
4289            PackageParser.Package scannedPkg) {
4290        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4291            return PackageManager.SIGNATURE_NO_MATCH;
4292        }
4293
4294        String msg = null;
4295        try {
4296            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4297                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4298                        + scannedPkg.packageName);
4299                return PackageManager.SIGNATURE_MATCH;
4300            }
4301        } catch (CertificateException e) {
4302            msg = e.getMessage();
4303        }
4304
4305        logCriticalInfo(Log.INFO,
4306                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4307        return PackageManager.SIGNATURE_NO_MATCH;
4308    }
4309
4310    @Override
4311    public String[] getPackagesForUid(int uid) {
4312        uid = UserHandle.getAppId(uid);
4313        // reader
4314        synchronized (mPackages) {
4315            Object obj = mSettings.getUserIdLPr(uid);
4316            if (obj instanceof SharedUserSetting) {
4317                final SharedUserSetting sus = (SharedUserSetting) obj;
4318                final int N = sus.packages.size();
4319                final String[] res = new String[N];
4320                final Iterator<PackageSetting> it = sus.packages.iterator();
4321                int i = 0;
4322                while (it.hasNext()) {
4323                    res[i++] = it.next().name;
4324                }
4325                return res;
4326            } else if (obj instanceof PackageSetting) {
4327                final PackageSetting ps = (PackageSetting) obj;
4328                return new String[] { ps.name };
4329            }
4330        }
4331        return null;
4332    }
4333
4334    @Override
4335    public String getNameForUid(int uid) {
4336        // reader
4337        synchronized (mPackages) {
4338            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4339            if (obj instanceof SharedUserSetting) {
4340                final SharedUserSetting sus = (SharedUserSetting) obj;
4341                return sus.name + ":" + sus.userId;
4342            } else if (obj instanceof PackageSetting) {
4343                final PackageSetting ps = (PackageSetting) obj;
4344                return ps.name;
4345            }
4346        }
4347        return null;
4348    }
4349
4350    @Override
4351    public int getUidForSharedUser(String sharedUserName) {
4352        if(sharedUserName == null) {
4353            return -1;
4354        }
4355        // reader
4356        synchronized (mPackages) {
4357            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4358            if (suid == null) {
4359                return -1;
4360            }
4361            return suid.userId;
4362        }
4363    }
4364
4365    @Override
4366    public int getFlagsForUid(int uid) {
4367        synchronized (mPackages) {
4368            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4369            if (obj instanceof SharedUserSetting) {
4370                final SharedUserSetting sus = (SharedUserSetting) obj;
4371                return sus.pkgFlags;
4372            } else if (obj instanceof PackageSetting) {
4373                final PackageSetting ps = (PackageSetting) obj;
4374                return ps.pkgFlags;
4375            }
4376        }
4377        return 0;
4378    }
4379
4380    @Override
4381    public int getPrivateFlagsForUid(int uid) {
4382        synchronized (mPackages) {
4383            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4384            if (obj instanceof SharedUserSetting) {
4385                final SharedUserSetting sus = (SharedUserSetting) obj;
4386                return sus.pkgPrivateFlags;
4387            } else if (obj instanceof PackageSetting) {
4388                final PackageSetting ps = (PackageSetting) obj;
4389                return ps.pkgPrivateFlags;
4390            }
4391        }
4392        return 0;
4393    }
4394
4395    @Override
4396    public boolean isUidPrivileged(int uid) {
4397        uid = UserHandle.getAppId(uid);
4398        // reader
4399        synchronized (mPackages) {
4400            Object obj = mSettings.getUserIdLPr(uid);
4401            if (obj instanceof SharedUserSetting) {
4402                final SharedUserSetting sus = (SharedUserSetting) obj;
4403                final Iterator<PackageSetting> it = sus.packages.iterator();
4404                while (it.hasNext()) {
4405                    if (it.next().isPrivileged()) {
4406                        return true;
4407                    }
4408                }
4409            } else if (obj instanceof PackageSetting) {
4410                final PackageSetting ps = (PackageSetting) obj;
4411                return ps.isPrivileged();
4412            }
4413        }
4414        return false;
4415    }
4416
4417    @Override
4418    public String[] getAppOpPermissionPackages(String permissionName) {
4419        synchronized (mPackages) {
4420            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4421            if (pkgs == null) {
4422                return null;
4423            }
4424            return pkgs.toArray(new String[pkgs.size()]);
4425        }
4426    }
4427
4428    @Override
4429    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4430            int flags, int userId) {
4431        if (!sUserManager.exists(userId)) return null;
4432        flags = augmentFlagsForUser(flags, userId);
4433        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4434        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4435        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4436    }
4437
4438    @Override
4439    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4440            IntentFilter filter, int match, ComponentName activity) {
4441        final int userId = UserHandle.getCallingUserId();
4442        if (DEBUG_PREFERRED) {
4443            Log.v(TAG, "setLastChosenActivity intent=" + intent
4444                + " resolvedType=" + resolvedType
4445                + " flags=" + flags
4446                + " filter=" + filter
4447                + " match=" + match
4448                + " activity=" + activity);
4449            filter.dump(new PrintStreamPrinter(System.out), "    ");
4450        }
4451        intent.setComponent(null);
4452        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4453        // Find any earlier preferred or last chosen entries and nuke them
4454        findPreferredActivity(intent, resolvedType,
4455                flags, query, 0, false, true, false, userId);
4456        // Add the new activity as the last chosen for this filter
4457        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4458                "Setting last chosen");
4459    }
4460
4461    @Override
4462    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4463        final int userId = UserHandle.getCallingUserId();
4464        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4465        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4466        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4467                false, false, false, userId);
4468    }
4469
4470    private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) {
4471        MessageDigest digest = null;
4472        try {
4473            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4474        } catch (NoSuchAlgorithmException e) {
4475            // If we can't create a digest, ignore ephemeral apps.
4476            return false;
4477        }
4478
4479        final byte[] hostBytes = intent.getData().getHost().getBytes();
4480        final byte[] digestBytes = digest.digest(hostBytes);
4481        int shaPrefix =
4482                digestBytes[0] << 24
4483                | digestBytes[1] << 16
4484                | digestBytes[2] << 8
4485                | digestBytes[3] << 0;
4486        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4487                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4488        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4489            // No hash prefix match; there are no ephemeral apps for this domain.
4490            return false;
4491        }
4492        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4493            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4494            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4495                continue;
4496            }
4497            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4498            // No filters; this should never happen.
4499            if (filters.isEmpty()) {
4500                continue;
4501            }
4502            // We have a domain match; resolve the filters to see if anything matches.
4503            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4504            for (int j = filters.size() - 1; j >= 0; --j) {
4505                ephemeralResolver.addFilter(filters.get(j));
4506            }
4507            List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent(
4508                    intent, resolvedType, false /*defaultOnly*/, userId);
4509            return !ephemeralResolveList.isEmpty();
4510        }
4511        // Hash or filter mis-match; no ephemeral apps for this domain.
4512        return false;
4513    }
4514
4515    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4516            int flags, List<ResolveInfo> query, int userId) {
4517        final boolean isWebUri = hasWebURI(intent);
4518        // Check whether or not an ephemeral app exists to handle the URI.
4519        if (isWebUri && mEphemeralResolverConnection != null) {
4520            // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution.
4521            boolean hasAlwaysHandler = false;
4522            synchronized (mPackages) {
4523                final int count = query.size();
4524                for (int n=0; n<count; n++) {
4525                    ResolveInfo info = query.get(n);
4526                    String packageName = info.activityInfo.packageName;
4527                    PackageSetting ps = mSettings.mPackages.get(packageName);
4528                    if (ps != null) {
4529                        // Try to get the status from User settings first
4530                        long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4531                        int status = (int) (packedStatus >> 32);
4532                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4533                                || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4534                            hasAlwaysHandler = true;
4535                            break;
4536                        }
4537                    }
4538                }
4539            }
4540
4541            // Only consider installing an ephemeral app if there isn't already a verified handler.
4542            // We've determined that there's an ephemeral app available for the URI, ignore any
4543            // ResolveInfo's and just return the ephemeral installer
4544            if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) {
4545                if (DEBUG_EPHEMERAL) {
4546                    Slog.v(TAG, "Resolving to the ephemeral installer");
4547                }
4548                // ditch the result and return a ResolveInfo to launch the ephemeral installer
4549                ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo);
4550                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4551                // make a deep copy of the applicationInfo
4552                ri.activityInfo.applicationInfo = new ApplicationInfo(
4553                        ri.activityInfo.applicationInfo);
4554                if (userId != 0) {
4555                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4556                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4557                }
4558                return ri;
4559            }
4560        }
4561        if (query != null) {
4562            final int N = query.size();
4563            if (N == 1) {
4564                return query.get(0);
4565            } else if (N > 1) {
4566                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4567                // If there is more than one activity with the same priority,
4568                // then let the user decide between them.
4569                ResolveInfo r0 = query.get(0);
4570                ResolveInfo r1 = query.get(1);
4571                if (DEBUG_INTENT_MATCHING || debug) {
4572                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4573                            + r1.activityInfo.name + "=" + r1.priority);
4574                }
4575                // If the first activity has a higher priority, or a different
4576                // default, then it is always desireable to pick it.
4577                if (r0.priority != r1.priority
4578                        || r0.preferredOrder != r1.preferredOrder
4579                        || r0.isDefault != r1.isDefault) {
4580                    return query.get(0);
4581                }
4582                // If we have saved a preference for a preferred activity for
4583                // this Intent, use that.
4584                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4585                        flags, query, r0.priority, true, false, debug, userId);
4586                if (ri != null) {
4587                    return ri;
4588                }
4589                ri = new ResolveInfo(mResolveInfo);
4590                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4591                ri.activityInfo.applicationInfo = new ApplicationInfo(
4592                        ri.activityInfo.applicationInfo);
4593                if (userId != 0) {
4594                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4595                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4596                }
4597                // Make sure that the resolver is displayable in car mode
4598                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4599                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4600                return ri;
4601            }
4602        }
4603        return null;
4604    }
4605
4606    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4607            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4608        final int N = query.size();
4609        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4610                .get(userId);
4611        // Get the list of persistent preferred activities that handle the intent
4612        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4613        List<PersistentPreferredActivity> pprefs = ppir != null
4614                ? ppir.queryIntent(intent, resolvedType,
4615                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4616                : null;
4617        if (pprefs != null && pprefs.size() > 0) {
4618            final int M = pprefs.size();
4619            for (int i=0; i<M; i++) {
4620                final PersistentPreferredActivity ppa = pprefs.get(i);
4621                if (DEBUG_PREFERRED || debug) {
4622                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4623                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4624                            + "\n  component=" + ppa.mComponent);
4625                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4626                }
4627                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4628                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4629                if (DEBUG_PREFERRED || debug) {
4630                    Slog.v(TAG, "Found persistent preferred activity:");
4631                    if (ai != null) {
4632                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4633                    } else {
4634                        Slog.v(TAG, "  null");
4635                    }
4636                }
4637                if (ai == null) {
4638                    // This previously registered persistent preferred activity
4639                    // component is no longer known. Ignore it and do NOT remove it.
4640                    continue;
4641                }
4642                for (int j=0; j<N; j++) {
4643                    final ResolveInfo ri = query.get(j);
4644                    if (!ri.activityInfo.applicationInfo.packageName
4645                            .equals(ai.applicationInfo.packageName)) {
4646                        continue;
4647                    }
4648                    if (!ri.activityInfo.name.equals(ai.name)) {
4649                        continue;
4650                    }
4651                    //  Found a persistent preference that can handle the intent.
4652                    if (DEBUG_PREFERRED || debug) {
4653                        Slog.v(TAG, "Returning persistent preferred activity: " +
4654                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4655                    }
4656                    return ri;
4657                }
4658            }
4659        }
4660        return null;
4661    }
4662
4663    // TODO: handle preferred activities missing while user has amnesia
4664    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4665            List<ResolveInfo> query, int priority, boolean always,
4666            boolean removeMatches, boolean debug, int userId) {
4667        if (!sUserManager.exists(userId)) return null;
4668        flags = augmentFlagsForUser(flags, userId);
4669        // writer
4670        synchronized (mPackages) {
4671            if (intent.getSelector() != null) {
4672                intent = intent.getSelector();
4673            }
4674            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4675
4676            // Try to find a matching persistent preferred activity.
4677            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4678                    debug, userId);
4679
4680            // If a persistent preferred activity matched, use it.
4681            if (pri != null) {
4682                return pri;
4683            }
4684
4685            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4686            // Get the list of preferred activities that handle the intent
4687            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4688            List<PreferredActivity> prefs = pir != null
4689                    ? pir.queryIntent(intent, resolvedType,
4690                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4691                    : null;
4692            if (prefs != null && prefs.size() > 0) {
4693                boolean changed = false;
4694                try {
4695                    // First figure out how good the original match set is.
4696                    // We will only allow preferred activities that came
4697                    // from the same match quality.
4698                    int match = 0;
4699
4700                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4701
4702                    final int N = query.size();
4703                    for (int j=0; j<N; j++) {
4704                        final ResolveInfo ri = query.get(j);
4705                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4706                                + ": 0x" + Integer.toHexString(match));
4707                        if (ri.match > match) {
4708                            match = ri.match;
4709                        }
4710                    }
4711
4712                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4713                            + Integer.toHexString(match));
4714
4715                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4716                    final int M = prefs.size();
4717                    for (int i=0; i<M; i++) {
4718                        final PreferredActivity pa = prefs.get(i);
4719                        if (DEBUG_PREFERRED || debug) {
4720                            Slog.v(TAG, "Checking PreferredActivity ds="
4721                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4722                                    + "\n  component=" + pa.mPref.mComponent);
4723                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4724                        }
4725                        if (pa.mPref.mMatch != match) {
4726                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4727                                    + Integer.toHexString(pa.mPref.mMatch));
4728                            continue;
4729                        }
4730                        // If it's not an "always" type preferred activity and that's what we're
4731                        // looking for, skip it.
4732                        if (always && !pa.mPref.mAlways) {
4733                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4734                            continue;
4735                        }
4736                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4737                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4738                        if (DEBUG_PREFERRED || debug) {
4739                            Slog.v(TAG, "Found preferred activity:");
4740                            if (ai != null) {
4741                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4742                            } else {
4743                                Slog.v(TAG, "  null");
4744                            }
4745                        }
4746                        if (ai == null) {
4747                            // This previously registered preferred activity
4748                            // component is no longer known.  Most likely an update
4749                            // to the app was installed and in the new version this
4750                            // component no longer exists.  Clean it up by removing
4751                            // it from the preferred activities list, and skip it.
4752                            Slog.w(TAG, "Removing dangling preferred activity: "
4753                                    + pa.mPref.mComponent);
4754                            pir.removeFilter(pa);
4755                            changed = true;
4756                            continue;
4757                        }
4758                        for (int j=0; j<N; j++) {
4759                            final ResolveInfo ri = query.get(j);
4760                            if (!ri.activityInfo.applicationInfo.packageName
4761                                    .equals(ai.applicationInfo.packageName)) {
4762                                continue;
4763                            }
4764                            if (!ri.activityInfo.name.equals(ai.name)) {
4765                                continue;
4766                            }
4767
4768                            if (removeMatches) {
4769                                pir.removeFilter(pa);
4770                                changed = true;
4771                                if (DEBUG_PREFERRED) {
4772                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4773                                }
4774                                break;
4775                            }
4776
4777                            // Okay we found a previously set preferred or last chosen app.
4778                            // If the result set is different from when this
4779                            // was created, we need to clear it and re-ask the
4780                            // user their preference, if we're looking for an "always" type entry.
4781                            if (always && !pa.mPref.sameSet(query)) {
4782                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4783                                        + intent + " type " + resolvedType);
4784                                if (DEBUG_PREFERRED) {
4785                                    Slog.v(TAG, "Removing preferred activity since set changed "
4786                                            + pa.mPref.mComponent);
4787                                }
4788                                pir.removeFilter(pa);
4789                                // Re-add the filter as a "last chosen" entry (!always)
4790                                PreferredActivity lastChosen = new PreferredActivity(
4791                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4792                                pir.addFilter(lastChosen);
4793                                changed = true;
4794                                return null;
4795                            }
4796
4797                            // Yay! Either the set matched or we're looking for the last chosen
4798                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4799                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4800                            return ri;
4801                        }
4802                    }
4803                } finally {
4804                    if (changed) {
4805                        if (DEBUG_PREFERRED) {
4806                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4807                        }
4808                        scheduleWritePackageRestrictionsLocked(userId);
4809                    }
4810                }
4811            }
4812        }
4813        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4814        return null;
4815    }
4816
4817    /*
4818     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4819     */
4820    @Override
4821    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4822            int targetUserId) {
4823        mContext.enforceCallingOrSelfPermission(
4824                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4825        List<CrossProfileIntentFilter> matches =
4826                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4827        if (matches != null) {
4828            int size = matches.size();
4829            for (int i = 0; i < size; i++) {
4830                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4831            }
4832        }
4833        if (hasWebURI(intent)) {
4834            // cross-profile app linking works only towards the parent.
4835            final UserInfo parent = getProfileParent(sourceUserId);
4836            synchronized(mPackages) {
4837                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4838                        intent, resolvedType, 0, sourceUserId, parent.id);
4839                return xpDomainInfo != null;
4840            }
4841        }
4842        return false;
4843    }
4844
4845    private UserInfo getProfileParent(int userId) {
4846        final long identity = Binder.clearCallingIdentity();
4847        try {
4848            return sUserManager.getProfileParent(userId);
4849        } finally {
4850            Binder.restoreCallingIdentity(identity);
4851        }
4852    }
4853
4854    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4855            String resolvedType, int userId) {
4856        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4857        if (resolver != null) {
4858            return resolver.queryIntent(intent, resolvedType, false, userId);
4859        }
4860        return null;
4861    }
4862
4863    @Override
4864    public List<ResolveInfo> queryIntentActivities(Intent intent,
4865            String resolvedType, int flags, int userId) {
4866        if (!sUserManager.exists(userId)) return Collections.emptyList();
4867        flags = augmentFlagsForUser(flags, userId);
4868        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4869        ComponentName comp = intent.getComponent();
4870        if (comp == null) {
4871            if (intent.getSelector() != null) {
4872                intent = intent.getSelector();
4873                comp = intent.getComponent();
4874            }
4875        }
4876
4877        if (comp != null) {
4878            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4879            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4880            if (ai != null) {
4881                final ResolveInfo ri = new ResolveInfo();
4882                ri.activityInfo = ai;
4883                list.add(ri);
4884            }
4885            return list;
4886        }
4887
4888        // reader
4889        synchronized (mPackages) {
4890            final String pkgName = intent.getPackage();
4891            if (pkgName == null) {
4892                List<CrossProfileIntentFilter> matchingFilters =
4893                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4894                // Check for results that need to skip the current profile.
4895                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4896                        resolvedType, flags, userId);
4897                if (xpResolveInfo != null) {
4898                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4899                    result.add(xpResolveInfo);
4900                    return filterIfNotSystemUser(result, userId);
4901                }
4902
4903                // Check for results in the current profile.
4904                List<ResolveInfo> result = mActivities.queryIntent(
4905                        intent, resolvedType, flags, userId);
4906                result = filterIfNotSystemUser(result, userId);
4907
4908                // Check for cross profile results.
4909                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4910                xpResolveInfo = queryCrossProfileIntents(
4911                        matchingFilters, intent, resolvedType, flags, userId,
4912                        hasNonNegativePriorityResult);
4913                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4914                    boolean isVisibleToUser = filterIfNotSystemUser(
4915                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4916                    if (isVisibleToUser) {
4917                        result.add(xpResolveInfo);
4918                        Collections.sort(result, mResolvePrioritySorter);
4919                    }
4920                }
4921                if (hasWebURI(intent)) {
4922                    CrossProfileDomainInfo xpDomainInfo = null;
4923                    final UserInfo parent = getProfileParent(userId);
4924                    if (parent != null) {
4925                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4926                                flags, userId, parent.id);
4927                    }
4928                    if (xpDomainInfo != null) {
4929                        if (xpResolveInfo != null) {
4930                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4931                            // in the result.
4932                            result.remove(xpResolveInfo);
4933                        }
4934                        if (result.size() == 0) {
4935                            result.add(xpDomainInfo.resolveInfo);
4936                            return result;
4937                        }
4938                    } else if (result.size() <= 1) {
4939                        return result;
4940                    }
4941                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4942                            xpDomainInfo, userId);
4943                    Collections.sort(result, mResolvePrioritySorter);
4944                }
4945                return result;
4946            }
4947            final PackageParser.Package pkg = mPackages.get(pkgName);
4948            if (pkg != null) {
4949                return filterIfNotSystemUser(
4950                        mActivities.queryIntentForPackage(
4951                                intent, resolvedType, flags, pkg.activities, userId),
4952                        userId);
4953            }
4954            return new ArrayList<ResolveInfo>();
4955        }
4956    }
4957
4958    private static class CrossProfileDomainInfo {
4959        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4960        ResolveInfo resolveInfo;
4961        /* Best domain verification status of the activities found in the other profile */
4962        int bestDomainVerificationStatus;
4963    }
4964
4965    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4966            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4967        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4968                sourceUserId)) {
4969            return null;
4970        }
4971        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4972                resolvedType, flags, parentUserId);
4973
4974        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4975            return null;
4976        }
4977        CrossProfileDomainInfo result = null;
4978        int size = resultTargetUser.size();
4979        for (int i = 0; i < size; i++) {
4980            ResolveInfo riTargetUser = resultTargetUser.get(i);
4981            // Intent filter verification is only for filters that specify a host. So don't return
4982            // those that handle all web uris.
4983            if (riTargetUser.handleAllWebDataURI) {
4984                continue;
4985            }
4986            String packageName = riTargetUser.activityInfo.packageName;
4987            PackageSetting ps = mSettings.mPackages.get(packageName);
4988            if (ps == null) {
4989                continue;
4990            }
4991            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4992            int status = (int)(verificationState >> 32);
4993            if (result == null) {
4994                result = new CrossProfileDomainInfo();
4995                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4996                        sourceUserId, parentUserId);
4997                result.bestDomainVerificationStatus = status;
4998            } else {
4999                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5000                        result.bestDomainVerificationStatus);
5001            }
5002        }
5003        // Don't consider matches with status NEVER across profiles.
5004        if (result != null && result.bestDomainVerificationStatus
5005                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5006            return null;
5007        }
5008        return result;
5009    }
5010
5011    /**
5012     * Verification statuses are ordered from the worse to the best, except for
5013     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5014     */
5015    private int bestDomainVerificationStatus(int status1, int status2) {
5016        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5017            return status2;
5018        }
5019        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5020            return status1;
5021        }
5022        return (int) MathUtils.max(status1, status2);
5023    }
5024
5025    private boolean isUserEnabled(int userId) {
5026        long callingId = Binder.clearCallingIdentity();
5027        try {
5028            UserInfo userInfo = sUserManager.getUserInfo(userId);
5029            return userInfo != null && userInfo.isEnabled();
5030        } finally {
5031            Binder.restoreCallingIdentity(callingId);
5032        }
5033    }
5034
5035    /**
5036     * Filter out activities with systemUserOnly flag set, when current user is not System.
5037     *
5038     * @return filtered list
5039     */
5040    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5041        if (userId == UserHandle.USER_SYSTEM) {
5042            return resolveInfos;
5043        }
5044        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5045            ResolveInfo info = resolveInfos.get(i);
5046            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5047                resolveInfos.remove(i);
5048            }
5049        }
5050        return resolveInfos;
5051    }
5052
5053    /**
5054     * @param resolveInfos list of resolve infos in descending priority order
5055     * @return if the list contains a resolve info with non-negative priority
5056     */
5057    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5058        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5059    }
5060
5061    private static boolean hasWebURI(Intent intent) {
5062        if (intent.getData() == null) {
5063            return false;
5064        }
5065        final String scheme = intent.getScheme();
5066        if (TextUtils.isEmpty(scheme)) {
5067            return false;
5068        }
5069        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5070    }
5071
5072    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5073            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5074            int userId) {
5075        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5076
5077        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5078            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5079                    candidates.size());
5080        }
5081
5082        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5083        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5084        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5085        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5086        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5087        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5088
5089        synchronized (mPackages) {
5090            final int count = candidates.size();
5091            // First, try to use linked apps. Partition the candidates into four lists:
5092            // one for the final results, one for the "do not use ever", one for "undefined status"
5093            // and finally one for "browser app type".
5094            for (int n=0; n<count; n++) {
5095                ResolveInfo info = candidates.get(n);
5096                String packageName = info.activityInfo.packageName;
5097                PackageSetting ps = mSettings.mPackages.get(packageName);
5098                if (ps != null) {
5099                    // Add to the special match all list (Browser use case)
5100                    if (info.handleAllWebDataURI) {
5101                        matchAllList.add(info);
5102                        continue;
5103                    }
5104                    // Try to get the status from User settings first
5105                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5106                    int status = (int)(packedStatus >> 32);
5107                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5108                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5109                        if (DEBUG_DOMAIN_VERIFICATION) {
5110                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5111                                    + " : linkgen=" + linkGeneration);
5112                        }
5113                        // Use link-enabled generation as preferredOrder, i.e.
5114                        // prefer newly-enabled over earlier-enabled.
5115                        info.preferredOrder = linkGeneration;
5116                        alwaysList.add(info);
5117                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5118                        if (DEBUG_DOMAIN_VERIFICATION) {
5119                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5120                        }
5121                        neverList.add(info);
5122                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5123                        if (DEBUG_DOMAIN_VERIFICATION) {
5124                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5125                        }
5126                        alwaysAskList.add(info);
5127                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5128                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5129                        if (DEBUG_DOMAIN_VERIFICATION) {
5130                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5131                        }
5132                        undefinedList.add(info);
5133                    }
5134                }
5135            }
5136
5137            // We'll want to include browser possibilities in a few cases
5138            boolean includeBrowser = false;
5139
5140            // First try to add the "always" resolution(s) for the current user, if any
5141            if (alwaysList.size() > 0) {
5142                result.addAll(alwaysList);
5143            } else {
5144                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5145                result.addAll(undefinedList);
5146                // Maybe add one for the other profile.
5147                if (xpDomainInfo != null && (
5148                        xpDomainInfo.bestDomainVerificationStatus
5149                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5150                    result.add(xpDomainInfo.resolveInfo);
5151                }
5152                includeBrowser = true;
5153            }
5154
5155            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5156            // If there were 'always' entries their preferred order has been set, so we also
5157            // back that off to make the alternatives equivalent
5158            if (alwaysAskList.size() > 0) {
5159                for (ResolveInfo i : result) {
5160                    i.preferredOrder = 0;
5161                }
5162                result.addAll(alwaysAskList);
5163                includeBrowser = true;
5164            }
5165
5166            if (includeBrowser) {
5167                // Also add browsers (all of them or only the default one)
5168                if (DEBUG_DOMAIN_VERIFICATION) {
5169                    Slog.v(TAG, "   ...including browsers in candidate set");
5170                }
5171                if ((matchFlags & MATCH_ALL) != 0) {
5172                    result.addAll(matchAllList);
5173                } else {
5174                    // Browser/generic handling case.  If there's a default browser, go straight
5175                    // to that (but only if there is no other higher-priority match).
5176                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5177                    int maxMatchPrio = 0;
5178                    ResolveInfo defaultBrowserMatch = null;
5179                    final int numCandidates = matchAllList.size();
5180                    for (int n = 0; n < numCandidates; n++) {
5181                        ResolveInfo info = matchAllList.get(n);
5182                        // track the highest overall match priority...
5183                        if (info.priority > maxMatchPrio) {
5184                            maxMatchPrio = info.priority;
5185                        }
5186                        // ...and the highest-priority default browser match
5187                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5188                            if (defaultBrowserMatch == null
5189                                    || (defaultBrowserMatch.priority < info.priority)) {
5190                                if (debug) {
5191                                    Slog.v(TAG, "Considering default browser match " + info);
5192                                }
5193                                defaultBrowserMatch = info;
5194                            }
5195                        }
5196                    }
5197                    if (defaultBrowserMatch != null
5198                            && defaultBrowserMatch.priority >= maxMatchPrio
5199                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5200                    {
5201                        if (debug) {
5202                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5203                        }
5204                        result.add(defaultBrowserMatch);
5205                    } else {
5206                        result.addAll(matchAllList);
5207                    }
5208                }
5209
5210                // If there is nothing selected, add all candidates and remove the ones that the user
5211                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5212                if (result.size() == 0) {
5213                    result.addAll(candidates);
5214                    result.removeAll(neverList);
5215                }
5216            }
5217        }
5218        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5219            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5220                    result.size());
5221            for (ResolveInfo info : result) {
5222                Slog.v(TAG, "  + " + info.activityInfo);
5223            }
5224        }
5225        return result;
5226    }
5227
5228    // Returns a packed value as a long:
5229    //
5230    // high 'int'-sized word: link status: undefined/ask/never/always.
5231    // low 'int'-sized word: relative priority among 'always' results.
5232    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5233        long result = ps.getDomainVerificationStatusForUser(userId);
5234        // if none available, get the master status
5235        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5236            if (ps.getIntentFilterVerificationInfo() != null) {
5237                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5238            }
5239        }
5240        return result;
5241    }
5242
5243    private ResolveInfo querySkipCurrentProfileIntents(
5244            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5245            int flags, int sourceUserId) {
5246        if (matchingFilters != null) {
5247            int size = matchingFilters.size();
5248            for (int i = 0; i < size; i ++) {
5249                CrossProfileIntentFilter filter = matchingFilters.get(i);
5250                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5251                    // Checking if there are activities in the target user that can handle the
5252                    // intent.
5253                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5254                            resolvedType, flags, sourceUserId);
5255                    if (resolveInfo != null) {
5256                        return resolveInfo;
5257                    }
5258                }
5259            }
5260        }
5261        return null;
5262    }
5263
5264    // Return matching ResolveInfo in target user if any.
5265    private ResolveInfo queryCrossProfileIntents(
5266            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5267            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5268        if (matchingFilters != null) {
5269            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5270            // match the same intent. For performance reasons, it is better not to
5271            // run queryIntent twice for the same userId
5272            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5273            int size = matchingFilters.size();
5274            for (int i = 0; i < size; i++) {
5275                CrossProfileIntentFilter filter = matchingFilters.get(i);
5276                int targetUserId = filter.getTargetUserId();
5277                boolean skipCurrentProfile =
5278                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5279                boolean skipCurrentProfileIfNoMatchFound =
5280                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5281                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5282                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5283                    // Checking if there are activities in the target user that can handle the
5284                    // intent.
5285                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5286                            resolvedType, flags, sourceUserId);
5287                    if (resolveInfo != null) return resolveInfo;
5288                    alreadyTriedUserIds.put(targetUserId, true);
5289                }
5290            }
5291        }
5292        return null;
5293    }
5294
5295    /**
5296     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5297     * will forward the intent to the filter's target user.
5298     * Otherwise, returns null.
5299     */
5300    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5301            String resolvedType, int flags, int sourceUserId) {
5302        int targetUserId = filter.getTargetUserId();
5303        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5304                resolvedType, flags, targetUserId);
5305        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5306                && isUserEnabled(targetUserId)) {
5307            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5308        }
5309        return null;
5310    }
5311
5312    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5313            int sourceUserId, int targetUserId) {
5314        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5315        long ident = Binder.clearCallingIdentity();
5316        boolean targetIsProfile;
5317        try {
5318            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5319        } finally {
5320            Binder.restoreCallingIdentity(ident);
5321        }
5322        String className;
5323        if (targetIsProfile) {
5324            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5325        } else {
5326            className = FORWARD_INTENT_TO_PARENT;
5327        }
5328        ComponentName forwardingActivityComponentName = new ComponentName(
5329                mAndroidApplication.packageName, className);
5330        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5331                sourceUserId);
5332        if (!targetIsProfile) {
5333            forwardingActivityInfo.showUserIcon = targetUserId;
5334            forwardingResolveInfo.noResourceId = true;
5335        }
5336        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5337        forwardingResolveInfo.priority = 0;
5338        forwardingResolveInfo.preferredOrder = 0;
5339        forwardingResolveInfo.match = 0;
5340        forwardingResolveInfo.isDefault = true;
5341        forwardingResolveInfo.filter = filter;
5342        forwardingResolveInfo.targetUserId = targetUserId;
5343        return forwardingResolveInfo;
5344    }
5345
5346    @Override
5347    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5348            Intent[] specifics, String[] specificTypes, Intent intent,
5349            String resolvedType, int flags, int userId) {
5350        if (!sUserManager.exists(userId)) return Collections.emptyList();
5351        flags = augmentFlagsForUser(flags, userId);
5352        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5353                false, "query intent activity options");
5354        final String resultsAction = intent.getAction();
5355
5356        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5357                | PackageManager.GET_RESOLVED_FILTER, userId);
5358
5359        if (DEBUG_INTENT_MATCHING) {
5360            Log.v(TAG, "Query " + intent + ": " + results);
5361        }
5362
5363        int specificsPos = 0;
5364        int N;
5365
5366        // todo: note that the algorithm used here is O(N^2).  This
5367        // isn't a problem in our current environment, but if we start running
5368        // into situations where we have more than 5 or 10 matches then this
5369        // should probably be changed to something smarter...
5370
5371        // First we go through and resolve each of the specific items
5372        // that were supplied, taking care of removing any corresponding
5373        // duplicate items in the generic resolve list.
5374        if (specifics != null) {
5375            for (int i=0; i<specifics.length; i++) {
5376                final Intent sintent = specifics[i];
5377                if (sintent == null) {
5378                    continue;
5379                }
5380
5381                if (DEBUG_INTENT_MATCHING) {
5382                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5383                }
5384
5385                String action = sintent.getAction();
5386                if (resultsAction != null && resultsAction.equals(action)) {
5387                    // If this action was explicitly requested, then don't
5388                    // remove things that have it.
5389                    action = null;
5390                }
5391
5392                ResolveInfo ri = null;
5393                ActivityInfo ai = null;
5394
5395                ComponentName comp = sintent.getComponent();
5396                if (comp == null) {
5397                    ri = resolveIntent(
5398                        sintent,
5399                        specificTypes != null ? specificTypes[i] : null,
5400                            flags, userId);
5401                    if (ri == null) {
5402                        continue;
5403                    }
5404                    if (ri == mResolveInfo) {
5405                        // ACK!  Must do something better with this.
5406                    }
5407                    ai = ri.activityInfo;
5408                    comp = new ComponentName(ai.applicationInfo.packageName,
5409                            ai.name);
5410                } else {
5411                    ai = getActivityInfo(comp, flags, userId);
5412                    if (ai == null) {
5413                        continue;
5414                    }
5415                }
5416
5417                // Look for any generic query activities that are duplicates
5418                // of this specific one, and remove them from the results.
5419                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5420                N = results.size();
5421                int j;
5422                for (j=specificsPos; j<N; j++) {
5423                    ResolveInfo sri = results.get(j);
5424                    if ((sri.activityInfo.name.equals(comp.getClassName())
5425                            && sri.activityInfo.applicationInfo.packageName.equals(
5426                                    comp.getPackageName()))
5427                        || (action != null && sri.filter.matchAction(action))) {
5428                        results.remove(j);
5429                        if (DEBUG_INTENT_MATCHING) Log.v(
5430                            TAG, "Removing duplicate item from " + j
5431                            + " due to specific " + specificsPos);
5432                        if (ri == null) {
5433                            ri = sri;
5434                        }
5435                        j--;
5436                        N--;
5437                    }
5438                }
5439
5440                // Add this specific item to its proper place.
5441                if (ri == null) {
5442                    ri = new ResolveInfo();
5443                    ri.activityInfo = ai;
5444                }
5445                results.add(specificsPos, ri);
5446                ri.specificIndex = i;
5447                specificsPos++;
5448            }
5449        }
5450
5451        // Now we go through the remaining generic results and remove any
5452        // duplicate actions that are found here.
5453        N = results.size();
5454        for (int i=specificsPos; i<N-1; i++) {
5455            final ResolveInfo rii = results.get(i);
5456            if (rii.filter == null) {
5457                continue;
5458            }
5459
5460            // Iterate over all of the actions of this result's intent
5461            // filter...  typically this should be just one.
5462            final Iterator<String> it = rii.filter.actionsIterator();
5463            if (it == null) {
5464                continue;
5465            }
5466            while (it.hasNext()) {
5467                final String action = it.next();
5468                if (resultsAction != null && resultsAction.equals(action)) {
5469                    // If this action was explicitly requested, then don't
5470                    // remove things that have it.
5471                    continue;
5472                }
5473                for (int j=i+1; j<N; j++) {
5474                    final ResolveInfo rij = results.get(j);
5475                    if (rij.filter != null && rij.filter.hasAction(action)) {
5476                        results.remove(j);
5477                        if (DEBUG_INTENT_MATCHING) Log.v(
5478                            TAG, "Removing duplicate item from " + j
5479                            + " due to action " + action + " at " + i);
5480                        j--;
5481                        N--;
5482                    }
5483                }
5484            }
5485
5486            // If the caller didn't request filter information, drop it now
5487            // so we don't have to marshall/unmarshall it.
5488            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5489                rii.filter = null;
5490            }
5491        }
5492
5493        // Filter out the caller activity if so requested.
5494        if (caller != null) {
5495            N = results.size();
5496            for (int i=0; i<N; i++) {
5497                ActivityInfo ainfo = results.get(i).activityInfo;
5498                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5499                        && caller.getClassName().equals(ainfo.name)) {
5500                    results.remove(i);
5501                    break;
5502                }
5503            }
5504        }
5505
5506        // If the caller didn't request filter information,
5507        // drop them now so we don't have to
5508        // marshall/unmarshall it.
5509        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5510            N = results.size();
5511            for (int i=0; i<N; i++) {
5512                results.get(i).filter = null;
5513            }
5514        }
5515
5516        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5517        return results;
5518    }
5519
5520    @Override
5521    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5522            int userId) {
5523        if (!sUserManager.exists(userId)) return Collections.emptyList();
5524        flags = augmentFlagsForUser(flags, userId);
5525        ComponentName comp = intent.getComponent();
5526        if (comp == null) {
5527            if (intent.getSelector() != null) {
5528                intent = intent.getSelector();
5529                comp = intent.getComponent();
5530            }
5531        }
5532        if (comp != null) {
5533            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5534            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5535            if (ai != null) {
5536                ResolveInfo ri = new ResolveInfo();
5537                ri.activityInfo = ai;
5538                list.add(ri);
5539            }
5540            return list;
5541        }
5542
5543        // reader
5544        synchronized (mPackages) {
5545            String pkgName = intent.getPackage();
5546            if (pkgName == null) {
5547                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5548            }
5549            final PackageParser.Package pkg = mPackages.get(pkgName);
5550            if (pkg != null) {
5551                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5552                        userId);
5553            }
5554            return null;
5555        }
5556    }
5557
5558    @Override
5559    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5560        if (!sUserManager.exists(userId)) return null;
5561        flags = augmentFlagsForUser(flags, userId);
5562        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5563        if (query != null) {
5564            if (query.size() >= 1) {
5565                // If there is more than one service with the same priority,
5566                // just arbitrarily pick the first one.
5567                return query.get(0);
5568            }
5569        }
5570        return null;
5571    }
5572
5573    @Override
5574    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5575            int userId) {
5576        if (!sUserManager.exists(userId)) return Collections.emptyList();
5577        flags = augmentFlagsForUser(flags, userId);
5578        ComponentName comp = intent.getComponent();
5579        if (comp == null) {
5580            if (intent.getSelector() != null) {
5581                intent = intent.getSelector();
5582                comp = intent.getComponent();
5583            }
5584        }
5585        if (comp != null) {
5586            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5587            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5588            if (si != null) {
5589                final ResolveInfo ri = new ResolveInfo();
5590                ri.serviceInfo = si;
5591                list.add(ri);
5592            }
5593            return list;
5594        }
5595
5596        // reader
5597        synchronized (mPackages) {
5598            String pkgName = intent.getPackage();
5599            if (pkgName == null) {
5600                return mServices.queryIntent(intent, resolvedType, flags, userId);
5601            }
5602            final PackageParser.Package pkg = mPackages.get(pkgName);
5603            if (pkg != null) {
5604                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5605                        userId);
5606            }
5607            return null;
5608        }
5609    }
5610
5611    @Override
5612    public List<ResolveInfo> queryIntentContentProviders(
5613            Intent intent, String resolvedType, int flags, int userId) {
5614        if (!sUserManager.exists(userId)) return Collections.emptyList();
5615        flags = augmentFlagsForUser(flags, userId);
5616        ComponentName comp = intent.getComponent();
5617        if (comp == null) {
5618            if (intent.getSelector() != null) {
5619                intent = intent.getSelector();
5620                comp = intent.getComponent();
5621            }
5622        }
5623        if (comp != null) {
5624            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5625            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5626            if (pi != null) {
5627                final ResolveInfo ri = new ResolveInfo();
5628                ri.providerInfo = pi;
5629                list.add(ri);
5630            }
5631            return list;
5632        }
5633
5634        // reader
5635        synchronized (mPackages) {
5636            String pkgName = intent.getPackage();
5637            if (pkgName == null) {
5638                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5639            }
5640            final PackageParser.Package pkg = mPackages.get(pkgName);
5641            if (pkg != null) {
5642                return mProviders.queryIntentForPackage(
5643                        intent, resolvedType, flags, pkg.providers, userId);
5644            }
5645            return null;
5646        }
5647    }
5648
5649    @Override
5650    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5651        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5652
5653        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5654
5655        // writer
5656        synchronized (mPackages) {
5657            ArrayList<PackageInfo> list;
5658            if (listUninstalled) {
5659                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5660                for (PackageSetting ps : mSettings.mPackages.values()) {
5661                    PackageInfo pi;
5662                    if (ps.pkg != null) {
5663                        pi = generatePackageInfo(ps.pkg, flags, userId);
5664                    } else {
5665                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5666                    }
5667                    if (pi != null) {
5668                        list.add(pi);
5669                    }
5670                }
5671            } else {
5672                list = new ArrayList<PackageInfo>(mPackages.size());
5673                for (PackageParser.Package p : mPackages.values()) {
5674                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5675                    if (pi != null) {
5676                        list.add(pi);
5677                    }
5678                }
5679            }
5680
5681            return new ParceledListSlice<PackageInfo>(list);
5682        }
5683    }
5684
5685    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5686            String[] permissions, boolean[] tmp, int flags, int userId) {
5687        int numMatch = 0;
5688        final PermissionsState permissionsState = ps.getPermissionsState();
5689        for (int i=0; i<permissions.length; i++) {
5690            final String permission = permissions[i];
5691            if (permissionsState.hasPermission(permission, userId)) {
5692                tmp[i] = true;
5693                numMatch++;
5694            } else {
5695                tmp[i] = false;
5696            }
5697        }
5698        if (numMatch == 0) {
5699            return;
5700        }
5701        PackageInfo pi;
5702        if (ps.pkg != null) {
5703            pi = generatePackageInfo(ps.pkg, flags, userId);
5704        } else {
5705            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5706        }
5707        // The above might return null in cases of uninstalled apps or install-state
5708        // skew across users/profiles.
5709        if (pi != null) {
5710            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5711                if (numMatch == permissions.length) {
5712                    pi.requestedPermissions = permissions;
5713                } else {
5714                    pi.requestedPermissions = new String[numMatch];
5715                    numMatch = 0;
5716                    for (int i=0; i<permissions.length; i++) {
5717                        if (tmp[i]) {
5718                            pi.requestedPermissions[numMatch] = permissions[i];
5719                            numMatch++;
5720                        }
5721                    }
5722                }
5723            }
5724            list.add(pi);
5725        }
5726    }
5727
5728    @Override
5729    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5730            String[] permissions, int flags, int userId) {
5731        if (!sUserManager.exists(userId)) return null;
5732        flags = augmentFlagsForUser(flags, userId);
5733        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5734
5735        // writer
5736        synchronized (mPackages) {
5737            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5738            boolean[] tmpBools = new boolean[permissions.length];
5739            if (listUninstalled) {
5740                for (PackageSetting ps : mSettings.mPackages.values()) {
5741                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5742                }
5743            } else {
5744                for (PackageParser.Package pkg : mPackages.values()) {
5745                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5746                    if (ps != null) {
5747                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5748                                userId);
5749                    }
5750                }
5751            }
5752
5753            return new ParceledListSlice<PackageInfo>(list);
5754        }
5755    }
5756
5757    @Override
5758    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5759        if (!sUserManager.exists(userId)) return null;
5760        flags = augmentFlagsForUser(flags, userId);
5761        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5762
5763        // writer
5764        synchronized (mPackages) {
5765            ArrayList<ApplicationInfo> list;
5766            if (listUninstalled) {
5767                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5768                for (PackageSetting ps : mSettings.mPackages.values()) {
5769                    ApplicationInfo ai;
5770                    if (ps.pkg != null) {
5771                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5772                                ps.readUserState(userId), userId);
5773                    } else {
5774                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5775                    }
5776                    if (ai != null) {
5777                        list.add(ai);
5778                    }
5779                }
5780            } else {
5781                list = new ArrayList<ApplicationInfo>(mPackages.size());
5782                for (PackageParser.Package p : mPackages.values()) {
5783                    if (p.mExtras != null) {
5784                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5785                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5786                        if (ai != null) {
5787                            list.add(ai);
5788                        }
5789                    }
5790                }
5791            }
5792
5793            return new ParceledListSlice<ApplicationInfo>(list);
5794        }
5795    }
5796
5797    @Override
5798    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5799        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5800                "getEphemeralApplications");
5801        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5802                "getEphemeralApplications");
5803        synchronized (mPackages) {
5804            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5805                    .getEphemeralApplicationsLPw(userId);
5806            if (ephemeralApps != null) {
5807                return new ParceledListSlice<>(ephemeralApps);
5808            }
5809        }
5810        return null;
5811    }
5812
5813    @Override
5814    public boolean isEphemeralApplication(String packageName, int userId) {
5815        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5816                "isEphemeral");
5817        if (!isCallerSameApp(packageName)) {
5818            return false;
5819        }
5820        synchronized (mPackages) {
5821            PackageParser.Package pkg = mPackages.get(packageName);
5822            if (pkg != null) {
5823                return pkg.applicationInfo.isEphemeralApp();
5824            }
5825        }
5826        return false;
5827    }
5828
5829    @Override
5830    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5831        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5832                "getCookie");
5833        if (!isCallerSameApp(packageName)) {
5834            return null;
5835        }
5836        synchronized (mPackages) {
5837            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5838                    packageName, userId);
5839        }
5840    }
5841
5842    @Override
5843    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5844        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5845                "setCookie");
5846        if (!isCallerSameApp(packageName)) {
5847            return false;
5848        }
5849        synchronized (mPackages) {
5850            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5851                    packageName, cookie, userId);
5852        }
5853    }
5854
5855    @Override
5856    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5857        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5858                "getEphemeralApplicationIcon");
5859        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5860                "getEphemeralApplicationIcon");
5861        synchronized (mPackages) {
5862            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5863                    packageName, userId);
5864        }
5865    }
5866
5867    private boolean isCallerSameApp(String packageName) {
5868        PackageParser.Package pkg = mPackages.get(packageName);
5869        return pkg != null
5870                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5871    }
5872
5873    public List<ApplicationInfo> getPersistentApplications(int flags) {
5874        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5875
5876        // reader
5877        synchronized (mPackages) {
5878            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5879            final int userId = UserHandle.getCallingUserId();
5880            while (i.hasNext()) {
5881                final PackageParser.Package p = i.next();
5882                if (p.applicationInfo != null
5883                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5884                        && (!mSafeMode || isSystemApp(p))) {
5885                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5886                    if (ps != null) {
5887                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5888                                ps.readUserState(userId), userId);
5889                        if (ai != null) {
5890                            finalList.add(ai);
5891                        }
5892                    }
5893                }
5894            }
5895        }
5896
5897        return finalList;
5898    }
5899
5900    @Override
5901    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5902        if (!sUserManager.exists(userId)) return null;
5903        flags = augmentFlagsForUser(flags, userId);
5904        // reader
5905        synchronized (mPackages) {
5906            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5907            PackageSetting ps = provider != null
5908                    ? mSettings.mPackages.get(provider.owner.packageName)
5909                    : null;
5910            return ps != null
5911                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5912                    && (!mSafeMode || (provider.info.applicationInfo.flags
5913                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5914                    ? PackageParser.generateProviderInfo(provider, flags,
5915                            ps.readUserState(userId), userId)
5916                    : null;
5917        }
5918    }
5919
5920    /**
5921     * @deprecated
5922     */
5923    @Deprecated
5924    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5925        // reader
5926        synchronized (mPackages) {
5927            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5928                    .entrySet().iterator();
5929            final int userId = UserHandle.getCallingUserId();
5930            while (i.hasNext()) {
5931                Map.Entry<String, PackageParser.Provider> entry = i.next();
5932                PackageParser.Provider p = entry.getValue();
5933                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5934
5935                if (ps != null && p.syncable
5936                        && (!mSafeMode || (p.info.applicationInfo.flags
5937                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5938                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5939                            ps.readUserState(userId), userId);
5940                    if (info != null) {
5941                        outNames.add(entry.getKey());
5942                        outInfo.add(info);
5943                    }
5944                }
5945            }
5946        }
5947    }
5948
5949    @Override
5950    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5951            int uid, int flags) {
5952        final int userId = processName != null ? UserHandle.getUserId(uid)
5953                : UserHandle.getCallingUserId();
5954        if (!sUserManager.exists(userId)) return null;
5955        flags = augmentFlagsForUser(flags, userId);
5956
5957        ArrayList<ProviderInfo> finalList = null;
5958        // reader
5959        synchronized (mPackages) {
5960            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5961            while (i.hasNext()) {
5962                final PackageParser.Provider p = i.next();
5963                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5964                if (ps != null && p.info.authority != null
5965                        && (processName == null
5966                                || (p.info.processName.equals(processName)
5967                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5968                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5969                        && (!mSafeMode
5970                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5971                    if (finalList == null) {
5972                        finalList = new ArrayList<ProviderInfo>(3);
5973                    }
5974                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5975                            ps.readUserState(userId), userId);
5976                    if (info != null) {
5977                        finalList.add(info);
5978                    }
5979                }
5980            }
5981        }
5982
5983        if (finalList != null) {
5984            Collections.sort(finalList, mProviderInitOrderSorter);
5985            return new ParceledListSlice<ProviderInfo>(finalList);
5986        }
5987
5988        return null;
5989    }
5990
5991    @Override
5992    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5993            int flags) {
5994        // reader
5995        synchronized (mPackages) {
5996            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5997            return PackageParser.generateInstrumentationInfo(i, flags);
5998        }
5999    }
6000
6001    @Override
6002    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6003            int flags) {
6004        ArrayList<InstrumentationInfo> finalList =
6005            new ArrayList<InstrumentationInfo>();
6006
6007        // reader
6008        synchronized (mPackages) {
6009            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6010            while (i.hasNext()) {
6011                final PackageParser.Instrumentation p = i.next();
6012                if (targetPackage == null
6013                        || targetPackage.equals(p.info.targetPackage)) {
6014                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6015                            flags);
6016                    if (ii != null) {
6017                        finalList.add(ii);
6018                    }
6019                }
6020            }
6021        }
6022
6023        return finalList;
6024    }
6025
6026    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6027        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6028        if (overlays == null) {
6029            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6030            return;
6031        }
6032        for (PackageParser.Package opkg : overlays.values()) {
6033            // Not much to do if idmap fails: we already logged the error
6034            // and we certainly don't want to abort installation of pkg simply
6035            // because an overlay didn't fit properly. For these reasons,
6036            // ignore the return value of createIdmapForPackagePairLI.
6037            createIdmapForPackagePairLI(pkg, opkg);
6038        }
6039    }
6040
6041    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6042            PackageParser.Package opkg) {
6043        if (!opkg.mTrustedOverlay) {
6044            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6045                    opkg.baseCodePath + ": overlay not trusted");
6046            return false;
6047        }
6048        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6049        if (overlaySet == null) {
6050            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6051                    opkg.baseCodePath + " but target package has no known overlays");
6052            return false;
6053        }
6054        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6055        // TODO: generate idmap for split APKs
6056        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6057            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6058                    + opkg.baseCodePath);
6059            return false;
6060        }
6061        PackageParser.Package[] overlayArray =
6062            overlaySet.values().toArray(new PackageParser.Package[0]);
6063        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6064            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6065                return p1.mOverlayPriority - p2.mOverlayPriority;
6066            }
6067        };
6068        Arrays.sort(overlayArray, cmp);
6069
6070        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6071        int i = 0;
6072        for (PackageParser.Package p : overlayArray) {
6073            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6074        }
6075        return true;
6076    }
6077
6078    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6079        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6080        try {
6081            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6082        } finally {
6083            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6084        }
6085    }
6086
6087    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6088        final File[] files = dir.listFiles();
6089        if (ArrayUtils.isEmpty(files)) {
6090            Log.d(TAG, "No files in app dir " + dir);
6091            return;
6092        }
6093
6094        if (DEBUG_PACKAGE_SCANNING) {
6095            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6096                    + " flags=0x" + Integer.toHexString(parseFlags));
6097        }
6098
6099        for (File file : files) {
6100            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6101                    && !PackageInstallerService.isStageName(file.getName());
6102            if (!isPackage) {
6103                // Ignore entries which are not packages
6104                continue;
6105            }
6106            try {
6107                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6108                        scanFlags, currentTime, null);
6109            } catch (PackageManagerException e) {
6110                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6111
6112                // Delete invalid userdata apps
6113                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6114                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6115                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6116                    if (file.isDirectory()) {
6117                        mInstaller.rmPackageDir(file.getAbsolutePath());
6118                    } else {
6119                        file.delete();
6120                    }
6121                }
6122            }
6123        }
6124    }
6125
6126    private static File getSettingsProblemFile() {
6127        File dataDir = Environment.getDataDirectory();
6128        File systemDir = new File(dataDir, "system");
6129        File fname = new File(systemDir, "uiderrors.txt");
6130        return fname;
6131    }
6132
6133    static void reportSettingsProblem(int priority, String msg) {
6134        logCriticalInfo(priority, msg);
6135    }
6136
6137    static void logCriticalInfo(int priority, String msg) {
6138        Slog.println(priority, TAG, msg);
6139        EventLogTags.writePmCriticalInfo(msg);
6140        try {
6141            File fname = getSettingsProblemFile();
6142            FileOutputStream out = new FileOutputStream(fname, true);
6143            PrintWriter pw = new FastPrintWriter(out);
6144            SimpleDateFormat formatter = new SimpleDateFormat();
6145            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6146            pw.println(dateString + ": " + msg);
6147            pw.close();
6148            FileUtils.setPermissions(
6149                    fname.toString(),
6150                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6151                    -1, -1);
6152        } catch (java.io.IOException e) {
6153        }
6154    }
6155
6156    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6157            PackageParser.Package pkg, File srcFile, int parseFlags)
6158            throws PackageManagerException {
6159        if (ps != null
6160                && ps.codePath.equals(srcFile)
6161                && ps.timeStamp == srcFile.lastModified()
6162                && !isCompatSignatureUpdateNeeded(pkg)
6163                && !isRecoverSignatureUpdateNeeded(pkg)) {
6164            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6165            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6166            ArraySet<PublicKey> signingKs;
6167            synchronized (mPackages) {
6168                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6169            }
6170            if (ps.signatures.mSignatures != null
6171                    && ps.signatures.mSignatures.length != 0
6172                    && signingKs != null) {
6173                // Optimization: reuse the existing cached certificates
6174                // if the package appears to be unchanged.
6175                pkg.mSignatures = ps.signatures.mSignatures;
6176                pkg.mSigningKeys = signingKs;
6177                return;
6178            }
6179
6180            Slog.w(TAG, "PackageSetting for " + ps.name
6181                    + " is missing signatures.  Collecting certs again to recover them.");
6182        } else {
6183            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6184        }
6185
6186        try {
6187            pp.collectCertificates(pkg, parseFlags);
6188            pp.collectManifestDigest(pkg);
6189        } catch (PackageParserException e) {
6190            throw PackageManagerException.from(e);
6191        }
6192    }
6193
6194    /**
6195     *  Traces a package scan.
6196     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6197     */
6198    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6199            long currentTime, UserHandle user) throws PackageManagerException {
6200        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6201        try {
6202            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6203        } finally {
6204            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6205        }
6206    }
6207
6208    /**
6209     *  Scans a package and returns the newly parsed package.
6210     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6211     */
6212    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6213            long currentTime, UserHandle user) throws PackageManagerException {
6214        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6215        parseFlags |= mDefParseFlags;
6216        PackageParser pp = new PackageParser();
6217        pp.setSeparateProcesses(mSeparateProcesses);
6218        pp.setOnlyCoreApps(mOnlyCore);
6219        pp.setDisplayMetrics(mMetrics);
6220
6221        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6222            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6223        }
6224
6225        final PackageParser.Package pkg;
6226        try {
6227            pkg = pp.parsePackage(scanFile, parseFlags);
6228        } catch (PackageParserException e) {
6229            throw PackageManagerException.from(e);
6230        }
6231
6232        PackageSetting ps = null;
6233        PackageSetting updatedPkg;
6234        // reader
6235        synchronized (mPackages) {
6236            // Look to see if we already know about this package.
6237            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6238            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6239                // This package has been renamed to its original name.  Let's
6240                // use that.
6241                ps = mSettings.peekPackageLPr(oldName);
6242            }
6243            // If there was no original package, see one for the real package name.
6244            if (ps == null) {
6245                ps = mSettings.peekPackageLPr(pkg.packageName);
6246            }
6247            // Check to see if this package could be hiding/updating a system
6248            // package.  Must look for it either under the original or real
6249            // package name depending on our state.
6250            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6251            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6252        }
6253        boolean updatedPkgBetter = false;
6254        // First check if this is a system package that may involve an update
6255        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6256            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6257            // it needs to drop FLAG_PRIVILEGED.
6258            if (locationIsPrivileged(scanFile)) {
6259                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6260            } else {
6261                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6262            }
6263
6264            if (ps != null && !ps.codePath.equals(scanFile)) {
6265                // The path has changed from what was last scanned...  check the
6266                // version of the new path against what we have stored to determine
6267                // what to do.
6268                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6269                if (pkg.mVersionCode <= ps.versionCode) {
6270                    // The system package has been updated and the code path does not match
6271                    // Ignore entry. Skip it.
6272                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6273                            + " ignored: updated version " + ps.versionCode
6274                            + " better than this " + pkg.mVersionCode);
6275                    if (!updatedPkg.codePath.equals(scanFile)) {
6276                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6277                                + ps.name + " changing from " + updatedPkg.codePathString
6278                                + " to " + scanFile);
6279                        updatedPkg.codePath = scanFile;
6280                        updatedPkg.codePathString = scanFile.toString();
6281                        updatedPkg.resourcePath = scanFile;
6282                        updatedPkg.resourcePathString = scanFile.toString();
6283                    }
6284                    updatedPkg.pkg = pkg;
6285                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6286                            "Package " + ps.name + " at " + scanFile
6287                                    + " ignored: updated version " + ps.versionCode
6288                                    + " better than this " + pkg.mVersionCode);
6289                } else {
6290                    // The current app on the system partition is better than
6291                    // what we have updated to on the data partition; switch
6292                    // back to the system partition version.
6293                    // At this point, its safely assumed that package installation for
6294                    // apps in system partition will go through. If not there won't be a working
6295                    // version of the app
6296                    // writer
6297                    synchronized (mPackages) {
6298                        // Just remove the loaded entries from package lists.
6299                        mPackages.remove(ps.name);
6300                    }
6301
6302                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6303                            + " reverting from " + ps.codePathString
6304                            + ": new version " + pkg.mVersionCode
6305                            + " better than installed " + ps.versionCode);
6306
6307                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6308                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6309                    synchronized (mInstallLock) {
6310                        args.cleanUpResourcesLI();
6311                    }
6312                    synchronized (mPackages) {
6313                        mSettings.enableSystemPackageLPw(ps.name);
6314                    }
6315                    updatedPkgBetter = true;
6316                }
6317            }
6318        }
6319
6320        if (updatedPkg != null) {
6321            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6322            // initially
6323            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6324
6325            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6326            // flag set initially
6327            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6328                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6329            }
6330        }
6331
6332        // Verify certificates against what was last scanned
6333        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6334
6335        /*
6336         * A new system app appeared, but we already had a non-system one of the
6337         * same name installed earlier.
6338         */
6339        boolean shouldHideSystemApp = false;
6340        if (updatedPkg == null && ps != null
6341                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6342            /*
6343             * Check to make sure the signatures match first. If they don't,
6344             * wipe the installed application and its data.
6345             */
6346            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6347                    != PackageManager.SIGNATURE_MATCH) {
6348                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6349                        + " signatures don't match existing userdata copy; removing");
6350                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6351                ps = null;
6352            } else {
6353                /*
6354                 * If the newly-added system app is an older version than the
6355                 * already installed version, hide it. It will be scanned later
6356                 * and re-added like an update.
6357                 */
6358                if (pkg.mVersionCode <= ps.versionCode) {
6359                    shouldHideSystemApp = true;
6360                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6361                            + " but new version " + pkg.mVersionCode + " better than installed "
6362                            + ps.versionCode + "; hiding system");
6363                } else {
6364                    /*
6365                     * The newly found system app is a newer version that the
6366                     * one previously installed. Simply remove the
6367                     * already-installed application and replace it with our own
6368                     * while keeping the application data.
6369                     */
6370                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6371                            + " reverting from " + ps.codePathString + ": new version "
6372                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6373                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6374                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6375                    synchronized (mInstallLock) {
6376                        args.cleanUpResourcesLI();
6377                    }
6378                }
6379            }
6380        }
6381
6382        // The apk is forward locked (not public) if its code and resources
6383        // are kept in different files. (except for app in either system or
6384        // vendor path).
6385        // TODO grab this value from PackageSettings
6386        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6387            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6388                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6389            }
6390        }
6391
6392        // TODO: extend to support forward-locked splits
6393        String resourcePath = null;
6394        String baseResourcePath = null;
6395        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6396            if (ps != null && ps.resourcePathString != null) {
6397                resourcePath = ps.resourcePathString;
6398                baseResourcePath = ps.resourcePathString;
6399            } else {
6400                // Should not happen at all. Just log an error.
6401                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6402            }
6403        } else {
6404            resourcePath = pkg.codePath;
6405            baseResourcePath = pkg.baseCodePath;
6406        }
6407
6408        // Set application objects path explicitly.
6409        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6410        pkg.applicationInfo.setCodePath(pkg.codePath);
6411        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6412        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6413        pkg.applicationInfo.setResourcePath(resourcePath);
6414        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6415        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6416
6417        // Note that we invoke the following method only if we are about to unpack an application
6418        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6419                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6420
6421        /*
6422         * If the system app should be overridden by a previously installed
6423         * data, hide the system app now and let the /data/app scan pick it up
6424         * again.
6425         */
6426        if (shouldHideSystemApp) {
6427            synchronized (mPackages) {
6428                mSettings.disableSystemPackageLPw(pkg.packageName);
6429            }
6430        }
6431
6432        return scannedPkg;
6433    }
6434
6435    private static String fixProcessName(String defProcessName,
6436            String processName, int uid) {
6437        if (processName == null) {
6438            return defProcessName;
6439        }
6440        return processName;
6441    }
6442
6443    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6444            throws PackageManagerException {
6445        if (pkgSetting.signatures.mSignatures != null) {
6446            // Already existing package. Make sure signatures match
6447            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6448                    == PackageManager.SIGNATURE_MATCH;
6449            if (!match) {
6450                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6451                        == PackageManager.SIGNATURE_MATCH;
6452            }
6453            if (!match) {
6454                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6455                        == PackageManager.SIGNATURE_MATCH;
6456            }
6457            if (!match) {
6458                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6459                        + pkg.packageName + " signatures do not match the "
6460                        + "previously installed version; ignoring!");
6461            }
6462        }
6463
6464        // Check for shared user signatures
6465        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6466            // Already existing package. Make sure signatures match
6467            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6468                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6469            if (!match) {
6470                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6471                        == PackageManager.SIGNATURE_MATCH;
6472            }
6473            if (!match) {
6474                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6475                        == PackageManager.SIGNATURE_MATCH;
6476            }
6477            if (!match) {
6478                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6479                        "Package " + pkg.packageName
6480                        + " has no signatures that match those in shared user "
6481                        + pkgSetting.sharedUser.name + "; ignoring!");
6482            }
6483        }
6484    }
6485
6486    /**
6487     * Enforces that only the system UID or root's UID can call a method exposed
6488     * via Binder.
6489     *
6490     * @param message used as message if SecurityException is thrown
6491     * @throws SecurityException if the caller is not system or root
6492     */
6493    private static final void enforceSystemOrRoot(String message) {
6494        final int uid = Binder.getCallingUid();
6495        if (uid != Process.SYSTEM_UID && uid != 0) {
6496            throw new SecurityException(message);
6497        }
6498    }
6499
6500    @Override
6501    public void performFstrimIfNeeded() {
6502        enforceSystemOrRoot("Only the system can request fstrim");
6503
6504        // Before everything else, see whether we need to fstrim.
6505        try {
6506            IMountService ms = PackageHelper.getMountService();
6507            if (ms != null) {
6508                final boolean isUpgrade = isUpgrade();
6509                boolean doTrim = isUpgrade;
6510                if (doTrim) {
6511                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6512                } else {
6513                    final long interval = android.provider.Settings.Global.getLong(
6514                            mContext.getContentResolver(),
6515                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6516                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6517                    if (interval > 0) {
6518                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6519                        if (timeSinceLast > interval) {
6520                            doTrim = true;
6521                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6522                                    + "; running immediately");
6523                        }
6524                    }
6525                }
6526                if (doTrim) {
6527                    if (!isFirstBoot()) {
6528                        try {
6529                            ActivityManagerNative.getDefault().showBootMessage(
6530                                    mContext.getResources().getString(
6531                                            R.string.android_upgrading_fstrim), true);
6532                        } catch (RemoteException e) {
6533                        }
6534                    }
6535                    ms.runMaintenance();
6536                }
6537            } else {
6538                Slog.e(TAG, "Mount service unavailable!");
6539            }
6540        } catch (RemoteException e) {
6541            // Can't happen; MountService is local
6542        }
6543    }
6544
6545    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6546        List<ResolveInfo> ris = null;
6547        try {
6548            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6549                    intent, null, 0, userId);
6550        } catch (RemoteException e) {
6551        }
6552        ArraySet<String> pkgNames = new ArraySet<String>();
6553        if (ris != null) {
6554            for (ResolveInfo ri : ris) {
6555                pkgNames.add(ri.activityInfo.packageName);
6556            }
6557        }
6558        return pkgNames;
6559    }
6560
6561    @Override
6562    public void notifyPackageUse(String packageName) {
6563        synchronized (mPackages) {
6564            PackageParser.Package p = mPackages.get(packageName);
6565            if (p == null) {
6566                return;
6567            }
6568            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6569        }
6570    }
6571
6572    @Override
6573    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6574        return performDexOptTraced(packageName, instructionSet);
6575    }
6576
6577    public boolean performDexOpt(String packageName, String instructionSet) {
6578        return performDexOptTraced(packageName, instructionSet);
6579    }
6580
6581    private boolean performDexOptTraced(String packageName, String instructionSet) {
6582        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6583        try {
6584            return performDexOptInternal(packageName, instructionSet);
6585        } finally {
6586            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6587        }
6588    }
6589
6590    private boolean performDexOptInternal(String packageName, String instructionSet) {
6591        PackageParser.Package p;
6592        final String targetInstructionSet;
6593        synchronized (mPackages) {
6594            p = mPackages.get(packageName);
6595            if (p == null) {
6596                return false;
6597            }
6598            mPackageUsage.write(false);
6599
6600            targetInstructionSet = instructionSet != null ? instructionSet :
6601                    getPrimaryInstructionSet(p.applicationInfo);
6602            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6603                return false;
6604            }
6605        }
6606        long callingId = Binder.clearCallingIdentity();
6607        try {
6608            synchronized (mInstallLock) {
6609                final String[] instructionSets = new String[] { targetInstructionSet };
6610                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6611                        true /* inclDependencies */);
6612                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6613            }
6614        } finally {
6615            Binder.restoreCallingIdentity(callingId);
6616        }
6617    }
6618
6619    public ArraySet<String> getPackagesThatNeedDexOpt() {
6620        ArraySet<String> pkgs = null;
6621        synchronized (mPackages) {
6622            for (PackageParser.Package p : mPackages.values()) {
6623                if (DEBUG_DEXOPT) {
6624                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6625                }
6626                if (!p.mDexOptPerformed.isEmpty()) {
6627                    continue;
6628                }
6629                if (pkgs == null) {
6630                    pkgs = new ArraySet<String>();
6631                }
6632                pkgs.add(p.packageName);
6633            }
6634        }
6635        return pkgs;
6636    }
6637
6638    public void shutdown() {
6639        mPackageUsage.write(true);
6640    }
6641
6642    @Override
6643    public void forceDexOpt(String packageName) {
6644        enforceSystemOrRoot("forceDexOpt");
6645
6646        PackageParser.Package pkg;
6647        synchronized (mPackages) {
6648            pkg = mPackages.get(packageName);
6649            if (pkg == null) {
6650                throw new IllegalArgumentException("Missing package: " + packageName);
6651            }
6652        }
6653
6654        synchronized (mInstallLock) {
6655            final String[] instructionSets = new String[] {
6656                    getPrimaryInstructionSet(pkg.applicationInfo) };
6657
6658            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6659
6660            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6661                    true /* inclDependencies */);
6662
6663            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6664            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6665                throw new IllegalStateException("Failed to dexopt: " + res);
6666            }
6667        }
6668    }
6669
6670    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6671        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6672            Slog.w(TAG, "Unable to update from " + oldPkg.name
6673                    + " to " + newPkg.packageName
6674                    + ": old package not in system partition");
6675            return false;
6676        } else if (mPackages.get(oldPkg.name) != null) {
6677            Slog.w(TAG, "Unable to update from " + oldPkg.name
6678                    + " to " + newPkg.packageName
6679                    + ": old package still exists");
6680            return false;
6681        }
6682        return true;
6683    }
6684
6685    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6686            throws PackageManagerException {
6687        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6688        if (res != 0) {
6689            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6690                    "Failed to install " + packageName + ": " + res);
6691        }
6692
6693        final int[] users = sUserManager.getUserIds();
6694        for (int user : users) {
6695            if (user != 0) {
6696                res = mInstaller.createUserData(volumeUuid, packageName,
6697                        UserHandle.getUid(user, uid), user, seinfo);
6698                if (res != 0) {
6699                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6700                            "Failed to createUserData " + packageName + ": " + res);
6701                }
6702            }
6703        }
6704    }
6705
6706    private int removeDataDirsLI(String volumeUuid, String packageName) {
6707        int[] users = sUserManager.getUserIds();
6708        int res = 0;
6709        for (int user : users) {
6710            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6711            if (resInner < 0) {
6712                res = resInner;
6713            }
6714        }
6715
6716        return res;
6717    }
6718
6719    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6720        int[] users = sUserManager.getUserIds();
6721        int res = 0;
6722        for (int user : users) {
6723            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6724            if (resInner < 0) {
6725                res = resInner;
6726            }
6727        }
6728        return res;
6729    }
6730
6731    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6732            PackageParser.Package changingLib) {
6733        if (file.path != null) {
6734            usesLibraryFiles.add(file.path);
6735            return;
6736        }
6737        PackageParser.Package p = mPackages.get(file.apk);
6738        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6739            // If we are doing this while in the middle of updating a library apk,
6740            // then we need to make sure to use that new apk for determining the
6741            // dependencies here.  (We haven't yet finished committing the new apk
6742            // to the package manager state.)
6743            if (p == null || p.packageName.equals(changingLib.packageName)) {
6744                p = changingLib;
6745            }
6746        }
6747        if (p != null) {
6748            usesLibraryFiles.addAll(p.getAllCodePaths());
6749        }
6750    }
6751
6752    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6753            PackageParser.Package changingLib) throws PackageManagerException {
6754        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6755            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6756            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6757            for (int i=0; i<N; i++) {
6758                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6759                if (file == null) {
6760                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6761                            "Package " + pkg.packageName + " requires unavailable shared library "
6762                            + pkg.usesLibraries.get(i) + "; failing!");
6763                }
6764                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6765            }
6766            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6767            for (int i=0; i<N; i++) {
6768                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6769                if (file == null) {
6770                    Slog.w(TAG, "Package " + pkg.packageName
6771                            + " desires unavailable shared library "
6772                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6773                } else {
6774                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6775                }
6776            }
6777            N = usesLibraryFiles.size();
6778            if (N > 0) {
6779                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6780            } else {
6781                pkg.usesLibraryFiles = null;
6782            }
6783        }
6784    }
6785
6786    private static boolean hasString(List<String> list, List<String> which) {
6787        if (list == null) {
6788            return false;
6789        }
6790        for (int i=list.size()-1; i>=0; i--) {
6791            for (int j=which.size()-1; j>=0; j--) {
6792                if (which.get(j).equals(list.get(i))) {
6793                    return true;
6794                }
6795            }
6796        }
6797        return false;
6798    }
6799
6800    private void updateAllSharedLibrariesLPw() {
6801        for (PackageParser.Package pkg : mPackages.values()) {
6802            try {
6803                updateSharedLibrariesLPw(pkg, null);
6804            } catch (PackageManagerException e) {
6805                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6806            }
6807        }
6808    }
6809
6810    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6811            PackageParser.Package changingPkg) {
6812        ArrayList<PackageParser.Package> res = null;
6813        for (PackageParser.Package pkg : mPackages.values()) {
6814            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6815                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6816                if (res == null) {
6817                    res = new ArrayList<PackageParser.Package>();
6818                }
6819                res.add(pkg);
6820                try {
6821                    updateSharedLibrariesLPw(pkg, changingPkg);
6822                } catch (PackageManagerException e) {
6823                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6824                }
6825            }
6826        }
6827        return res;
6828    }
6829
6830    /**
6831     * Derive the value of the {@code cpuAbiOverride} based on the provided
6832     * value and an optional stored value from the package settings.
6833     */
6834    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6835        String cpuAbiOverride = null;
6836
6837        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6838            cpuAbiOverride = null;
6839        } else if (abiOverride != null) {
6840            cpuAbiOverride = abiOverride;
6841        } else if (settings != null) {
6842            cpuAbiOverride = settings.cpuAbiOverrideString;
6843        }
6844
6845        return cpuAbiOverride;
6846    }
6847
6848    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6849            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6850        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6851        try {
6852            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6853        } finally {
6854            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6855        }
6856    }
6857
6858    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6859            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6860        boolean success = false;
6861        try {
6862            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6863                    currentTime, user);
6864            success = true;
6865            return res;
6866        } finally {
6867            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6868                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6869            }
6870        }
6871    }
6872
6873    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6874            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6875        final File scanFile = new File(pkg.codePath);
6876        if (pkg.applicationInfo.getCodePath() == null ||
6877                pkg.applicationInfo.getResourcePath() == null) {
6878            // Bail out. The resource and code paths haven't been set.
6879            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6880                    "Code and resource paths haven't been set correctly");
6881        }
6882
6883        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6884            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6885        } else {
6886            // Only allow system apps to be flagged as core apps.
6887            pkg.coreApp = false;
6888        }
6889
6890        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6891            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6892        }
6893
6894        if (mCustomResolverComponentName != null &&
6895                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6896            setUpCustomResolverActivity(pkg);
6897        }
6898
6899        if (pkg.packageName.equals("android")) {
6900            synchronized (mPackages) {
6901                if (mAndroidApplication != null) {
6902                    Slog.w(TAG, "*************************************************");
6903                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6904                    Slog.w(TAG, " file=" + scanFile);
6905                    Slog.w(TAG, "*************************************************");
6906                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6907                            "Core android package being redefined.  Skipping.");
6908                }
6909
6910                // Set up information for our fall-back user intent resolution activity.
6911                mPlatformPackage = pkg;
6912                pkg.mVersionCode = mSdkVersion;
6913                mAndroidApplication = pkg.applicationInfo;
6914
6915                if (!mResolverReplaced) {
6916                    mResolveActivity.applicationInfo = mAndroidApplication;
6917                    mResolveActivity.name = ResolverActivity.class.getName();
6918                    mResolveActivity.packageName = mAndroidApplication.packageName;
6919                    mResolveActivity.processName = "system:ui";
6920                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6921                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6922                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6923                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6924                    mResolveActivity.exported = true;
6925                    mResolveActivity.enabled = true;
6926                    mResolveInfo.activityInfo = mResolveActivity;
6927                    mResolveInfo.priority = 0;
6928                    mResolveInfo.preferredOrder = 0;
6929                    mResolveInfo.match = 0;
6930                    mResolveComponentName = new ComponentName(
6931                            mAndroidApplication.packageName, mResolveActivity.name);
6932                }
6933            }
6934        }
6935
6936        if (DEBUG_PACKAGE_SCANNING) {
6937            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6938                Log.d(TAG, "Scanning package " + pkg.packageName);
6939        }
6940
6941        if (mPackages.containsKey(pkg.packageName)
6942                || mSharedLibraries.containsKey(pkg.packageName)) {
6943            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6944                    "Application package " + pkg.packageName
6945                    + " already installed.  Skipping duplicate.");
6946        }
6947
6948        // If we're only installing presumed-existing packages, require that the
6949        // scanned APK is both already known and at the path previously established
6950        // for it.  Previously unknown packages we pick up normally, but if we have an
6951        // a priori expectation about this package's install presence, enforce it.
6952        // With a singular exception for new system packages. When an OTA contains
6953        // a new system package, we allow the codepath to change from a system location
6954        // to the user-installed location. If we don't allow this change, any newer,
6955        // user-installed version of the application will be ignored.
6956        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6957            if (mExpectingBetter.containsKey(pkg.packageName)) {
6958                logCriticalInfo(Log.WARN,
6959                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6960            } else {
6961                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6962                if (known != null) {
6963                    if (DEBUG_PACKAGE_SCANNING) {
6964                        Log.d(TAG, "Examining " + pkg.codePath
6965                                + " and requiring known paths " + known.codePathString
6966                                + " & " + known.resourcePathString);
6967                    }
6968                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6969                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6970                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6971                                "Application package " + pkg.packageName
6972                                + " found at " + pkg.applicationInfo.getCodePath()
6973                                + " but expected at " + known.codePathString + "; ignoring.");
6974                    }
6975                }
6976            }
6977        }
6978
6979        // Initialize package source and resource directories
6980        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6981        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6982
6983        SharedUserSetting suid = null;
6984        PackageSetting pkgSetting = null;
6985
6986        if (!isSystemApp(pkg)) {
6987            // Only system apps can use these features.
6988            pkg.mOriginalPackages = null;
6989            pkg.mRealPackage = null;
6990            pkg.mAdoptPermissions = null;
6991        }
6992
6993        // writer
6994        synchronized (mPackages) {
6995            if (pkg.mSharedUserId != null) {
6996                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6997                if (suid == null) {
6998                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6999                            "Creating application package " + pkg.packageName
7000                            + " for shared user failed");
7001                }
7002                if (DEBUG_PACKAGE_SCANNING) {
7003                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7004                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7005                                + "): packages=" + suid.packages);
7006                }
7007            }
7008
7009            // Check if we are renaming from an original package name.
7010            PackageSetting origPackage = null;
7011            String realName = null;
7012            if (pkg.mOriginalPackages != null) {
7013                // This package may need to be renamed to a previously
7014                // installed name.  Let's check on that...
7015                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7016                if (pkg.mOriginalPackages.contains(renamed)) {
7017                    // This package had originally been installed as the
7018                    // original name, and we have already taken care of
7019                    // transitioning to the new one.  Just update the new
7020                    // one to continue using the old name.
7021                    realName = pkg.mRealPackage;
7022                    if (!pkg.packageName.equals(renamed)) {
7023                        // Callers into this function may have already taken
7024                        // care of renaming the package; only do it here if
7025                        // it is not already done.
7026                        pkg.setPackageName(renamed);
7027                    }
7028
7029                } else {
7030                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7031                        if ((origPackage = mSettings.peekPackageLPr(
7032                                pkg.mOriginalPackages.get(i))) != null) {
7033                            // We do have the package already installed under its
7034                            // original name...  should we use it?
7035                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7036                                // New package is not compatible with original.
7037                                origPackage = null;
7038                                continue;
7039                            } else if (origPackage.sharedUser != null) {
7040                                // Make sure uid is compatible between packages.
7041                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7042                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7043                                            + " to " + pkg.packageName + ": old uid "
7044                                            + origPackage.sharedUser.name
7045                                            + " differs from " + pkg.mSharedUserId);
7046                                    origPackage = null;
7047                                    continue;
7048                                }
7049                            } else {
7050                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7051                                        + pkg.packageName + " to old name " + origPackage.name);
7052                            }
7053                            break;
7054                        }
7055                    }
7056                }
7057            }
7058
7059            if (mTransferedPackages.contains(pkg.packageName)) {
7060                Slog.w(TAG, "Package " + pkg.packageName
7061                        + " was transferred to another, but its .apk remains");
7062            }
7063
7064            // Just create the setting, don't add it yet. For already existing packages
7065            // the PkgSetting exists already and doesn't have to be created.
7066            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7067                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7068                    pkg.applicationInfo.primaryCpuAbi,
7069                    pkg.applicationInfo.secondaryCpuAbi,
7070                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7071                    user, false);
7072            if (pkgSetting == null) {
7073                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7074                        "Creating application package " + pkg.packageName + " failed");
7075            }
7076
7077            if (pkgSetting.origPackage != null) {
7078                // If we are first transitioning from an original package,
7079                // fix up the new package's name now.  We need to do this after
7080                // looking up the package under its new name, so getPackageLP
7081                // can take care of fiddling things correctly.
7082                pkg.setPackageName(origPackage.name);
7083
7084                // File a report about this.
7085                String msg = "New package " + pkgSetting.realName
7086                        + " renamed to replace old package " + pkgSetting.name;
7087                reportSettingsProblem(Log.WARN, msg);
7088
7089                // Make a note of it.
7090                mTransferedPackages.add(origPackage.name);
7091
7092                // No longer need to retain this.
7093                pkgSetting.origPackage = null;
7094            }
7095
7096            if (realName != null) {
7097                // Make a note of it.
7098                mTransferedPackages.add(pkg.packageName);
7099            }
7100
7101            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7102                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7103            }
7104
7105            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7106                // Check all shared libraries and map to their actual file path.
7107                // We only do this here for apps not on a system dir, because those
7108                // are the only ones that can fail an install due to this.  We
7109                // will take care of the system apps by updating all of their
7110                // library paths after the scan is done.
7111                updateSharedLibrariesLPw(pkg, null);
7112            }
7113
7114            if (mFoundPolicyFile) {
7115                SELinuxMMAC.assignSeinfoValue(pkg);
7116            }
7117
7118            pkg.applicationInfo.uid = pkgSetting.appId;
7119            pkg.mExtras = pkgSetting;
7120            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7121                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7122                    // We just determined the app is signed correctly, so bring
7123                    // over the latest parsed certs.
7124                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7125                } else {
7126                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7127                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7128                                "Package " + pkg.packageName + " upgrade keys do not match the "
7129                                + "previously installed version");
7130                    } else {
7131                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7132                        String msg = "System package " + pkg.packageName
7133                            + " signature changed; retaining data.";
7134                        reportSettingsProblem(Log.WARN, msg);
7135                    }
7136                }
7137            } else {
7138                try {
7139                    verifySignaturesLP(pkgSetting, pkg);
7140                    // We just determined the app is signed correctly, so bring
7141                    // over the latest parsed certs.
7142                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7143                } catch (PackageManagerException e) {
7144                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7145                        throw e;
7146                    }
7147                    // The signature has changed, but this package is in the system
7148                    // image...  let's recover!
7149                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7150                    // However...  if this package is part of a shared user, but it
7151                    // doesn't match the signature of the shared user, let's fail.
7152                    // What this means is that you can't change the signatures
7153                    // associated with an overall shared user, which doesn't seem all
7154                    // that unreasonable.
7155                    if (pkgSetting.sharedUser != null) {
7156                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7157                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7158                            throw new PackageManagerException(
7159                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7160                                            "Signature mismatch for shared user : "
7161                                            + pkgSetting.sharedUser);
7162                        }
7163                    }
7164                    // File a report about this.
7165                    String msg = "System package " + pkg.packageName
7166                        + " signature changed; retaining data.";
7167                    reportSettingsProblem(Log.WARN, msg);
7168                }
7169            }
7170            // Verify that this new package doesn't have any content providers
7171            // that conflict with existing packages.  Only do this if the
7172            // package isn't already installed, since we don't want to break
7173            // things that are installed.
7174            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7175                final int N = pkg.providers.size();
7176                int i;
7177                for (i=0; i<N; i++) {
7178                    PackageParser.Provider p = pkg.providers.get(i);
7179                    if (p.info.authority != null) {
7180                        String names[] = p.info.authority.split(";");
7181                        for (int j = 0; j < names.length; j++) {
7182                            if (mProvidersByAuthority.containsKey(names[j])) {
7183                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7184                                final String otherPackageName =
7185                                        ((other != null && other.getComponentName() != null) ?
7186                                                other.getComponentName().getPackageName() : "?");
7187                                throw new PackageManagerException(
7188                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7189                                                "Can't install because provider name " + names[j]
7190                                                + " (in package " + pkg.applicationInfo.packageName
7191                                                + ") is already used by " + otherPackageName);
7192                            }
7193                        }
7194                    }
7195                }
7196            }
7197
7198            if (pkg.mAdoptPermissions != null) {
7199                // This package wants to adopt ownership of permissions from
7200                // another package.
7201                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7202                    final String origName = pkg.mAdoptPermissions.get(i);
7203                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7204                    if (orig != null) {
7205                        if (verifyPackageUpdateLPr(orig, pkg)) {
7206                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7207                                    + pkg.packageName);
7208                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7209                        }
7210                    }
7211                }
7212            }
7213        }
7214
7215        final String pkgName = pkg.packageName;
7216
7217        final long scanFileTime = scanFile.lastModified();
7218        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7219        pkg.applicationInfo.processName = fixProcessName(
7220                pkg.applicationInfo.packageName,
7221                pkg.applicationInfo.processName,
7222                pkg.applicationInfo.uid);
7223
7224        if (pkg != mPlatformPackage) {
7225            // This is a normal package, need to make its data directory.
7226            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7227                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7228
7229            boolean uidError = false;
7230            if (dataPath.exists()) {
7231                int currentUid = 0;
7232                try {
7233                    StructStat stat = Os.stat(dataPath.getPath());
7234                    currentUid = stat.st_uid;
7235                } catch (ErrnoException e) {
7236                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7237                }
7238
7239                // If we have mismatched owners for the data path, we have a problem.
7240                if (currentUid != pkg.applicationInfo.uid) {
7241                    boolean recovered = false;
7242                    if (currentUid == 0) {
7243                        // The directory somehow became owned by root.  Wow.
7244                        // This is probably because the system was stopped while
7245                        // installd was in the middle of messing with its libs
7246                        // directory.  Ask installd to fix that.
7247                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7248                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7249                        if (ret >= 0) {
7250                            recovered = true;
7251                            String msg = "Package " + pkg.packageName
7252                                    + " unexpectedly changed to uid 0; recovered to " +
7253                                    + pkg.applicationInfo.uid;
7254                            reportSettingsProblem(Log.WARN, msg);
7255                        }
7256                    }
7257                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7258                            || (scanFlags&SCAN_BOOTING) != 0)) {
7259                        // If this is a system app, we can at least delete its
7260                        // current data so the application will still work.
7261                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7262                        if (ret >= 0) {
7263                            // TODO: Kill the processes first
7264                            // Old data gone!
7265                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7266                                    ? "System package " : "Third party package ";
7267                            String msg = prefix + pkg.packageName
7268                                    + " has changed from uid: "
7269                                    + currentUid + " to "
7270                                    + pkg.applicationInfo.uid + "; old data erased";
7271                            reportSettingsProblem(Log.WARN, msg);
7272                            recovered = true;
7273                        }
7274                        if (!recovered) {
7275                            mHasSystemUidErrors = true;
7276                        }
7277                    } else if (!recovered) {
7278                        // If we allow this install to proceed, we will be broken.
7279                        // Abort, abort!
7280                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7281                                "scanPackageLI");
7282                    }
7283                    if (!recovered) {
7284                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7285                            + pkg.applicationInfo.uid + "/fs_"
7286                            + currentUid;
7287                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7288                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7289                        String msg = "Package " + pkg.packageName
7290                                + " has mismatched uid: "
7291                                + currentUid + " on disk, "
7292                                + pkg.applicationInfo.uid + " in settings";
7293                        // writer
7294                        synchronized (mPackages) {
7295                            mSettings.mReadMessages.append(msg);
7296                            mSettings.mReadMessages.append('\n');
7297                            uidError = true;
7298                            if (!pkgSetting.uidError) {
7299                                reportSettingsProblem(Log.ERROR, msg);
7300                            }
7301                        }
7302                    }
7303                }
7304
7305                // Ensure that directories are prepared
7306                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7307                        pkg.applicationInfo.seinfo);
7308
7309                if (mShouldRestoreconData) {
7310                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7311                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7312                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7313                }
7314            } else {
7315                if (DEBUG_PACKAGE_SCANNING) {
7316                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7317                        Log.v(TAG, "Want this data dir: " + dataPath);
7318                }
7319                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7320                        pkg.applicationInfo.seinfo);
7321            }
7322
7323            // Get all of our default paths setup
7324            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7325
7326            pkgSetting.uidError = uidError;
7327        }
7328
7329        final String path = scanFile.getPath();
7330        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7331
7332        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7333            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7334
7335            // Some system apps still use directory structure for native libraries
7336            // in which case we might end up not detecting abi solely based on apk
7337            // structure. Try to detect abi based on directory structure.
7338            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7339                    pkg.applicationInfo.primaryCpuAbi == null) {
7340                setBundledAppAbisAndRoots(pkg, pkgSetting);
7341                setNativeLibraryPaths(pkg);
7342            }
7343
7344        } else {
7345            if ((scanFlags & SCAN_MOVE) != 0) {
7346                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7347                // but we already have this packages package info in the PackageSetting. We just
7348                // use that and derive the native library path based on the new codepath.
7349                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7350                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7351            }
7352
7353            // Set native library paths again. For moves, the path will be updated based on the
7354            // ABIs we've determined above. For non-moves, the path will be updated based on the
7355            // ABIs we determined during compilation, but the path will depend on the final
7356            // package path (after the rename away from the stage path).
7357            setNativeLibraryPaths(pkg);
7358        }
7359
7360        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7361        final int[] userIds = sUserManager.getUserIds();
7362        synchronized (mInstallLock) {
7363            // Make sure all user data directories are ready to roll; we're okay
7364            // if they already exist
7365            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7366                for (int userId : userIds) {
7367                    if (userId != UserHandle.USER_SYSTEM) {
7368                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7369                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7370                                pkg.applicationInfo.seinfo);
7371                    }
7372                }
7373            }
7374
7375            // Create a native library symlink only if we have native libraries
7376            // and if the native libraries are 32 bit libraries. We do not provide
7377            // this symlink for 64 bit libraries.
7378            if (pkg.applicationInfo.primaryCpuAbi != null &&
7379                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7380                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7381                try {
7382                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7383                    for (int userId : userIds) {
7384                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7385                                nativeLibPath, userId) < 0) {
7386                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7387                                    "Failed linking native library dir (user=" + userId + ")");
7388                        }
7389                    }
7390                } finally {
7391                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7392                }
7393            }
7394        }
7395
7396        // This is a special case for the "system" package, where the ABI is
7397        // dictated by the zygote configuration (and init.rc). We should keep track
7398        // of this ABI so that we can deal with "normal" applications that run under
7399        // the same UID correctly.
7400        if (mPlatformPackage == pkg) {
7401            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7402                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7403        }
7404
7405        // If there's a mismatch between the abi-override in the package setting
7406        // and the abiOverride specified for the install. Warn about this because we
7407        // would've already compiled the app without taking the package setting into
7408        // account.
7409        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7410            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7411                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7412                        " for package: " + pkg.packageName);
7413            }
7414        }
7415
7416        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7417        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7418        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7419
7420        // Copy the derived override back to the parsed package, so that we can
7421        // update the package settings accordingly.
7422        pkg.cpuAbiOverride = cpuAbiOverride;
7423
7424        if (DEBUG_ABI_SELECTION) {
7425            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7426                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7427                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7428        }
7429
7430        // Push the derived path down into PackageSettings so we know what to
7431        // clean up at uninstall time.
7432        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7433
7434        if (DEBUG_ABI_SELECTION) {
7435            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7436                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7437                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7438        }
7439
7440        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7441            // We don't do this here during boot because we can do it all
7442            // at once after scanning all existing packages.
7443            //
7444            // We also do this *before* we perform dexopt on this package, so that
7445            // we can avoid redundant dexopts, and also to make sure we've got the
7446            // code and package path correct.
7447            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7448                    pkg, true /* boot complete */);
7449        }
7450
7451        if (mFactoryTest && pkg.requestedPermissions.contains(
7452                android.Manifest.permission.FACTORY_TEST)) {
7453            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7454        }
7455
7456        ArrayList<PackageParser.Package> clientLibPkgs = null;
7457
7458        // writer
7459        synchronized (mPackages) {
7460            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7461                // Only system apps can add new shared libraries.
7462                if (pkg.libraryNames != null) {
7463                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7464                        String name = pkg.libraryNames.get(i);
7465                        boolean allowed = false;
7466                        if (pkg.isUpdatedSystemApp()) {
7467                            // New library entries can only be added through the
7468                            // system image.  This is important to get rid of a lot
7469                            // of nasty edge cases: for example if we allowed a non-
7470                            // system update of the app to add a library, then uninstalling
7471                            // the update would make the library go away, and assumptions
7472                            // we made such as through app install filtering would now
7473                            // have allowed apps on the device which aren't compatible
7474                            // with it.  Better to just have the restriction here, be
7475                            // conservative, and create many fewer cases that can negatively
7476                            // impact the user experience.
7477                            final PackageSetting sysPs = mSettings
7478                                    .getDisabledSystemPkgLPr(pkg.packageName);
7479                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7480                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7481                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7482                                        allowed = true;
7483                                        break;
7484                                    }
7485                                }
7486                            }
7487                        } else {
7488                            allowed = true;
7489                        }
7490                        if (allowed) {
7491                            if (!mSharedLibraries.containsKey(name)) {
7492                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7493                            } else if (!name.equals(pkg.packageName)) {
7494                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7495                                        + name + " already exists; skipping");
7496                            }
7497                        } else {
7498                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7499                                    + name + " that is not declared on system image; skipping");
7500                        }
7501                    }
7502                    if ((scanFlags & SCAN_BOOTING) == 0) {
7503                        // If we are not booting, we need to update any applications
7504                        // that are clients of our shared library.  If we are booting,
7505                        // this will all be done once the scan is complete.
7506                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7507                    }
7508                }
7509            }
7510        }
7511
7512        // Request the ActivityManager to kill the process(only for existing packages)
7513        // so that we do not end up in a confused state while the user is still using the older
7514        // version of the application while the new one gets installed.
7515        if ((scanFlags & SCAN_REPLACING) != 0) {
7516            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7517
7518            killApplication(pkg.applicationInfo.packageName,
7519                        pkg.applicationInfo.uid, "replace pkg");
7520
7521            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7522        }
7523
7524        // Also need to kill any apps that are dependent on the library.
7525        if (clientLibPkgs != null) {
7526            for (int i=0; i<clientLibPkgs.size(); i++) {
7527                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7528                killApplication(clientPkg.applicationInfo.packageName,
7529                        clientPkg.applicationInfo.uid, "update lib");
7530            }
7531        }
7532
7533        // Make sure we're not adding any bogus keyset info
7534        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7535        ksms.assertScannedPackageValid(pkg);
7536
7537        // writer
7538        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7539
7540        boolean createIdmapFailed = false;
7541        synchronized (mPackages) {
7542            // We don't expect installation to fail beyond this point
7543
7544            // Add the new setting to mSettings
7545            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7546            // Add the new setting to mPackages
7547            mPackages.put(pkg.applicationInfo.packageName, pkg);
7548            // Make sure we don't accidentally delete its data.
7549            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7550            while (iter.hasNext()) {
7551                PackageCleanItem item = iter.next();
7552                if (pkgName.equals(item.packageName)) {
7553                    iter.remove();
7554                }
7555            }
7556
7557            // Take care of first install / last update times.
7558            if (currentTime != 0) {
7559                if (pkgSetting.firstInstallTime == 0) {
7560                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7561                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7562                    pkgSetting.lastUpdateTime = currentTime;
7563                }
7564            } else if (pkgSetting.firstInstallTime == 0) {
7565                // We need *something*.  Take time time stamp of the file.
7566                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7567            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7568                if (scanFileTime != pkgSetting.timeStamp) {
7569                    // A package on the system image has changed; consider this
7570                    // to be an update.
7571                    pkgSetting.lastUpdateTime = scanFileTime;
7572                }
7573            }
7574
7575            // Add the package's KeySets to the global KeySetManagerService
7576            ksms.addScannedPackageLPw(pkg);
7577
7578            int N = pkg.providers.size();
7579            StringBuilder r = null;
7580            int i;
7581            for (i=0; i<N; i++) {
7582                PackageParser.Provider p = pkg.providers.get(i);
7583                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7584                        p.info.processName, pkg.applicationInfo.uid);
7585                mProviders.addProvider(p);
7586                p.syncable = p.info.isSyncable;
7587                if (p.info.authority != null) {
7588                    String names[] = p.info.authority.split(";");
7589                    p.info.authority = null;
7590                    for (int j = 0; j < names.length; j++) {
7591                        if (j == 1 && p.syncable) {
7592                            // We only want the first authority for a provider to possibly be
7593                            // syncable, so if we already added this provider using a different
7594                            // authority clear the syncable flag. We copy the provider before
7595                            // changing it because the mProviders object contains a reference
7596                            // to a provider that we don't want to change.
7597                            // Only do this for the second authority since the resulting provider
7598                            // object can be the same for all future authorities for this provider.
7599                            p = new PackageParser.Provider(p);
7600                            p.syncable = false;
7601                        }
7602                        if (!mProvidersByAuthority.containsKey(names[j])) {
7603                            mProvidersByAuthority.put(names[j], p);
7604                            if (p.info.authority == null) {
7605                                p.info.authority = names[j];
7606                            } else {
7607                                p.info.authority = p.info.authority + ";" + names[j];
7608                            }
7609                            if (DEBUG_PACKAGE_SCANNING) {
7610                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7611                                    Log.d(TAG, "Registered content provider: " + names[j]
7612                                            + ", className = " + p.info.name + ", isSyncable = "
7613                                            + p.info.isSyncable);
7614                            }
7615                        } else {
7616                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7617                            Slog.w(TAG, "Skipping provider name " + names[j] +
7618                                    " (in package " + pkg.applicationInfo.packageName +
7619                                    "): name already used by "
7620                                    + ((other != null && other.getComponentName() != null)
7621                                            ? other.getComponentName().getPackageName() : "?"));
7622                        }
7623                    }
7624                }
7625                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7626                    if (r == null) {
7627                        r = new StringBuilder(256);
7628                    } else {
7629                        r.append(' ');
7630                    }
7631                    r.append(p.info.name);
7632                }
7633            }
7634            if (r != null) {
7635                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7636            }
7637
7638            N = pkg.services.size();
7639            r = null;
7640            for (i=0; i<N; i++) {
7641                PackageParser.Service s = pkg.services.get(i);
7642                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7643                        s.info.processName, pkg.applicationInfo.uid);
7644                mServices.addService(s);
7645                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7646                    if (r == null) {
7647                        r = new StringBuilder(256);
7648                    } else {
7649                        r.append(' ');
7650                    }
7651                    r.append(s.info.name);
7652                }
7653            }
7654            if (r != null) {
7655                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7656            }
7657
7658            N = pkg.receivers.size();
7659            r = null;
7660            for (i=0; i<N; i++) {
7661                PackageParser.Activity a = pkg.receivers.get(i);
7662                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7663                        a.info.processName, pkg.applicationInfo.uid);
7664                mReceivers.addActivity(a, "receiver");
7665                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7666                    if (r == null) {
7667                        r = new StringBuilder(256);
7668                    } else {
7669                        r.append(' ');
7670                    }
7671                    r.append(a.info.name);
7672                }
7673            }
7674            if (r != null) {
7675                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7676            }
7677
7678            N = pkg.activities.size();
7679            r = null;
7680            for (i=0; i<N; i++) {
7681                PackageParser.Activity a = pkg.activities.get(i);
7682                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7683                        a.info.processName, pkg.applicationInfo.uid);
7684                mActivities.addActivity(a, "activity");
7685                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7686                    if (r == null) {
7687                        r = new StringBuilder(256);
7688                    } else {
7689                        r.append(' ');
7690                    }
7691                    r.append(a.info.name);
7692                }
7693            }
7694            if (r != null) {
7695                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7696            }
7697
7698            N = pkg.permissionGroups.size();
7699            r = null;
7700            for (i=0; i<N; i++) {
7701                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7702                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7703                if (cur == null) {
7704                    mPermissionGroups.put(pg.info.name, pg);
7705                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7706                        if (r == null) {
7707                            r = new StringBuilder(256);
7708                        } else {
7709                            r.append(' ');
7710                        }
7711                        r.append(pg.info.name);
7712                    }
7713                } else {
7714                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7715                            + pg.info.packageName + " ignored: original from "
7716                            + cur.info.packageName);
7717                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7718                        if (r == null) {
7719                            r = new StringBuilder(256);
7720                        } else {
7721                            r.append(' ');
7722                        }
7723                        r.append("DUP:");
7724                        r.append(pg.info.name);
7725                    }
7726                }
7727            }
7728            if (r != null) {
7729                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7730            }
7731
7732            N = pkg.permissions.size();
7733            r = null;
7734            for (i=0; i<N; i++) {
7735                PackageParser.Permission p = pkg.permissions.get(i);
7736
7737                // Assume by default that we did not install this permission into the system.
7738                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7739
7740                // Now that permission groups have a special meaning, we ignore permission
7741                // groups for legacy apps to prevent unexpected behavior. In particular,
7742                // permissions for one app being granted to someone just becuase they happen
7743                // to be in a group defined by another app (before this had no implications).
7744                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7745                    p.group = mPermissionGroups.get(p.info.group);
7746                    // Warn for a permission in an unknown group.
7747                    if (p.info.group != null && p.group == null) {
7748                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7749                                + p.info.packageName + " in an unknown group " + p.info.group);
7750                    }
7751                }
7752
7753                ArrayMap<String, BasePermission> permissionMap =
7754                        p.tree ? mSettings.mPermissionTrees
7755                                : mSettings.mPermissions;
7756                BasePermission bp = permissionMap.get(p.info.name);
7757
7758                // Allow system apps to redefine non-system permissions
7759                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7760                    final boolean currentOwnerIsSystem = (bp.perm != null
7761                            && isSystemApp(bp.perm.owner));
7762                    if (isSystemApp(p.owner)) {
7763                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7764                            // It's a built-in permission and no owner, take ownership now
7765                            bp.packageSetting = pkgSetting;
7766                            bp.perm = p;
7767                            bp.uid = pkg.applicationInfo.uid;
7768                            bp.sourcePackage = p.info.packageName;
7769                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7770                        } else if (!currentOwnerIsSystem) {
7771                            String msg = "New decl " + p.owner + " of permission  "
7772                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7773                            reportSettingsProblem(Log.WARN, msg);
7774                            bp = null;
7775                        }
7776                    }
7777                }
7778
7779                if (bp == null) {
7780                    bp = new BasePermission(p.info.name, p.info.packageName,
7781                            BasePermission.TYPE_NORMAL);
7782                    permissionMap.put(p.info.name, bp);
7783                }
7784
7785                if (bp.perm == null) {
7786                    if (bp.sourcePackage == null
7787                            || bp.sourcePackage.equals(p.info.packageName)) {
7788                        BasePermission tree = findPermissionTreeLP(p.info.name);
7789                        if (tree == null
7790                                || tree.sourcePackage.equals(p.info.packageName)) {
7791                            bp.packageSetting = pkgSetting;
7792                            bp.perm = p;
7793                            bp.uid = pkg.applicationInfo.uid;
7794                            bp.sourcePackage = p.info.packageName;
7795                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7796                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7797                                if (r == null) {
7798                                    r = new StringBuilder(256);
7799                                } else {
7800                                    r.append(' ');
7801                                }
7802                                r.append(p.info.name);
7803                            }
7804                        } else {
7805                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7806                                    + p.info.packageName + " ignored: base tree "
7807                                    + tree.name + " is from package "
7808                                    + tree.sourcePackage);
7809                        }
7810                    } else {
7811                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7812                                + p.info.packageName + " ignored: original from "
7813                                + bp.sourcePackage);
7814                    }
7815                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7816                    if (r == null) {
7817                        r = new StringBuilder(256);
7818                    } else {
7819                        r.append(' ');
7820                    }
7821                    r.append("DUP:");
7822                    r.append(p.info.name);
7823                }
7824                if (bp.perm == p) {
7825                    bp.protectionLevel = p.info.protectionLevel;
7826                }
7827            }
7828
7829            if (r != null) {
7830                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7831            }
7832
7833            N = pkg.instrumentation.size();
7834            r = null;
7835            for (i=0; i<N; i++) {
7836                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7837                a.info.packageName = pkg.applicationInfo.packageName;
7838                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7839                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7840                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7841                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7842                a.info.dataDir = pkg.applicationInfo.dataDir;
7843                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7844                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7845
7846                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7847                // need other information about the application, like the ABI and what not ?
7848                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7849                mInstrumentation.put(a.getComponentName(), a);
7850                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7851                    if (r == null) {
7852                        r = new StringBuilder(256);
7853                    } else {
7854                        r.append(' ');
7855                    }
7856                    r.append(a.info.name);
7857                }
7858            }
7859            if (r != null) {
7860                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7861            }
7862
7863            if (pkg.protectedBroadcasts != null) {
7864                N = pkg.protectedBroadcasts.size();
7865                for (i=0; i<N; i++) {
7866                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7867                }
7868            }
7869
7870            pkgSetting.setTimeStamp(scanFileTime);
7871
7872            // Create idmap files for pairs of (packages, overlay packages).
7873            // Note: "android", ie framework-res.apk, is handled by native layers.
7874            if (pkg.mOverlayTarget != null) {
7875                // This is an overlay package.
7876                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7877                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7878                        mOverlays.put(pkg.mOverlayTarget,
7879                                new ArrayMap<String, PackageParser.Package>());
7880                    }
7881                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7882                    map.put(pkg.packageName, pkg);
7883                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7884                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7885                        createIdmapFailed = true;
7886                    }
7887                }
7888            } else if (mOverlays.containsKey(pkg.packageName) &&
7889                    !pkg.packageName.equals("android")) {
7890                // This is a regular package, with one or more known overlay packages.
7891                createIdmapsForPackageLI(pkg);
7892            }
7893        }
7894
7895        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7896
7897        if (createIdmapFailed) {
7898            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7899                    "scanPackageLI failed to createIdmap");
7900        }
7901        return pkg;
7902    }
7903
7904    /**
7905     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7906     * is derived purely on the basis of the contents of {@code scanFile} and
7907     * {@code cpuAbiOverride}.
7908     *
7909     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7910     */
7911    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7912                                 String cpuAbiOverride, boolean extractLibs)
7913            throws PackageManagerException {
7914        // TODO: We can probably be smarter about this stuff. For installed apps,
7915        // we can calculate this information at install time once and for all. For
7916        // system apps, we can probably assume that this information doesn't change
7917        // after the first boot scan. As things stand, we do lots of unnecessary work.
7918
7919        // Give ourselves some initial paths; we'll come back for another
7920        // pass once we've determined ABI below.
7921        setNativeLibraryPaths(pkg);
7922
7923        // We would never need to extract libs for forward-locked and external packages,
7924        // since the container service will do it for us. We shouldn't attempt to
7925        // extract libs from system app when it was not updated.
7926        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7927                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7928            extractLibs = false;
7929        }
7930
7931        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7932        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7933
7934        NativeLibraryHelper.Handle handle = null;
7935        try {
7936            handle = NativeLibraryHelper.Handle.create(pkg);
7937            // TODO(multiArch): This can be null for apps that didn't go through the
7938            // usual installation process. We can calculate it again, like we
7939            // do during install time.
7940            //
7941            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7942            // unnecessary.
7943            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7944
7945            // Null out the abis so that they can be recalculated.
7946            pkg.applicationInfo.primaryCpuAbi = null;
7947            pkg.applicationInfo.secondaryCpuAbi = null;
7948            if (isMultiArch(pkg.applicationInfo)) {
7949                // Warn if we've set an abiOverride for multi-lib packages..
7950                // By definition, we need to copy both 32 and 64 bit libraries for
7951                // such packages.
7952                if (pkg.cpuAbiOverride != null
7953                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7954                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7955                }
7956
7957                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7958                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7959                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7960                    if (extractLibs) {
7961                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7962                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7963                                useIsaSpecificSubdirs);
7964                    } else {
7965                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7966                    }
7967                }
7968
7969                maybeThrowExceptionForMultiArchCopy(
7970                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7971
7972                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7973                    if (extractLibs) {
7974                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7975                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7976                                useIsaSpecificSubdirs);
7977                    } else {
7978                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7979                    }
7980                }
7981
7982                maybeThrowExceptionForMultiArchCopy(
7983                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7984
7985                if (abi64 >= 0) {
7986                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7987                }
7988
7989                if (abi32 >= 0) {
7990                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7991                    if (abi64 >= 0) {
7992                        pkg.applicationInfo.secondaryCpuAbi = abi;
7993                    } else {
7994                        pkg.applicationInfo.primaryCpuAbi = abi;
7995                    }
7996                }
7997            } else {
7998                String[] abiList = (cpuAbiOverride != null) ?
7999                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8000
8001                // Enable gross and lame hacks for apps that are built with old
8002                // SDK tools. We must scan their APKs for renderscript bitcode and
8003                // not launch them if it's present. Don't bother checking on devices
8004                // that don't have 64 bit support.
8005                boolean needsRenderScriptOverride = false;
8006                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8007                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8008                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8009                    needsRenderScriptOverride = true;
8010                }
8011
8012                final int copyRet;
8013                if (extractLibs) {
8014                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8015                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8016                } else {
8017                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8018                }
8019
8020                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8021                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8022                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8023                }
8024
8025                if (copyRet >= 0) {
8026                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8027                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8028                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8029                } else if (needsRenderScriptOverride) {
8030                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8031                }
8032            }
8033        } catch (IOException ioe) {
8034            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8035        } finally {
8036            IoUtils.closeQuietly(handle);
8037        }
8038
8039        // Now that we've calculated the ABIs and determined if it's an internal app,
8040        // we will go ahead and populate the nativeLibraryPath.
8041        setNativeLibraryPaths(pkg);
8042    }
8043
8044    /**
8045     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8046     * i.e, so that all packages can be run inside a single process if required.
8047     *
8048     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8049     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8050     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8051     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8052     * updating a package that belongs to a shared user.
8053     *
8054     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8055     * adds unnecessary complexity.
8056     */
8057    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8058            PackageParser.Package scannedPackage, boolean bootComplete) {
8059        String requiredInstructionSet = null;
8060        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8061            requiredInstructionSet = VMRuntime.getInstructionSet(
8062                     scannedPackage.applicationInfo.primaryCpuAbi);
8063        }
8064
8065        PackageSetting requirer = null;
8066        for (PackageSetting ps : packagesForUser) {
8067            // If packagesForUser contains scannedPackage, we skip it. This will happen
8068            // when scannedPackage is an update of an existing package. Without this check,
8069            // we will never be able to change the ABI of any package belonging to a shared
8070            // user, even if it's compatible with other packages.
8071            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8072                if (ps.primaryCpuAbiString == null) {
8073                    continue;
8074                }
8075
8076                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8077                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8078                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8079                    // this but there's not much we can do.
8080                    String errorMessage = "Instruction set mismatch, "
8081                            + ((requirer == null) ? "[caller]" : requirer)
8082                            + " requires " + requiredInstructionSet + " whereas " + ps
8083                            + " requires " + instructionSet;
8084                    Slog.w(TAG, errorMessage);
8085                }
8086
8087                if (requiredInstructionSet == null) {
8088                    requiredInstructionSet = instructionSet;
8089                    requirer = ps;
8090                }
8091            }
8092        }
8093
8094        if (requiredInstructionSet != null) {
8095            String adjustedAbi;
8096            if (requirer != null) {
8097                // requirer != null implies that either scannedPackage was null or that scannedPackage
8098                // did not require an ABI, in which case we have to adjust scannedPackage to match
8099                // the ABI of the set (which is the same as requirer's ABI)
8100                adjustedAbi = requirer.primaryCpuAbiString;
8101                if (scannedPackage != null) {
8102                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8103                }
8104            } else {
8105                // requirer == null implies that we're updating all ABIs in the set to
8106                // match scannedPackage.
8107                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8108            }
8109
8110            for (PackageSetting ps : packagesForUser) {
8111                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8112                    if (ps.primaryCpuAbiString != null) {
8113                        continue;
8114                    }
8115
8116                    ps.primaryCpuAbiString = adjustedAbi;
8117                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8118                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8119                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8120                        mInstaller.rmdex(ps.codePathString,
8121                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8122                    }
8123                }
8124            }
8125        }
8126    }
8127
8128    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8129        synchronized (mPackages) {
8130            mResolverReplaced = true;
8131            // Set up information for custom user intent resolution activity.
8132            mResolveActivity.applicationInfo = pkg.applicationInfo;
8133            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8134            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8135            mResolveActivity.processName = pkg.applicationInfo.packageName;
8136            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8137            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8138                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8139            mResolveActivity.theme = 0;
8140            mResolveActivity.exported = true;
8141            mResolveActivity.enabled = true;
8142            mResolveInfo.activityInfo = mResolveActivity;
8143            mResolveInfo.priority = 0;
8144            mResolveInfo.preferredOrder = 0;
8145            mResolveInfo.match = 0;
8146            mResolveComponentName = mCustomResolverComponentName;
8147            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8148                    mResolveComponentName);
8149        }
8150    }
8151
8152    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8153        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8154
8155        // Set up information for ephemeral installer activity
8156        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8157        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8158        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8159        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8160        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8161        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8162                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8163        mEphemeralInstallerActivity.theme = 0;
8164        mEphemeralInstallerActivity.exported = true;
8165        mEphemeralInstallerActivity.enabled = true;
8166        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8167        mEphemeralInstallerInfo.priority = 0;
8168        mEphemeralInstallerInfo.preferredOrder = 0;
8169        mEphemeralInstallerInfo.match = 0;
8170
8171        if (DEBUG_EPHEMERAL) {
8172            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8173        }
8174    }
8175
8176    private static String calculateBundledApkRoot(final String codePathString) {
8177        final File codePath = new File(codePathString);
8178        final File codeRoot;
8179        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8180            codeRoot = Environment.getRootDirectory();
8181        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8182            codeRoot = Environment.getOemDirectory();
8183        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8184            codeRoot = Environment.getVendorDirectory();
8185        } else {
8186            // Unrecognized code path; take its top real segment as the apk root:
8187            // e.g. /something/app/blah.apk => /something
8188            try {
8189                File f = codePath.getCanonicalFile();
8190                File parent = f.getParentFile();    // non-null because codePath is a file
8191                File tmp;
8192                while ((tmp = parent.getParentFile()) != null) {
8193                    f = parent;
8194                    parent = tmp;
8195                }
8196                codeRoot = f;
8197                Slog.w(TAG, "Unrecognized code path "
8198                        + codePath + " - using " + codeRoot);
8199            } catch (IOException e) {
8200                // Can't canonicalize the code path -- shenanigans?
8201                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8202                return Environment.getRootDirectory().getPath();
8203            }
8204        }
8205        return codeRoot.getPath();
8206    }
8207
8208    /**
8209     * Derive and set the location of native libraries for the given package,
8210     * which varies depending on where and how the package was installed.
8211     */
8212    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8213        final ApplicationInfo info = pkg.applicationInfo;
8214        final String codePath = pkg.codePath;
8215        final File codeFile = new File(codePath);
8216        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8217        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8218
8219        info.nativeLibraryRootDir = null;
8220        info.nativeLibraryRootRequiresIsa = false;
8221        info.nativeLibraryDir = null;
8222        info.secondaryNativeLibraryDir = null;
8223
8224        if (isApkFile(codeFile)) {
8225            // Monolithic install
8226            if (bundledApp) {
8227                // If "/system/lib64/apkname" exists, assume that is the per-package
8228                // native library directory to use; otherwise use "/system/lib/apkname".
8229                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8230                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8231                        getPrimaryInstructionSet(info));
8232
8233                // This is a bundled system app so choose the path based on the ABI.
8234                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8235                // is just the default path.
8236                final String apkName = deriveCodePathName(codePath);
8237                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8238                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8239                        apkName).getAbsolutePath();
8240
8241                if (info.secondaryCpuAbi != null) {
8242                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8243                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8244                            secondaryLibDir, apkName).getAbsolutePath();
8245                }
8246            } else if (asecApp) {
8247                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8248                        .getAbsolutePath();
8249            } else {
8250                final String apkName = deriveCodePathName(codePath);
8251                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8252                        .getAbsolutePath();
8253            }
8254
8255            info.nativeLibraryRootRequiresIsa = false;
8256            info.nativeLibraryDir = info.nativeLibraryRootDir;
8257        } else {
8258            // Cluster install
8259            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8260            info.nativeLibraryRootRequiresIsa = true;
8261
8262            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8263                    getPrimaryInstructionSet(info)).getAbsolutePath();
8264
8265            if (info.secondaryCpuAbi != null) {
8266                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8267                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8268            }
8269        }
8270    }
8271
8272    /**
8273     * Calculate the abis and roots for a bundled app. These can uniquely
8274     * be determined from the contents of the system partition, i.e whether
8275     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8276     * of this information, and instead assume that the system was built
8277     * sensibly.
8278     */
8279    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8280                                           PackageSetting pkgSetting) {
8281        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8282
8283        // If "/system/lib64/apkname" exists, assume that is the per-package
8284        // native library directory to use; otherwise use "/system/lib/apkname".
8285        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8286        setBundledAppAbi(pkg, apkRoot, apkName);
8287        // pkgSetting might be null during rescan following uninstall of updates
8288        // to a bundled app, so accommodate that possibility.  The settings in
8289        // that case will be established later from the parsed package.
8290        //
8291        // If the settings aren't null, sync them up with what we've just derived.
8292        // note that apkRoot isn't stored in the package settings.
8293        if (pkgSetting != null) {
8294            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8295            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8296        }
8297    }
8298
8299    /**
8300     * Deduces the ABI of a bundled app and sets the relevant fields on the
8301     * parsed pkg object.
8302     *
8303     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8304     *        under which system libraries are installed.
8305     * @param apkName the name of the installed package.
8306     */
8307    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8308        final File codeFile = new File(pkg.codePath);
8309
8310        final boolean has64BitLibs;
8311        final boolean has32BitLibs;
8312        if (isApkFile(codeFile)) {
8313            // Monolithic install
8314            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8315            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8316        } else {
8317            // Cluster install
8318            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8319            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8320                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8321                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8322                has64BitLibs = (new File(rootDir, isa)).exists();
8323            } else {
8324                has64BitLibs = false;
8325            }
8326            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8327                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8328                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8329                has32BitLibs = (new File(rootDir, isa)).exists();
8330            } else {
8331                has32BitLibs = false;
8332            }
8333        }
8334
8335        if (has64BitLibs && !has32BitLibs) {
8336            // The package has 64 bit libs, but not 32 bit libs. Its primary
8337            // ABI should be 64 bit. We can safely assume here that the bundled
8338            // native libraries correspond to the most preferred ABI in the list.
8339
8340            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8341            pkg.applicationInfo.secondaryCpuAbi = null;
8342        } else if (has32BitLibs && !has64BitLibs) {
8343            // The package has 32 bit libs but not 64 bit libs. Its primary
8344            // ABI should be 32 bit.
8345
8346            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8347            pkg.applicationInfo.secondaryCpuAbi = null;
8348        } else if (has32BitLibs && has64BitLibs) {
8349            // The application has both 64 and 32 bit bundled libraries. We check
8350            // here that the app declares multiArch support, and warn if it doesn't.
8351            //
8352            // We will be lenient here and record both ABIs. The primary will be the
8353            // ABI that's higher on the list, i.e, a device that's configured to prefer
8354            // 64 bit apps will see a 64 bit primary ABI,
8355
8356            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8357                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8358            }
8359
8360            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8361                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8362                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8363            } else {
8364                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8365                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8366            }
8367        } else {
8368            pkg.applicationInfo.primaryCpuAbi = null;
8369            pkg.applicationInfo.secondaryCpuAbi = null;
8370        }
8371    }
8372
8373    private void killApplication(String pkgName, int appId, String reason) {
8374        // Request the ActivityManager to kill the process(only for existing packages)
8375        // so that we do not end up in a confused state while the user is still using the older
8376        // version of the application while the new one gets installed.
8377        IActivityManager am = ActivityManagerNative.getDefault();
8378        if (am != null) {
8379            try {
8380                am.killApplicationWithAppId(pkgName, appId, reason);
8381            } catch (RemoteException e) {
8382            }
8383        }
8384    }
8385
8386    void removePackageLI(PackageSetting ps, boolean chatty) {
8387        if (DEBUG_INSTALL) {
8388            if (chatty)
8389                Log.d(TAG, "Removing package " + ps.name);
8390        }
8391
8392        // writer
8393        synchronized (mPackages) {
8394            mPackages.remove(ps.name);
8395            final PackageParser.Package pkg = ps.pkg;
8396            if (pkg != null) {
8397                cleanPackageDataStructuresLILPw(pkg, chatty);
8398            }
8399        }
8400    }
8401
8402    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8403        if (DEBUG_INSTALL) {
8404            if (chatty)
8405                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8406        }
8407
8408        // writer
8409        synchronized (mPackages) {
8410            mPackages.remove(pkg.applicationInfo.packageName);
8411            cleanPackageDataStructuresLILPw(pkg, chatty);
8412        }
8413    }
8414
8415    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8416        int N = pkg.providers.size();
8417        StringBuilder r = null;
8418        int i;
8419        for (i=0; i<N; i++) {
8420            PackageParser.Provider p = pkg.providers.get(i);
8421            mProviders.removeProvider(p);
8422            if (p.info.authority == null) {
8423
8424                /* There was another ContentProvider with this authority when
8425                 * this app was installed so this authority is null,
8426                 * Ignore it as we don't have to unregister the provider.
8427                 */
8428                continue;
8429            }
8430            String names[] = p.info.authority.split(";");
8431            for (int j = 0; j < names.length; j++) {
8432                if (mProvidersByAuthority.get(names[j]) == p) {
8433                    mProvidersByAuthority.remove(names[j]);
8434                    if (DEBUG_REMOVE) {
8435                        if (chatty)
8436                            Log.d(TAG, "Unregistered content provider: " + names[j]
8437                                    + ", className = " + p.info.name + ", isSyncable = "
8438                                    + p.info.isSyncable);
8439                    }
8440                }
8441            }
8442            if (DEBUG_REMOVE && chatty) {
8443                if (r == null) {
8444                    r = new StringBuilder(256);
8445                } else {
8446                    r.append(' ');
8447                }
8448                r.append(p.info.name);
8449            }
8450        }
8451        if (r != null) {
8452            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8453        }
8454
8455        N = pkg.services.size();
8456        r = null;
8457        for (i=0; i<N; i++) {
8458            PackageParser.Service s = pkg.services.get(i);
8459            mServices.removeService(s);
8460            if (chatty) {
8461                if (r == null) {
8462                    r = new StringBuilder(256);
8463                } else {
8464                    r.append(' ');
8465                }
8466                r.append(s.info.name);
8467            }
8468        }
8469        if (r != null) {
8470            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8471        }
8472
8473        N = pkg.receivers.size();
8474        r = null;
8475        for (i=0; i<N; i++) {
8476            PackageParser.Activity a = pkg.receivers.get(i);
8477            mReceivers.removeActivity(a, "receiver");
8478            if (DEBUG_REMOVE && chatty) {
8479                if (r == null) {
8480                    r = new StringBuilder(256);
8481                } else {
8482                    r.append(' ');
8483                }
8484                r.append(a.info.name);
8485            }
8486        }
8487        if (r != null) {
8488            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8489        }
8490
8491        N = pkg.activities.size();
8492        r = null;
8493        for (i=0; i<N; i++) {
8494            PackageParser.Activity a = pkg.activities.get(i);
8495            mActivities.removeActivity(a, "activity");
8496            if (DEBUG_REMOVE && chatty) {
8497                if (r == null) {
8498                    r = new StringBuilder(256);
8499                } else {
8500                    r.append(' ');
8501                }
8502                r.append(a.info.name);
8503            }
8504        }
8505        if (r != null) {
8506            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8507        }
8508
8509        N = pkg.permissions.size();
8510        r = null;
8511        for (i=0; i<N; i++) {
8512            PackageParser.Permission p = pkg.permissions.get(i);
8513            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8514            if (bp == null) {
8515                bp = mSettings.mPermissionTrees.get(p.info.name);
8516            }
8517            if (bp != null && bp.perm == p) {
8518                bp.perm = null;
8519                if (DEBUG_REMOVE && chatty) {
8520                    if (r == null) {
8521                        r = new StringBuilder(256);
8522                    } else {
8523                        r.append(' ');
8524                    }
8525                    r.append(p.info.name);
8526                }
8527            }
8528            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8529                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8530                if (appOpPkgs != null) {
8531                    appOpPkgs.remove(pkg.packageName);
8532                }
8533            }
8534        }
8535        if (r != null) {
8536            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8537        }
8538
8539        N = pkg.requestedPermissions.size();
8540        r = null;
8541        for (i=0; i<N; i++) {
8542            String perm = pkg.requestedPermissions.get(i);
8543            BasePermission bp = mSettings.mPermissions.get(perm);
8544            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8545                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8546                if (appOpPkgs != null) {
8547                    appOpPkgs.remove(pkg.packageName);
8548                    if (appOpPkgs.isEmpty()) {
8549                        mAppOpPermissionPackages.remove(perm);
8550                    }
8551                }
8552            }
8553        }
8554        if (r != null) {
8555            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8556        }
8557
8558        N = pkg.instrumentation.size();
8559        r = null;
8560        for (i=0; i<N; i++) {
8561            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8562            mInstrumentation.remove(a.getComponentName());
8563            if (DEBUG_REMOVE && chatty) {
8564                if (r == null) {
8565                    r = new StringBuilder(256);
8566                } else {
8567                    r.append(' ');
8568                }
8569                r.append(a.info.name);
8570            }
8571        }
8572        if (r != null) {
8573            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8574        }
8575
8576        r = null;
8577        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8578            // Only system apps can hold shared libraries.
8579            if (pkg.libraryNames != null) {
8580                for (i=0; i<pkg.libraryNames.size(); i++) {
8581                    String name = pkg.libraryNames.get(i);
8582                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8583                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8584                        mSharedLibraries.remove(name);
8585                        if (DEBUG_REMOVE && chatty) {
8586                            if (r == null) {
8587                                r = new StringBuilder(256);
8588                            } else {
8589                                r.append(' ');
8590                            }
8591                            r.append(name);
8592                        }
8593                    }
8594                }
8595            }
8596        }
8597        if (r != null) {
8598            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8599        }
8600    }
8601
8602    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8603        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8604            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8605                return true;
8606            }
8607        }
8608        return false;
8609    }
8610
8611    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8612    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8613    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8614
8615    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8616            int flags) {
8617        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8618        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8619    }
8620
8621    private void updatePermissionsLPw(String changingPkg,
8622            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8623        // Make sure there are no dangling permission trees.
8624        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8625        while (it.hasNext()) {
8626            final BasePermission bp = it.next();
8627            if (bp.packageSetting == null) {
8628                // We may not yet have parsed the package, so just see if
8629                // we still know about its settings.
8630                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8631            }
8632            if (bp.packageSetting == null) {
8633                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8634                        + " from package " + bp.sourcePackage);
8635                it.remove();
8636            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8637                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8638                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8639                            + " from package " + bp.sourcePackage);
8640                    flags |= UPDATE_PERMISSIONS_ALL;
8641                    it.remove();
8642                }
8643            }
8644        }
8645
8646        // Make sure all dynamic permissions have been assigned to a package,
8647        // and make sure there are no dangling permissions.
8648        it = mSettings.mPermissions.values().iterator();
8649        while (it.hasNext()) {
8650            final BasePermission bp = it.next();
8651            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8652                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8653                        + bp.name + " pkg=" + bp.sourcePackage
8654                        + " info=" + bp.pendingInfo);
8655                if (bp.packageSetting == null && bp.pendingInfo != null) {
8656                    final BasePermission tree = findPermissionTreeLP(bp.name);
8657                    if (tree != null && tree.perm != null) {
8658                        bp.packageSetting = tree.packageSetting;
8659                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8660                                new PermissionInfo(bp.pendingInfo));
8661                        bp.perm.info.packageName = tree.perm.info.packageName;
8662                        bp.perm.info.name = bp.name;
8663                        bp.uid = tree.uid;
8664                    }
8665                }
8666            }
8667            if (bp.packageSetting == null) {
8668                // We may not yet have parsed the package, so just see if
8669                // we still know about its settings.
8670                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8671            }
8672            if (bp.packageSetting == null) {
8673                Slog.w(TAG, "Removing dangling permission: " + bp.name
8674                        + " from package " + bp.sourcePackage);
8675                it.remove();
8676            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8677                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8678                    Slog.i(TAG, "Removing old permission: " + bp.name
8679                            + " from package " + bp.sourcePackage);
8680                    flags |= UPDATE_PERMISSIONS_ALL;
8681                    it.remove();
8682                }
8683            }
8684        }
8685
8686        // Now update the permissions for all packages, in particular
8687        // replace the granted permissions of the system packages.
8688        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8689            for (PackageParser.Package pkg : mPackages.values()) {
8690                if (pkg != pkgInfo) {
8691                    // Only replace for packages on requested volume
8692                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8693                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8694                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8695                    grantPermissionsLPw(pkg, replace, changingPkg);
8696                }
8697            }
8698        }
8699
8700        if (pkgInfo != null) {
8701            // Only replace for packages on requested volume
8702            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8703            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8704                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8705            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8706        }
8707    }
8708
8709    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8710            String packageOfInterest) {
8711        // IMPORTANT: There are two types of permissions: install and runtime.
8712        // Install time permissions are granted when the app is installed to
8713        // all device users and users added in the future. Runtime permissions
8714        // are granted at runtime explicitly to specific users. Normal and signature
8715        // protected permissions are install time permissions. Dangerous permissions
8716        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8717        // otherwise they are runtime permissions. This function does not manage
8718        // runtime permissions except for the case an app targeting Lollipop MR1
8719        // being upgraded to target a newer SDK, in which case dangerous permissions
8720        // are transformed from install time to runtime ones.
8721
8722        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8723        if (ps == null) {
8724            return;
8725        }
8726
8727        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8728
8729        PermissionsState permissionsState = ps.getPermissionsState();
8730        PermissionsState origPermissions = permissionsState;
8731
8732        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8733
8734        boolean runtimePermissionsRevoked = false;
8735        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8736
8737        boolean changedInstallPermission = false;
8738
8739        if (replace) {
8740            ps.installPermissionsFixed = false;
8741            if (!ps.isSharedUser()) {
8742                origPermissions = new PermissionsState(permissionsState);
8743                permissionsState.reset();
8744            } else {
8745                // We need to know only about runtime permission changes since the
8746                // calling code always writes the install permissions state but
8747                // the runtime ones are written only if changed. The only cases of
8748                // changed runtime permissions here are promotion of an install to
8749                // runtime and revocation of a runtime from a shared user.
8750                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8751                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8752                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8753                    runtimePermissionsRevoked = true;
8754                }
8755            }
8756        }
8757
8758        permissionsState.setGlobalGids(mGlobalGids);
8759
8760        final int N = pkg.requestedPermissions.size();
8761        for (int i=0; i<N; i++) {
8762            final String name = pkg.requestedPermissions.get(i);
8763            final BasePermission bp = mSettings.mPermissions.get(name);
8764
8765            if (DEBUG_INSTALL) {
8766                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8767            }
8768
8769            if (bp == null || bp.packageSetting == null) {
8770                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8771                    Slog.w(TAG, "Unknown permission " + name
8772                            + " in package " + pkg.packageName);
8773                }
8774                continue;
8775            }
8776
8777            final String perm = bp.name;
8778            boolean allowedSig = false;
8779            int grant = GRANT_DENIED;
8780
8781            // Keep track of app op permissions.
8782            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8783                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8784                if (pkgs == null) {
8785                    pkgs = new ArraySet<>();
8786                    mAppOpPermissionPackages.put(bp.name, pkgs);
8787                }
8788                pkgs.add(pkg.packageName);
8789            }
8790
8791            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8792            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8793                    >= Build.VERSION_CODES.M;
8794            switch (level) {
8795                case PermissionInfo.PROTECTION_NORMAL: {
8796                    // For all apps normal permissions are install time ones.
8797                    grant = GRANT_INSTALL;
8798                } break;
8799
8800                case PermissionInfo.PROTECTION_DANGEROUS: {
8801                    // If a permission review is required for legacy apps we represent
8802                    // their permissions as always granted runtime ones since we need
8803                    // to keep the review required permission flag per user while an
8804                    // install permission's state is shared across all users.
8805                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8806                        // For legacy apps dangerous permissions are install time ones.
8807                        grant = GRANT_INSTALL;
8808                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8809                        // For legacy apps that became modern, install becomes runtime.
8810                        grant = GRANT_UPGRADE;
8811                    } else if (mPromoteSystemApps
8812                            && isSystemApp(ps)
8813                            && mExistingSystemPackages.contains(ps.name)) {
8814                        // For legacy system apps, install becomes runtime.
8815                        // We cannot check hasInstallPermission() for system apps since those
8816                        // permissions were granted implicitly and not persisted pre-M.
8817                        grant = GRANT_UPGRADE;
8818                    } else {
8819                        // For modern apps keep runtime permissions unchanged.
8820                        grant = GRANT_RUNTIME;
8821                    }
8822                } break;
8823
8824                case PermissionInfo.PROTECTION_SIGNATURE: {
8825                    // For all apps signature permissions are install time ones.
8826                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8827                    if (allowedSig) {
8828                        grant = GRANT_INSTALL;
8829                    }
8830                } break;
8831            }
8832
8833            if (DEBUG_INSTALL) {
8834                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8835            }
8836
8837            if (grant != GRANT_DENIED) {
8838                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8839                    // If this is an existing, non-system package, then
8840                    // we can't add any new permissions to it.
8841                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8842                        // Except...  if this is a permission that was added
8843                        // to the platform (note: need to only do this when
8844                        // updating the platform).
8845                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8846                            grant = GRANT_DENIED;
8847                        }
8848                    }
8849                }
8850
8851                switch (grant) {
8852                    case GRANT_INSTALL: {
8853                        // Revoke this as runtime permission to handle the case of
8854                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8855                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8856                            if (origPermissions.getRuntimePermissionState(
8857                                    bp.name, userId) != null) {
8858                                // Revoke the runtime permission and clear the flags.
8859                                origPermissions.revokeRuntimePermission(bp, userId);
8860                                origPermissions.updatePermissionFlags(bp, userId,
8861                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8862                                // If we revoked a permission permission, we have to write.
8863                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8864                                        changedRuntimePermissionUserIds, userId);
8865                            }
8866                        }
8867                        // Grant an install permission.
8868                        if (permissionsState.grantInstallPermission(bp) !=
8869                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8870                            changedInstallPermission = true;
8871                        }
8872                    } break;
8873
8874                    case GRANT_RUNTIME: {
8875                        // Grant previously granted runtime permissions.
8876                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8877                            PermissionState permissionState = origPermissions
8878                                    .getRuntimePermissionState(bp.name, userId);
8879                            int flags = permissionState != null
8880                                    ? permissionState.getFlags() : 0;
8881                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8882                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8883                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8884                                    // If we cannot put the permission as it was, we have to write.
8885                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8886                                            changedRuntimePermissionUserIds, userId);
8887                                }
8888                                // If the app supports runtime permissions no need for a review.
8889                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8890                                        && appSupportsRuntimePermissions
8891                                        && (flags & PackageManager
8892                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8893                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8894                                    // Since we changed the flags, we have to write.
8895                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8896                                            changedRuntimePermissionUserIds, userId);
8897                                }
8898                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8899                                    && !appSupportsRuntimePermissions) {
8900                                // For legacy apps that need a permission review, every new
8901                                // runtime permission is granted but it is pending a review.
8902                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8903                                    permissionsState.grantRuntimePermission(bp, userId);
8904                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8905                                    // We changed the permission and flags, hence have to write.
8906                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8907                                            changedRuntimePermissionUserIds, userId);
8908                                }
8909                            }
8910                            // Propagate the permission flags.
8911                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8912                        }
8913                    } break;
8914
8915                    case GRANT_UPGRADE: {
8916                        // Grant runtime permissions for a previously held install permission.
8917                        PermissionState permissionState = origPermissions
8918                                .getInstallPermissionState(bp.name);
8919                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8920
8921                        if (origPermissions.revokeInstallPermission(bp)
8922                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8923                            // We will be transferring the permission flags, so clear them.
8924                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8925                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8926                            changedInstallPermission = true;
8927                        }
8928
8929                        // If the permission is not to be promoted to runtime we ignore it and
8930                        // also its other flags as they are not applicable to install permissions.
8931                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8932                            for (int userId : currentUserIds) {
8933                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8934                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8935                                    // Transfer the permission flags.
8936                                    permissionsState.updatePermissionFlags(bp, userId,
8937                                            flags, flags);
8938                                    // If we granted the permission, we have to write.
8939                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8940                                            changedRuntimePermissionUserIds, userId);
8941                                }
8942                            }
8943                        }
8944                    } break;
8945
8946                    default: {
8947                        if (packageOfInterest == null
8948                                || packageOfInterest.equals(pkg.packageName)) {
8949                            Slog.w(TAG, "Not granting permission " + perm
8950                                    + " to package " + pkg.packageName
8951                                    + " because it was previously installed without");
8952                        }
8953                    } break;
8954                }
8955            } else {
8956                if (permissionsState.revokeInstallPermission(bp) !=
8957                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8958                    // Also drop the permission flags.
8959                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8960                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8961                    changedInstallPermission = true;
8962                    Slog.i(TAG, "Un-granting permission " + perm
8963                            + " from package " + pkg.packageName
8964                            + " (protectionLevel=" + bp.protectionLevel
8965                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8966                            + ")");
8967                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8968                    // Don't print warning for app op permissions, since it is fine for them
8969                    // not to be granted, there is a UI for the user to decide.
8970                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8971                        Slog.w(TAG, "Not granting permission " + perm
8972                                + " to package " + pkg.packageName
8973                                + " (protectionLevel=" + bp.protectionLevel
8974                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8975                                + ")");
8976                    }
8977                }
8978            }
8979        }
8980
8981        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8982                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8983            // This is the first that we have heard about this package, so the
8984            // permissions we have now selected are fixed until explicitly
8985            // changed.
8986            ps.installPermissionsFixed = true;
8987        }
8988
8989        // Persist the runtime permissions state for users with changes. If permissions
8990        // were revoked because no app in the shared user declares them we have to
8991        // write synchronously to avoid losing runtime permissions state.
8992        for (int userId : changedRuntimePermissionUserIds) {
8993            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8994        }
8995
8996        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8997    }
8998
8999    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9000        boolean allowed = false;
9001        final int NP = PackageParser.NEW_PERMISSIONS.length;
9002        for (int ip=0; ip<NP; ip++) {
9003            final PackageParser.NewPermissionInfo npi
9004                    = PackageParser.NEW_PERMISSIONS[ip];
9005            if (npi.name.equals(perm)
9006                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9007                allowed = true;
9008                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9009                        + pkg.packageName);
9010                break;
9011            }
9012        }
9013        return allowed;
9014    }
9015
9016    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9017            BasePermission bp, PermissionsState origPermissions) {
9018        boolean allowed;
9019        allowed = (compareSignatures(
9020                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9021                        == PackageManager.SIGNATURE_MATCH)
9022                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9023                        == PackageManager.SIGNATURE_MATCH);
9024        if (!allowed && (bp.protectionLevel
9025                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9026            if (isSystemApp(pkg)) {
9027                // For updated system applications, a system permission
9028                // is granted only if it had been defined by the original application.
9029                if (pkg.isUpdatedSystemApp()) {
9030                    final PackageSetting sysPs = mSettings
9031                            .getDisabledSystemPkgLPr(pkg.packageName);
9032                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9033                        // If the original was granted this permission, we take
9034                        // that grant decision as read and propagate it to the
9035                        // update.
9036                        if (sysPs.isPrivileged()) {
9037                            allowed = true;
9038                        }
9039                    } else {
9040                        // The system apk may have been updated with an older
9041                        // version of the one on the data partition, but which
9042                        // granted a new system permission that it didn't have
9043                        // before.  In this case we do want to allow the app to
9044                        // now get the new permission if the ancestral apk is
9045                        // privileged to get it.
9046                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9047                            for (int j=0;
9048                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9049                                if (perm.equals(
9050                                        sysPs.pkg.requestedPermissions.get(j))) {
9051                                    allowed = true;
9052                                    break;
9053                                }
9054                            }
9055                        }
9056                    }
9057                } else {
9058                    allowed = isPrivilegedApp(pkg);
9059                }
9060            }
9061        }
9062        if (!allowed) {
9063            if (!allowed && (bp.protectionLevel
9064                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9065                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9066                // If this was a previously normal/dangerous permission that got moved
9067                // to a system permission as part of the runtime permission redesign, then
9068                // we still want to blindly grant it to old apps.
9069                allowed = true;
9070            }
9071            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9072                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9073                // If this permission is to be granted to the system installer and
9074                // this app is an installer, then it gets the permission.
9075                allowed = true;
9076            }
9077            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9078                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9079                // If this permission is to be granted to the system verifier and
9080                // this app is a verifier, then it gets the permission.
9081                allowed = true;
9082            }
9083            if (!allowed && (bp.protectionLevel
9084                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9085                    && isSystemApp(pkg)) {
9086                // Any pre-installed system app is allowed to get this permission.
9087                allowed = true;
9088            }
9089            if (!allowed && (bp.protectionLevel
9090                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9091                // For development permissions, a development permission
9092                // is granted only if it was already granted.
9093                allowed = origPermissions.hasInstallPermission(perm);
9094            }
9095        }
9096        return allowed;
9097    }
9098
9099    final class ActivityIntentResolver
9100            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9101        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9102                boolean defaultOnly, int userId) {
9103            if (!sUserManager.exists(userId)) return null;
9104            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9105            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9106        }
9107
9108        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9109                int userId) {
9110            if (!sUserManager.exists(userId)) return null;
9111            mFlags = flags;
9112            return super.queryIntent(intent, resolvedType,
9113                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9114        }
9115
9116        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9117                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9118            if (!sUserManager.exists(userId)) return null;
9119            if (packageActivities == null) {
9120                return null;
9121            }
9122            mFlags = flags;
9123            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9124            final int N = packageActivities.size();
9125            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9126                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9127
9128            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9129            for (int i = 0; i < N; ++i) {
9130                intentFilters = packageActivities.get(i).intents;
9131                if (intentFilters != null && intentFilters.size() > 0) {
9132                    PackageParser.ActivityIntentInfo[] array =
9133                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9134                    intentFilters.toArray(array);
9135                    listCut.add(array);
9136                }
9137            }
9138            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9139        }
9140
9141        public final void addActivity(PackageParser.Activity a, String type) {
9142            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9143            mActivities.put(a.getComponentName(), a);
9144            if (DEBUG_SHOW_INFO)
9145                Log.v(
9146                TAG, "  " + type + " " +
9147                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9148            if (DEBUG_SHOW_INFO)
9149                Log.v(TAG, "    Class=" + a.info.name);
9150            final int NI = a.intents.size();
9151            for (int j=0; j<NI; j++) {
9152                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9153                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9154                    intent.setPriority(0);
9155                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9156                            + a.className + " with priority > 0, forcing to 0");
9157                }
9158                if (DEBUG_SHOW_INFO) {
9159                    Log.v(TAG, "    IntentFilter:");
9160                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9161                }
9162                if (!intent.debugCheck()) {
9163                    Log.w(TAG, "==> For Activity " + a.info.name);
9164                }
9165                addFilter(intent);
9166            }
9167        }
9168
9169        public final void removeActivity(PackageParser.Activity a, String type) {
9170            mActivities.remove(a.getComponentName());
9171            if (DEBUG_SHOW_INFO) {
9172                Log.v(TAG, "  " + type + " "
9173                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9174                                : a.info.name) + ":");
9175                Log.v(TAG, "    Class=" + a.info.name);
9176            }
9177            final int NI = a.intents.size();
9178            for (int j=0; j<NI; j++) {
9179                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9180                if (DEBUG_SHOW_INFO) {
9181                    Log.v(TAG, "    IntentFilter:");
9182                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9183                }
9184                removeFilter(intent);
9185            }
9186        }
9187
9188        @Override
9189        protected boolean allowFilterResult(
9190                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9191            ActivityInfo filterAi = filter.activity.info;
9192            for (int i=dest.size()-1; i>=0; i--) {
9193                ActivityInfo destAi = dest.get(i).activityInfo;
9194                if (destAi.name == filterAi.name
9195                        && destAi.packageName == filterAi.packageName) {
9196                    return false;
9197                }
9198            }
9199            return true;
9200        }
9201
9202        @Override
9203        protected ActivityIntentInfo[] newArray(int size) {
9204            return new ActivityIntentInfo[size];
9205        }
9206
9207        @Override
9208        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9209            if (!sUserManager.exists(userId)) return true;
9210            PackageParser.Package p = filter.activity.owner;
9211            if (p != null) {
9212                PackageSetting ps = (PackageSetting)p.mExtras;
9213                if (ps != null) {
9214                    // System apps are never considered stopped for purposes of
9215                    // filtering, because there may be no way for the user to
9216                    // actually re-launch them.
9217                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9218                            && ps.getStopped(userId);
9219                }
9220            }
9221            return false;
9222        }
9223
9224        @Override
9225        protected boolean isPackageForFilter(String packageName,
9226                PackageParser.ActivityIntentInfo info) {
9227            return packageName.equals(info.activity.owner.packageName);
9228        }
9229
9230        @Override
9231        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9232                int match, int userId) {
9233            if (!sUserManager.exists(userId)) return null;
9234            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9235                return null;
9236            }
9237            final PackageParser.Activity activity = info.activity;
9238            if (mSafeMode && (activity.info.applicationInfo.flags
9239                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9240                return null;
9241            }
9242            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9243            if (ps == null) {
9244                return null;
9245            }
9246            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9247                    ps.readUserState(userId), userId);
9248            if (ai == null) {
9249                return null;
9250            }
9251            final ResolveInfo res = new ResolveInfo();
9252            res.activityInfo = ai;
9253            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9254                res.filter = info;
9255            }
9256            if (info != null) {
9257                res.handleAllWebDataURI = info.handleAllWebDataURI();
9258            }
9259            res.priority = info.getPriority();
9260            res.preferredOrder = activity.owner.mPreferredOrder;
9261            //System.out.println("Result: " + res.activityInfo.className +
9262            //                   " = " + res.priority);
9263            res.match = match;
9264            res.isDefault = info.hasDefault;
9265            res.labelRes = info.labelRes;
9266            res.nonLocalizedLabel = info.nonLocalizedLabel;
9267            if (userNeedsBadging(userId)) {
9268                res.noResourceId = true;
9269            } else {
9270                res.icon = info.icon;
9271            }
9272            res.iconResourceId = info.icon;
9273            res.system = res.activityInfo.applicationInfo.isSystemApp();
9274            return res;
9275        }
9276
9277        @Override
9278        protected void sortResults(List<ResolveInfo> results) {
9279            Collections.sort(results, mResolvePrioritySorter);
9280        }
9281
9282        @Override
9283        protected void dumpFilter(PrintWriter out, String prefix,
9284                PackageParser.ActivityIntentInfo filter) {
9285            out.print(prefix); out.print(
9286                    Integer.toHexString(System.identityHashCode(filter.activity)));
9287                    out.print(' ');
9288                    filter.activity.printComponentShortName(out);
9289                    out.print(" filter ");
9290                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9291        }
9292
9293        @Override
9294        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9295            return filter.activity;
9296        }
9297
9298        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9299            PackageParser.Activity activity = (PackageParser.Activity)label;
9300            out.print(prefix); out.print(
9301                    Integer.toHexString(System.identityHashCode(activity)));
9302                    out.print(' ');
9303                    activity.printComponentShortName(out);
9304            if (count > 1) {
9305                out.print(" ("); out.print(count); out.print(" filters)");
9306            }
9307            out.println();
9308        }
9309
9310//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9311//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9312//            final List<ResolveInfo> retList = Lists.newArrayList();
9313//            while (i.hasNext()) {
9314//                final ResolveInfo resolveInfo = i.next();
9315//                if (isEnabledLP(resolveInfo.activityInfo)) {
9316//                    retList.add(resolveInfo);
9317//                }
9318//            }
9319//            return retList;
9320//        }
9321
9322        // Keys are String (activity class name), values are Activity.
9323        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9324                = new ArrayMap<ComponentName, PackageParser.Activity>();
9325        private int mFlags;
9326    }
9327
9328    private final class ServiceIntentResolver
9329            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9330        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9331                boolean defaultOnly, int userId) {
9332            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9333            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9334        }
9335
9336        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9337                int userId) {
9338            if (!sUserManager.exists(userId)) return null;
9339            mFlags = flags;
9340            return super.queryIntent(intent, resolvedType,
9341                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9342        }
9343
9344        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9345                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9346            if (!sUserManager.exists(userId)) return null;
9347            if (packageServices == null) {
9348                return null;
9349            }
9350            mFlags = flags;
9351            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9352            final int N = packageServices.size();
9353            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9354                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9355
9356            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9357            for (int i = 0; i < N; ++i) {
9358                intentFilters = packageServices.get(i).intents;
9359                if (intentFilters != null && intentFilters.size() > 0) {
9360                    PackageParser.ServiceIntentInfo[] array =
9361                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9362                    intentFilters.toArray(array);
9363                    listCut.add(array);
9364                }
9365            }
9366            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9367        }
9368
9369        public final void addService(PackageParser.Service s) {
9370            mServices.put(s.getComponentName(), s);
9371            if (DEBUG_SHOW_INFO) {
9372                Log.v(TAG, "  "
9373                        + (s.info.nonLocalizedLabel != null
9374                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9375                Log.v(TAG, "    Class=" + s.info.name);
9376            }
9377            final int NI = s.intents.size();
9378            int j;
9379            for (j=0; j<NI; j++) {
9380                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9381                if (DEBUG_SHOW_INFO) {
9382                    Log.v(TAG, "    IntentFilter:");
9383                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9384                }
9385                if (!intent.debugCheck()) {
9386                    Log.w(TAG, "==> For Service " + s.info.name);
9387                }
9388                addFilter(intent);
9389            }
9390        }
9391
9392        public final void removeService(PackageParser.Service s) {
9393            mServices.remove(s.getComponentName());
9394            if (DEBUG_SHOW_INFO) {
9395                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9396                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9397                Log.v(TAG, "    Class=" + s.info.name);
9398            }
9399            final int NI = s.intents.size();
9400            int j;
9401            for (j=0; j<NI; j++) {
9402                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9403                if (DEBUG_SHOW_INFO) {
9404                    Log.v(TAG, "    IntentFilter:");
9405                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9406                }
9407                removeFilter(intent);
9408            }
9409        }
9410
9411        @Override
9412        protected boolean allowFilterResult(
9413                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9414            ServiceInfo filterSi = filter.service.info;
9415            for (int i=dest.size()-1; i>=0; i--) {
9416                ServiceInfo destAi = dest.get(i).serviceInfo;
9417                if (destAi.name == filterSi.name
9418                        && destAi.packageName == filterSi.packageName) {
9419                    return false;
9420                }
9421            }
9422            return true;
9423        }
9424
9425        @Override
9426        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9427            return new PackageParser.ServiceIntentInfo[size];
9428        }
9429
9430        @Override
9431        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9432            if (!sUserManager.exists(userId)) return true;
9433            PackageParser.Package p = filter.service.owner;
9434            if (p != null) {
9435                PackageSetting ps = (PackageSetting)p.mExtras;
9436                if (ps != null) {
9437                    // System apps are never considered stopped for purposes of
9438                    // filtering, because there may be no way for the user to
9439                    // actually re-launch them.
9440                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9441                            && ps.getStopped(userId);
9442                }
9443            }
9444            return false;
9445        }
9446
9447        @Override
9448        protected boolean isPackageForFilter(String packageName,
9449                PackageParser.ServiceIntentInfo info) {
9450            return packageName.equals(info.service.owner.packageName);
9451        }
9452
9453        @Override
9454        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9455                int match, int userId) {
9456            if (!sUserManager.exists(userId)) return null;
9457            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9458            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9459                return null;
9460            }
9461            final PackageParser.Service service = info.service;
9462            if (mSafeMode && (service.info.applicationInfo.flags
9463                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9464                return null;
9465            }
9466            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9467            if (ps == null) {
9468                return null;
9469            }
9470            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9471                    ps.readUserState(userId), userId);
9472            if (si == null) {
9473                return null;
9474            }
9475            final ResolveInfo res = new ResolveInfo();
9476            res.serviceInfo = si;
9477            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9478                res.filter = filter;
9479            }
9480            res.priority = info.getPriority();
9481            res.preferredOrder = service.owner.mPreferredOrder;
9482            res.match = match;
9483            res.isDefault = info.hasDefault;
9484            res.labelRes = info.labelRes;
9485            res.nonLocalizedLabel = info.nonLocalizedLabel;
9486            res.icon = info.icon;
9487            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9488            return res;
9489        }
9490
9491        @Override
9492        protected void sortResults(List<ResolveInfo> results) {
9493            Collections.sort(results, mResolvePrioritySorter);
9494        }
9495
9496        @Override
9497        protected void dumpFilter(PrintWriter out, String prefix,
9498                PackageParser.ServiceIntentInfo filter) {
9499            out.print(prefix); out.print(
9500                    Integer.toHexString(System.identityHashCode(filter.service)));
9501                    out.print(' ');
9502                    filter.service.printComponentShortName(out);
9503                    out.print(" filter ");
9504                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9505        }
9506
9507        @Override
9508        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9509            return filter.service;
9510        }
9511
9512        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9513            PackageParser.Service service = (PackageParser.Service)label;
9514            out.print(prefix); out.print(
9515                    Integer.toHexString(System.identityHashCode(service)));
9516                    out.print(' ');
9517                    service.printComponentShortName(out);
9518            if (count > 1) {
9519                out.print(" ("); out.print(count); out.print(" filters)");
9520            }
9521            out.println();
9522        }
9523
9524//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9525//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9526//            final List<ResolveInfo> retList = Lists.newArrayList();
9527//            while (i.hasNext()) {
9528//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9529//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9530//                    retList.add(resolveInfo);
9531//                }
9532//            }
9533//            return retList;
9534//        }
9535
9536        // Keys are String (activity class name), values are Activity.
9537        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9538                = new ArrayMap<ComponentName, PackageParser.Service>();
9539        private int mFlags;
9540    };
9541
9542    private final class ProviderIntentResolver
9543            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9544        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9545                boolean defaultOnly, int userId) {
9546            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9547            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9548        }
9549
9550        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9551                int userId) {
9552            if (!sUserManager.exists(userId))
9553                return null;
9554            mFlags = flags;
9555            return super.queryIntent(intent, resolvedType,
9556                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9557        }
9558
9559        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9560                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9561            if (!sUserManager.exists(userId))
9562                return null;
9563            if (packageProviders == null) {
9564                return null;
9565            }
9566            mFlags = flags;
9567            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9568            final int N = packageProviders.size();
9569            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9570                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9571
9572            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9573            for (int i = 0; i < N; ++i) {
9574                intentFilters = packageProviders.get(i).intents;
9575                if (intentFilters != null && intentFilters.size() > 0) {
9576                    PackageParser.ProviderIntentInfo[] array =
9577                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9578                    intentFilters.toArray(array);
9579                    listCut.add(array);
9580                }
9581            }
9582            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9583        }
9584
9585        public final void addProvider(PackageParser.Provider p) {
9586            if (mProviders.containsKey(p.getComponentName())) {
9587                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9588                return;
9589            }
9590
9591            mProviders.put(p.getComponentName(), p);
9592            if (DEBUG_SHOW_INFO) {
9593                Log.v(TAG, "  "
9594                        + (p.info.nonLocalizedLabel != null
9595                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9596                Log.v(TAG, "    Class=" + p.info.name);
9597            }
9598            final int NI = p.intents.size();
9599            int j;
9600            for (j = 0; j < NI; j++) {
9601                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9602                if (DEBUG_SHOW_INFO) {
9603                    Log.v(TAG, "    IntentFilter:");
9604                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9605                }
9606                if (!intent.debugCheck()) {
9607                    Log.w(TAG, "==> For Provider " + p.info.name);
9608                }
9609                addFilter(intent);
9610            }
9611        }
9612
9613        public final void removeProvider(PackageParser.Provider p) {
9614            mProviders.remove(p.getComponentName());
9615            if (DEBUG_SHOW_INFO) {
9616                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9617                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9618                Log.v(TAG, "    Class=" + p.info.name);
9619            }
9620            final int NI = p.intents.size();
9621            int j;
9622            for (j = 0; j < NI; j++) {
9623                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9624                if (DEBUG_SHOW_INFO) {
9625                    Log.v(TAG, "    IntentFilter:");
9626                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9627                }
9628                removeFilter(intent);
9629            }
9630        }
9631
9632        @Override
9633        protected boolean allowFilterResult(
9634                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9635            ProviderInfo filterPi = filter.provider.info;
9636            for (int i = dest.size() - 1; i >= 0; i--) {
9637                ProviderInfo destPi = dest.get(i).providerInfo;
9638                if (destPi.name == filterPi.name
9639                        && destPi.packageName == filterPi.packageName) {
9640                    return false;
9641                }
9642            }
9643            return true;
9644        }
9645
9646        @Override
9647        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9648            return new PackageParser.ProviderIntentInfo[size];
9649        }
9650
9651        @Override
9652        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9653            if (!sUserManager.exists(userId))
9654                return true;
9655            PackageParser.Package p = filter.provider.owner;
9656            if (p != null) {
9657                PackageSetting ps = (PackageSetting) p.mExtras;
9658                if (ps != null) {
9659                    // System apps are never considered stopped for purposes of
9660                    // filtering, because there may be no way for the user to
9661                    // actually re-launch them.
9662                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9663                            && ps.getStopped(userId);
9664                }
9665            }
9666            return false;
9667        }
9668
9669        @Override
9670        protected boolean isPackageForFilter(String packageName,
9671                PackageParser.ProviderIntentInfo info) {
9672            return packageName.equals(info.provider.owner.packageName);
9673        }
9674
9675        @Override
9676        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9677                int match, int userId) {
9678            if (!sUserManager.exists(userId))
9679                return null;
9680            final PackageParser.ProviderIntentInfo info = filter;
9681            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9682                return null;
9683            }
9684            final PackageParser.Provider provider = info.provider;
9685            if (mSafeMode && (provider.info.applicationInfo.flags
9686                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9687                return null;
9688            }
9689            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9690            if (ps == null) {
9691                return null;
9692            }
9693            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9694                    ps.readUserState(userId), userId);
9695            if (pi == null) {
9696                return null;
9697            }
9698            final ResolveInfo res = new ResolveInfo();
9699            res.providerInfo = pi;
9700            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9701                res.filter = filter;
9702            }
9703            res.priority = info.getPriority();
9704            res.preferredOrder = provider.owner.mPreferredOrder;
9705            res.match = match;
9706            res.isDefault = info.hasDefault;
9707            res.labelRes = info.labelRes;
9708            res.nonLocalizedLabel = info.nonLocalizedLabel;
9709            res.icon = info.icon;
9710            res.system = res.providerInfo.applicationInfo.isSystemApp();
9711            return res;
9712        }
9713
9714        @Override
9715        protected void sortResults(List<ResolveInfo> results) {
9716            Collections.sort(results, mResolvePrioritySorter);
9717        }
9718
9719        @Override
9720        protected void dumpFilter(PrintWriter out, String prefix,
9721                PackageParser.ProviderIntentInfo filter) {
9722            out.print(prefix);
9723            out.print(
9724                    Integer.toHexString(System.identityHashCode(filter.provider)));
9725            out.print(' ');
9726            filter.provider.printComponentShortName(out);
9727            out.print(" filter ");
9728            out.println(Integer.toHexString(System.identityHashCode(filter)));
9729        }
9730
9731        @Override
9732        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9733            return filter.provider;
9734        }
9735
9736        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9737            PackageParser.Provider provider = (PackageParser.Provider)label;
9738            out.print(prefix); out.print(
9739                    Integer.toHexString(System.identityHashCode(provider)));
9740                    out.print(' ');
9741                    provider.printComponentShortName(out);
9742            if (count > 1) {
9743                out.print(" ("); out.print(count); out.print(" filters)");
9744            }
9745            out.println();
9746        }
9747
9748        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9749                = new ArrayMap<ComponentName, PackageParser.Provider>();
9750        private int mFlags;
9751    }
9752
9753    private static final class EphemeralIntentResolver
9754            extends IntentResolver<IntentFilter, ResolveInfo> {
9755        @Override
9756        protected IntentFilter[] newArray(int size) {
9757            return new IntentFilter[size];
9758        }
9759
9760        @Override
9761        protected boolean isPackageForFilter(String packageName, IntentFilter info) {
9762            return true;
9763        }
9764
9765        @Override
9766        protected ResolveInfo newResult(IntentFilter info, int match, int userId) {
9767            if (!sUserManager.exists(userId)) return null;
9768            final ResolveInfo res = new ResolveInfo();
9769            res.filter = info;
9770            return res;
9771        }
9772    }
9773
9774    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9775            new Comparator<ResolveInfo>() {
9776        public int compare(ResolveInfo r1, ResolveInfo r2) {
9777            int v1 = r1.priority;
9778            int v2 = r2.priority;
9779            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9780            if (v1 != v2) {
9781                return (v1 > v2) ? -1 : 1;
9782            }
9783            v1 = r1.preferredOrder;
9784            v2 = r2.preferredOrder;
9785            if (v1 != v2) {
9786                return (v1 > v2) ? -1 : 1;
9787            }
9788            if (r1.isDefault != r2.isDefault) {
9789                return r1.isDefault ? -1 : 1;
9790            }
9791            v1 = r1.match;
9792            v2 = r2.match;
9793            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9794            if (v1 != v2) {
9795                return (v1 > v2) ? -1 : 1;
9796            }
9797            if (r1.system != r2.system) {
9798                return r1.system ? -1 : 1;
9799            }
9800            return 0;
9801        }
9802    };
9803
9804    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9805            new Comparator<ProviderInfo>() {
9806        public int compare(ProviderInfo p1, ProviderInfo p2) {
9807            final int v1 = p1.initOrder;
9808            final int v2 = p2.initOrder;
9809            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9810        }
9811    };
9812
9813    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9814            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9815            final int[] userIds) {
9816        mHandler.post(new Runnable() {
9817            @Override
9818            public void run() {
9819                try {
9820                    final IActivityManager am = ActivityManagerNative.getDefault();
9821                    if (am == null) return;
9822                    final int[] resolvedUserIds;
9823                    if (userIds == null) {
9824                        resolvedUserIds = am.getRunningUserIds();
9825                    } else {
9826                        resolvedUserIds = userIds;
9827                    }
9828                    for (int id : resolvedUserIds) {
9829                        final Intent intent = new Intent(action,
9830                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9831                        if (extras != null) {
9832                            intent.putExtras(extras);
9833                        }
9834                        if (targetPkg != null) {
9835                            intent.setPackage(targetPkg);
9836                        }
9837                        // Modify the UID when posting to other users
9838                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9839                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9840                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9841                            intent.putExtra(Intent.EXTRA_UID, uid);
9842                        }
9843                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9844                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9845                        if (DEBUG_BROADCASTS) {
9846                            RuntimeException here = new RuntimeException("here");
9847                            here.fillInStackTrace();
9848                            Slog.d(TAG, "Sending to user " + id + ": "
9849                                    + intent.toShortString(false, true, false, false)
9850                                    + " " + intent.getExtras(), here);
9851                        }
9852                        am.broadcastIntent(null, intent, null, finishedReceiver,
9853                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9854                                null, finishedReceiver != null, false, id);
9855                    }
9856                } catch (RemoteException ex) {
9857                }
9858            }
9859        });
9860    }
9861
9862    /**
9863     * Check if the external storage media is available. This is true if there
9864     * is a mounted external storage medium or if the external storage is
9865     * emulated.
9866     */
9867    private boolean isExternalMediaAvailable() {
9868        return mMediaMounted || Environment.isExternalStorageEmulated();
9869    }
9870
9871    @Override
9872    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9873        // writer
9874        synchronized (mPackages) {
9875            if (!isExternalMediaAvailable()) {
9876                // If the external storage is no longer mounted at this point,
9877                // the caller may not have been able to delete all of this
9878                // packages files and can not delete any more.  Bail.
9879                return null;
9880            }
9881            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9882            if (lastPackage != null) {
9883                pkgs.remove(lastPackage);
9884            }
9885            if (pkgs.size() > 0) {
9886                return pkgs.get(0);
9887            }
9888        }
9889        return null;
9890    }
9891
9892    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9893        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9894                userId, andCode ? 1 : 0, packageName);
9895        if (mSystemReady) {
9896            msg.sendToTarget();
9897        } else {
9898            if (mPostSystemReadyMessages == null) {
9899                mPostSystemReadyMessages = new ArrayList<>();
9900            }
9901            mPostSystemReadyMessages.add(msg);
9902        }
9903    }
9904
9905    void startCleaningPackages() {
9906        // reader
9907        synchronized (mPackages) {
9908            if (!isExternalMediaAvailable()) {
9909                return;
9910            }
9911            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9912                return;
9913            }
9914        }
9915        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9916        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9917        IActivityManager am = ActivityManagerNative.getDefault();
9918        if (am != null) {
9919            try {
9920                am.startService(null, intent, null, mContext.getOpPackageName(),
9921                        UserHandle.USER_SYSTEM);
9922            } catch (RemoteException e) {
9923            }
9924        }
9925    }
9926
9927    @Override
9928    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9929            int installFlags, String installerPackageName, VerificationParams verificationParams,
9930            String packageAbiOverride) {
9931        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9932                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9933    }
9934
9935    @Override
9936    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9937            int installFlags, String installerPackageName, VerificationParams verificationParams,
9938            String packageAbiOverride, int userId) {
9939        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9940
9941        final int callingUid = Binder.getCallingUid();
9942        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9943
9944        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9945            try {
9946                if (observer != null) {
9947                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9948                }
9949            } catch (RemoteException re) {
9950            }
9951            return;
9952        }
9953
9954        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9955            installFlags |= PackageManager.INSTALL_FROM_ADB;
9956
9957        } else {
9958            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9959            // about installerPackageName.
9960
9961            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9962            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9963        }
9964
9965        UserHandle user;
9966        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9967            user = UserHandle.ALL;
9968        } else {
9969            user = new UserHandle(userId);
9970        }
9971
9972        // Only system components can circumvent runtime permissions when installing.
9973        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9974                && mContext.checkCallingOrSelfPermission(Manifest.permission
9975                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9976            throw new SecurityException("You need the "
9977                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9978                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9979        }
9980
9981        verificationParams.setInstallerUid(callingUid);
9982
9983        final File originFile = new File(originPath);
9984        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9985
9986        final Message msg = mHandler.obtainMessage(INIT_COPY);
9987        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9988                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9989        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9990        msg.obj = params;
9991
9992        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9993                System.identityHashCode(msg.obj));
9994        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9995                System.identityHashCode(msg.obj));
9996
9997        mHandler.sendMessage(msg);
9998    }
9999
10000    void installStage(String packageName, File stagedDir, String stagedCid,
10001            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10002            String installerPackageName, int installerUid, UserHandle user) {
10003        if (DEBUG_EPHEMERAL) {
10004            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10005                Slog.d(TAG, "Ephemeral install of " + packageName);
10006            }
10007        }
10008        final VerificationParams verifParams = new VerificationParams(
10009                null, sessionParams.originatingUri, sessionParams.referrerUri,
10010                sessionParams.originatingUid, null);
10011        verifParams.setInstallerUid(installerUid);
10012
10013        final OriginInfo origin;
10014        if (stagedDir != null) {
10015            origin = OriginInfo.fromStagedFile(stagedDir);
10016        } else {
10017            origin = OriginInfo.fromStagedContainer(stagedCid);
10018        }
10019
10020        final Message msg = mHandler.obtainMessage(INIT_COPY);
10021        final InstallParams params = new InstallParams(origin, null, observer,
10022                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10023                verifParams, user, sessionParams.abiOverride,
10024                sessionParams.grantedRuntimePermissions);
10025        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10026        msg.obj = params;
10027
10028        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10029                System.identityHashCode(msg.obj));
10030        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10031                System.identityHashCode(msg.obj));
10032
10033        mHandler.sendMessage(msg);
10034    }
10035
10036    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10037        Bundle extras = new Bundle(1);
10038        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10039
10040        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10041                packageName, extras, 0, null, null, new int[] {userId});
10042        try {
10043            IActivityManager am = ActivityManagerNative.getDefault();
10044            final boolean isSystem =
10045                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10046            if (isSystem && am.isUserRunning(userId, 0)) {
10047                // The just-installed/enabled app is bundled on the system, so presumed
10048                // to be able to run automatically without needing an explicit launch.
10049                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10050                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10051                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10052                        .setPackage(packageName);
10053                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10054                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10055            }
10056        } catch (RemoteException e) {
10057            // shouldn't happen
10058            Slog.w(TAG, "Unable to bootstrap installed package", e);
10059        }
10060    }
10061
10062    @Override
10063    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10064            int userId) {
10065        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10066        PackageSetting pkgSetting;
10067        final int uid = Binder.getCallingUid();
10068        enforceCrossUserPermission(uid, userId, true, true,
10069                "setApplicationHiddenSetting for user " + userId);
10070
10071        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10072            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10073            return false;
10074        }
10075
10076        long callingId = Binder.clearCallingIdentity();
10077        try {
10078            boolean sendAdded = false;
10079            boolean sendRemoved = false;
10080            // writer
10081            synchronized (mPackages) {
10082                pkgSetting = mSettings.mPackages.get(packageName);
10083                if (pkgSetting == null) {
10084                    return false;
10085                }
10086                if (pkgSetting.getHidden(userId) != hidden) {
10087                    pkgSetting.setHidden(hidden, userId);
10088                    mSettings.writePackageRestrictionsLPr(userId);
10089                    if (hidden) {
10090                        sendRemoved = true;
10091                    } else {
10092                        sendAdded = true;
10093                    }
10094                }
10095            }
10096            if (sendAdded) {
10097                sendPackageAddedForUser(packageName, pkgSetting, userId);
10098                return true;
10099            }
10100            if (sendRemoved) {
10101                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10102                        "hiding pkg");
10103                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10104                return true;
10105            }
10106        } finally {
10107            Binder.restoreCallingIdentity(callingId);
10108        }
10109        return false;
10110    }
10111
10112    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10113            int userId) {
10114        final PackageRemovedInfo info = new PackageRemovedInfo();
10115        info.removedPackage = packageName;
10116        info.removedUsers = new int[] {userId};
10117        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10118        info.sendBroadcast(false, false, false);
10119    }
10120
10121    /**
10122     * Returns true if application is not found or there was an error. Otherwise it returns
10123     * the hidden state of the package for the given user.
10124     */
10125    @Override
10126    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10127        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10128        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10129                false, "getApplicationHidden for user " + userId);
10130        PackageSetting pkgSetting;
10131        long callingId = Binder.clearCallingIdentity();
10132        try {
10133            // writer
10134            synchronized (mPackages) {
10135                pkgSetting = mSettings.mPackages.get(packageName);
10136                if (pkgSetting == null) {
10137                    return true;
10138                }
10139                return pkgSetting.getHidden(userId);
10140            }
10141        } finally {
10142            Binder.restoreCallingIdentity(callingId);
10143        }
10144    }
10145
10146    /**
10147     * @hide
10148     */
10149    @Override
10150    public int installExistingPackageAsUser(String packageName, int userId) {
10151        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10152                null);
10153        PackageSetting pkgSetting;
10154        final int uid = Binder.getCallingUid();
10155        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10156                + userId);
10157        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10158            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10159        }
10160
10161        long callingId = Binder.clearCallingIdentity();
10162        try {
10163            boolean sendAdded = false;
10164
10165            // writer
10166            synchronized (mPackages) {
10167                pkgSetting = mSettings.mPackages.get(packageName);
10168                if (pkgSetting == null) {
10169                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10170                }
10171                if (!pkgSetting.getInstalled(userId)) {
10172                    pkgSetting.setInstalled(true, userId);
10173                    pkgSetting.setHidden(false, userId);
10174                    mSettings.writePackageRestrictionsLPr(userId);
10175                    sendAdded = true;
10176                }
10177            }
10178
10179            if (sendAdded) {
10180                sendPackageAddedForUser(packageName, pkgSetting, userId);
10181            }
10182        } finally {
10183            Binder.restoreCallingIdentity(callingId);
10184        }
10185
10186        return PackageManager.INSTALL_SUCCEEDED;
10187    }
10188
10189    boolean isUserRestricted(int userId, String restrictionKey) {
10190        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10191        if (restrictions.getBoolean(restrictionKey, false)) {
10192            Log.w(TAG, "User is restricted: " + restrictionKey);
10193            return true;
10194        }
10195        return false;
10196    }
10197
10198    @Override
10199    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10200        mContext.enforceCallingOrSelfPermission(
10201                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10202                "Only package verification agents can verify applications");
10203
10204        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10205        final PackageVerificationResponse response = new PackageVerificationResponse(
10206                verificationCode, Binder.getCallingUid());
10207        msg.arg1 = id;
10208        msg.obj = response;
10209        mHandler.sendMessage(msg);
10210    }
10211
10212    @Override
10213    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10214            long millisecondsToDelay) {
10215        mContext.enforceCallingOrSelfPermission(
10216                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10217                "Only package verification agents can extend verification timeouts");
10218
10219        final PackageVerificationState state = mPendingVerification.get(id);
10220        final PackageVerificationResponse response = new PackageVerificationResponse(
10221                verificationCodeAtTimeout, Binder.getCallingUid());
10222
10223        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10224            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10225        }
10226        if (millisecondsToDelay < 0) {
10227            millisecondsToDelay = 0;
10228        }
10229        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10230                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10231            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10232        }
10233
10234        if ((state != null) && !state.timeoutExtended()) {
10235            state.extendTimeout();
10236
10237            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10238            msg.arg1 = id;
10239            msg.obj = response;
10240            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10241        }
10242    }
10243
10244    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10245            int verificationCode, UserHandle user) {
10246        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10247        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10248        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10249        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10250        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10251
10252        mContext.sendBroadcastAsUser(intent, user,
10253                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10254    }
10255
10256    private ComponentName matchComponentForVerifier(String packageName,
10257            List<ResolveInfo> receivers) {
10258        ActivityInfo targetReceiver = null;
10259
10260        final int NR = receivers.size();
10261        for (int i = 0; i < NR; i++) {
10262            final ResolveInfo info = receivers.get(i);
10263            if (info.activityInfo == null) {
10264                continue;
10265            }
10266
10267            if (packageName.equals(info.activityInfo.packageName)) {
10268                targetReceiver = info.activityInfo;
10269                break;
10270            }
10271        }
10272
10273        if (targetReceiver == null) {
10274            return null;
10275        }
10276
10277        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10278    }
10279
10280    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10281            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10282        if (pkgInfo.verifiers.length == 0) {
10283            return null;
10284        }
10285
10286        final int N = pkgInfo.verifiers.length;
10287        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10288        for (int i = 0; i < N; i++) {
10289            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10290
10291            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10292                    receivers);
10293            if (comp == null) {
10294                continue;
10295            }
10296
10297            final int verifierUid = getUidForVerifier(verifierInfo);
10298            if (verifierUid == -1) {
10299                continue;
10300            }
10301
10302            if (DEBUG_VERIFY) {
10303                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10304                        + " with the correct signature");
10305            }
10306            sufficientVerifiers.add(comp);
10307            verificationState.addSufficientVerifier(verifierUid);
10308        }
10309
10310        return sufficientVerifiers;
10311    }
10312
10313    private int getUidForVerifier(VerifierInfo verifierInfo) {
10314        synchronized (mPackages) {
10315            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10316            if (pkg == null) {
10317                return -1;
10318            } else if (pkg.mSignatures.length != 1) {
10319                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10320                        + " has more than one signature; ignoring");
10321                return -1;
10322            }
10323
10324            /*
10325             * If the public key of the package's signature does not match
10326             * our expected public key, then this is a different package and
10327             * we should skip.
10328             */
10329
10330            final byte[] expectedPublicKey;
10331            try {
10332                final Signature verifierSig = pkg.mSignatures[0];
10333                final PublicKey publicKey = verifierSig.getPublicKey();
10334                expectedPublicKey = publicKey.getEncoded();
10335            } catch (CertificateException e) {
10336                return -1;
10337            }
10338
10339            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10340
10341            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10342                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10343                        + " does not have the expected public key; ignoring");
10344                return -1;
10345            }
10346
10347            return pkg.applicationInfo.uid;
10348        }
10349    }
10350
10351    @Override
10352    public void finishPackageInstall(int token) {
10353        enforceSystemOrRoot("Only the system is allowed to finish installs");
10354
10355        if (DEBUG_INSTALL) {
10356            Slog.v(TAG, "BM finishing package install for " + token);
10357        }
10358        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10359
10360        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10361        mHandler.sendMessage(msg);
10362    }
10363
10364    /**
10365     * Get the verification agent timeout.
10366     *
10367     * @return verification timeout in milliseconds
10368     */
10369    private long getVerificationTimeout() {
10370        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10371                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10372                DEFAULT_VERIFICATION_TIMEOUT);
10373    }
10374
10375    /**
10376     * Get the default verification agent response code.
10377     *
10378     * @return default verification response code
10379     */
10380    private int getDefaultVerificationResponse() {
10381        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10382                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10383                DEFAULT_VERIFICATION_RESPONSE);
10384    }
10385
10386    /**
10387     * Check whether or not package verification has been enabled.
10388     *
10389     * @return true if verification should be performed
10390     */
10391    private boolean isVerificationEnabled(int userId, int installFlags) {
10392        if (!DEFAULT_VERIFY_ENABLE) {
10393            return false;
10394        }
10395        // TODO: fix b/25118622; don't bypass verification
10396        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10397            return false;
10398        }
10399        // Ephemeral apps don't get the full verification treatment
10400        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10401            if (DEBUG_EPHEMERAL) {
10402                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10403            }
10404            return false;
10405        }
10406
10407        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10408
10409        // Check if installing from ADB
10410        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10411            // Do not run verification in a test harness environment
10412            if (ActivityManager.isRunningInTestHarness()) {
10413                return false;
10414            }
10415            if (ensureVerifyAppsEnabled) {
10416                return true;
10417            }
10418            // Check if the developer does not want package verification for ADB installs
10419            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10420                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10421                return false;
10422            }
10423        }
10424
10425        if (ensureVerifyAppsEnabled) {
10426            return true;
10427        }
10428
10429        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10430                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10431    }
10432
10433    @Override
10434    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10435            throws RemoteException {
10436        mContext.enforceCallingOrSelfPermission(
10437                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10438                "Only intentfilter verification agents can verify applications");
10439
10440        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10441        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10442                Binder.getCallingUid(), verificationCode, failedDomains);
10443        msg.arg1 = id;
10444        msg.obj = response;
10445        mHandler.sendMessage(msg);
10446    }
10447
10448    @Override
10449    public int getIntentVerificationStatus(String packageName, int userId) {
10450        synchronized (mPackages) {
10451            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10452        }
10453    }
10454
10455    @Override
10456    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10457        mContext.enforceCallingOrSelfPermission(
10458                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10459
10460        boolean result = false;
10461        synchronized (mPackages) {
10462            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10463        }
10464        if (result) {
10465            scheduleWritePackageRestrictionsLocked(userId);
10466        }
10467        return result;
10468    }
10469
10470    @Override
10471    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10472        synchronized (mPackages) {
10473            return mSettings.getIntentFilterVerificationsLPr(packageName);
10474        }
10475    }
10476
10477    @Override
10478    public List<IntentFilter> getAllIntentFilters(String packageName) {
10479        if (TextUtils.isEmpty(packageName)) {
10480            return Collections.<IntentFilter>emptyList();
10481        }
10482        synchronized (mPackages) {
10483            PackageParser.Package pkg = mPackages.get(packageName);
10484            if (pkg == null || pkg.activities == null) {
10485                return Collections.<IntentFilter>emptyList();
10486            }
10487            final int count = pkg.activities.size();
10488            ArrayList<IntentFilter> result = new ArrayList<>();
10489            for (int n=0; n<count; n++) {
10490                PackageParser.Activity activity = pkg.activities.get(n);
10491                if (activity.intents != null || activity.intents.size() > 0) {
10492                    result.addAll(activity.intents);
10493                }
10494            }
10495            return result;
10496        }
10497    }
10498
10499    @Override
10500    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10501        mContext.enforceCallingOrSelfPermission(
10502                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10503
10504        synchronized (mPackages) {
10505            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10506            if (packageName != null) {
10507                result |= updateIntentVerificationStatus(packageName,
10508                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10509                        userId);
10510                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10511                        packageName, userId);
10512            }
10513            return result;
10514        }
10515    }
10516
10517    @Override
10518    public String getDefaultBrowserPackageName(int userId) {
10519        synchronized (mPackages) {
10520            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10521        }
10522    }
10523
10524    /**
10525     * Get the "allow unknown sources" setting.
10526     *
10527     * @return the current "allow unknown sources" setting
10528     */
10529    private int getUnknownSourcesSettings() {
10530        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10531                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10532                -1);
10533    }
10534
10535    @Override
10536    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10537        final int uid = Binder.getCallingUid();
10538        // writer
10539        synchronized (mPackages) {
10540            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10541            if (targetPackageSetting == null) {
10542                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10543            }
10544
10545            PackageSetting installerPackageSetting;
10546            if (installerPackageName != null) {
10547                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10548                if (installerPackageSetting == null) {
10549                    throw new IllegalArgumentException("Unknown installer package: "
10550                            + installerPackageName);
10551                }
10552            } else {
10553                installerPackageSetting = null;
10554            }
10555
10556            Signature[] callerSignature;
10557            Object obj = mSettings.getUserIdLPr(uid);
10558            if (obj != null) {
10559                if (obj instanceof SharedUserSetting) {
10560                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10561                } else if (obj instanceof PackageSetting) {
10562                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10563                } else {
10564                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10565                }
10566            } else {
10567                throw new SecurityException("Unknown calling uid " + uid);
10568            }
10569
10570            // Verify: can't set installerPackageName to a package that is
10571            // not signed with the same cert as the caller.
10572            if (installerPackageSetting != null) {
10573                if (compareSignatures(callerSignature,
10574                        installerPackageSetting.signatures.mSignatures)
10575                        != PackageManager.SIGNATURE_MATCH) {
10576                    throw new SecurityException(
10577                            "Caller does not have same cert as new installer package "
10578                            + installerPackageName);
10579                }
10580            }
10581
10582            // Verify: if target already has an installer package, it must
10583            // be signed with the same cert as the caller.
10584            if (targetPackageSetting.installerPackageName != null) {
10585                PackageSetting setting = mSettings.mPackages.get(
10586                        targetPackageSetting.installerPackageName);
10587                // If the currently set package isn't valid, then it's always
10588                // okay to change it.
10589                if (setting != null) {
10590                    if (compareSignatures(callerSignature,
10591                            setting.signatures.mSignatures)
10592                            != PackageManager.SIGNATURE_MATCH) {
10593                        throw new SecurityException(
10594                                "Caller does not have same cert as old installer package "
10595                                + targetPackageSetting.installerPackageName);
10596                    }
10597                }
10598            }
10599
10600            // Okay!
10601            targetPackageSetting.installerPackageName = installerPackageName;
10602            scheduleWriteSettingsLocked();
10603        }
10604    }
10605
10606    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10607        // Queue up an async operation since the package installation may take a little while.
10608        mHandler.post(new Runnable() {
10609            public void run() {
10610                mHandler.removeCallbacks(this);
10611                 // Result object to be returned
10612                PackageInstalledInfo res = new PackageInstalledInfo();
10613                res.returnCode = currentStatus;
10614                res.uid = -1;
10615                res.pkg = null;
10616                res.removedInfo = new PackageRemovedInfo();
10617                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10618                    args.doPreInstall(res.returnCode);
10619                    synchronized (mInstallLock) {
10620                        installPackageTracedLI(args, res);
10621                    }
10622                    args.doPostInstall(res.returnCode, res.uid);
10623                }
10624
10625                // A restore should be performed at this point if (a) the install
10626                // succeeded, (b) the operation is not an update, and (c) the new
10627                // package has not opted out of backup participation.
10628                final boolean update = res.removedInfo.removedPackage != null;
10629                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10630                boolean doRestore = !update
10631                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10632
10633                // Set up the post-install work request bookkeeping.  This will be used
10634                // and cleaned up by the post-install event handling regardless of whether
10635                // there's a restore pass performed.  Token values are >= 1.
10636                int token;
10637                if (mNextInstallToken < 0) mNextInstallToken = 1;
10638                token = mNextInstallToken++;
10639
10640                PostInstallData data = new PostInstallData(args, res);
10641                mRunningInstalls.put(token, data);
10642                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10643
10644                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10645                    // Pass responsibility to the Backup Manager.  It will perform a
10646                    // restore if appropriate, then pass responsibility back to the
10647                    // Package Manager to run the post-install observer callbacks
10648                    // and broadcasts.
10649                    IBackupManager bm = IBackupManager.Stub.asInterface(
10650                            ServiceManager.getService(Context.BACKUP_SERVICE));
10651                    if (bm != null) {
10652                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10653                                + " to BM for possible restore");
10654                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10655                        try {
10656                            // TODO: http://b/22388012
10657                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10658                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10659                            } else {
10660                                doRestore = false;
10661                            }
10662                        } catch (RemoteException e) {
10663                            // can't happen; the backup manager is local
10664                        } catch (Exception e) {
10665                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10666                            doRestore = false;
10667                        }
10668                    } else {
10669                        Slog.e(TAG, "Backup Manager not found!");
10670                        doRestore = false;
10671                    }
10672                }
10673
10674                if (!doRestore) {
10675                    // No restore possible, or the Backup Manager was mysteriously not
10676                    // available -- just fire the post-install work request directly.
10677                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10678
10679                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10680
10681                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10682                    mHandler.sendMessage(msg);
10683                }
10684            }
10685        });
10686    }
10687
10688    private abstract class HandlerParams {
10689        private static final int MAX_RETRIES = 4;
10690
10691        /**
10692         * Number of times startCopy() has been attempted and had a non-fatal
10693         * error.
10694         */
10695        private int mRetries = 0;
10696
10697        /** User handle for the user requesting the information or installation. */
10698        private final UserHandle mUser;
10699        String traceMethod;
10700        int traceCookie;
10701
10702        HandlerParams(UserHandle user) {
10703            mUser = user;
10704        }
10705
10706        UserHandle getUser() {
10707            return mUser;
10708        }
10709
10710        HandlerParams setTraceMethod(String traceMethod) {
10711            this.traceMethod = traceMethod;
10712            return this;
10713        }
10714
10715        HandlerParams setTraceCookie(int traceCookie) {
10716            this.traceCookie = traceCookie;
10717            return this;
10718        }
10719
10720        final boolean startCopy() {
10721            boolean res;
10722            try {
10723                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10724
10725                if (++mRetries > MAX_RETRIES) {
10726                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10727                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10728                    handleServiceError();
10729                    return false;
10730                } else {
10731                    handleStartCopy();
10732                    res = true;
10733                }
10734            } catch (RemoteException e) {
10735                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10736                mHandler.sendEmptyMessage(MCS_RECONNECT);
10737                res = false;
10738            }
10739            handleReturnCode();
10740            return res;
10741        }
10742
10743        final void serviceError() {
10744            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10745            handleServiceError();
10746            handleReturnCode();
10747        }
10748
10749        abstract void handleStartCopy() throws RemoteException;
10750        abstract void handleServiceError();
10751        abstract void handleReturnCode();
10752    }
10753
10754    class MeasureParams extends HandlerParams {
10755        private final PackageStats mStats;
10756        private boolean mSuccess;
10757
10758        private final IPackageStatsObserver mObserver;
10759
10760        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10761            super(new UserHandle(stats.userHandle));
10762            mObserver = observer;
10763            mStats = stats;
10764        }
10765
10766        @Override
10767        public String toString() {
10768            return "MeasureParams{"
10769                + Integer.toHexString(System.identityHashCode(this))
10770                + " " + mStats.packageName + "}";
10771        }
10772
10773        @Override
10774        void handleStartCopy() throws RemoteException {
10775            synchronized (mInstallLock) {
10776                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10777            }
10778
10779            if (mSuccess) {
10780                final boolean mounted;
10781                if (Environment.isExternalStorageEmulated()) {
10782                    mounted = true;
10783                } else {
10784                    final String status = Environment.getExternalStorageState();
10785                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10786                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10787                }
10788
10789                if (mounted) {
10790                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10791
10792                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10793                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10794
10795                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10796                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10797
10798                    // Always subtract cache size, since it's a subdirectory
10799                    mStats.externalDataSize -= mStats.externalCacheSize;
10800
10801                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10802                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10803
10804                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10805                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10806                }
10807            }
10808        }
10809
10810        @Override
10811        void handleReturnCode() {
10812            if (mObserver != null) {
10813                try {
10814                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10815                } catch (RemoteException e) {
10816                    Slog.i(TAG, "Observer no longer exists.");
10817                }
10818            }
10819        }
10820
10821        @Override
10822        void handleServiceError() {
10823            Slog.e(TAG, "Could not measure application " + mStats.packageName
10824                            + " external storage");
10825        }
10826    }
10827
10828    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10829            throws RemoteException {
10830        long result = 0;
10831        for (File path : paths) {
10832            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10833        }
10834        return result;
10835    }
10836
10837    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10838        for (File path : paths) {
10839            try {
10840                mcs.clearDirectory(path.getAbsolutePath());
10841            } catch (RemoteException e) {
10842            }
10843        }
10844    }
10845
10846    static class OriginInfo {
10847        /**
10848         * Location where install is coming from, before it has been
10849         * copied/renamed into place. This could be a single monolithic APK
10850         * file, or a cluster directory. This location may be untrusted.
10851         */
10852        final File file;
10853        final String cid;
10854
10855        /**
10856         * Flag indicating that {@link #file} or {@link #cid} has already been
10857         * staged, meaning downstream users don't need to defensively copy the
10858         * contents.
10859         */
10860        final boolean staged;
10861
10862        /**
10863         * Flag indicating that {@link #file} or {@link #cid} is an already
10864         * installed app that is being moved.
10865         */
10866        final boolean existing;
10867
10868        final String resolvedPath;
10869        final File resolvedFile;
10870
10871        static OriginInfo fromNothing() {
10872            return new OriginInfo(null, null, false, false);
10873        }
10874
10875        static OriginInfo fromUntrustedFile(File file) {
10876            return new OriginInfo(file, null, false, false);
10877        }
10878
10879        static OriginInfo fromExistingFile(File file) {
10880            return new OriginInfo(file, null, false, true);
10881        }
10882
10883        static OriginInfo fromStagedFile(File file) {
10884            return new OriginInfo(file, null, true, false);
10885        }
10886
10887        static OriginInfo fromStagedContainer(String cid) {
10888            return new OriginInfo(null, cid, true, false);
10889        }
10890
10891        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10892            this.file = file;
10893            this.cid = cid;
10894            this.staged = staged;
10895            this.existing = existing;
10896
10897            if (cid != null) {
10898                resolvedPath = PackageHelper.getSdDir(cid);
10899                resolvedFile = new File(resolvedPath);
10900            } else if (file != null) {
10901                resolvedPath = file.getAbsolutePath();
10902                resolvedFile = file;
10903            } else {
10904                resolvedPath = null;
10905                resolvedFile = null;
10906            }
10907        }
10908    }
10909
10910    class MoveInfo {
10911        final int moveId;
10912        final String fromUuid;
10913        final String toUuid;
10914        final String packageName;
10915        final String dataAppName;
10916        final int appId;
10917        final String seinfo;
10918
10919        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10920                String dataAppName, int appId, String seinfo) {
10921            this.moveId = moveId;
10922            this.fromUuid = fromUuid;
10923            this.toUuid = toUuid;
10924            this.packageName = packageName;
10925            this.dataAppName = dataAppName;
10926            this.appId = appId;
10927            this.seinfo = seinfo;
10928        }
10929    }
10930
10931    class InstallParams extends HandlerParams {
10932        final OriginInfo origin;
10933        final MoveInfo move;
10934        final IPackageInstallObserver2 observer;
10935        int installFlags;
10936        final String installerPackageName;
10937        final String volumeUuid;
10938        final VerificationParams verificationParams;
10939        private InstallArgs mArgs;
10940        private int mRet;
10941        final String packageAbiOverride;
10942        final String[] grantedRuntimePermissions;
10943
10944        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10945                int installFlags, String installerPackageName, String volumeUuid,
10946                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10947                String[] grantedPermissions) {
10948            super(user);
10949            this.origin = origin;
10950            this.move = move;
10951            this.observer = observer;
10952            this.installFlags = installFlags;
10953            this.installerPackageName = installerPackageName;
10954            this.volumeUuid = volumeUuid;
10955            this.verificationParams = verificationParams;
10956            this.packageAbiOverride = packageAbiOverride;
10957            this.grantedRuntimePermissions = grantedPermissions;
10958        }
10959
10960        @Override
10961        public String toString() {
10962            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10963                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10964        }
10965
10966        public ManifestDigest getManifestDigest() {
10967            if (verificationParams == null) {
10968                return null;
10969            }
10970            return verificationParams.getManifestDigest();
10971        }
10972
10973        private int installLocationPolicy(PackageInfoLite pkgLite) {
10974            String packageName = pkgLite.packageName;
10975            int installLocation = pkgLite.installLocation;
10976            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10977            // reader
10978            synchronized (mPackages) {
10979                PackageParser.Package pkg = mPackages.get(packageName);
10980                if (pkg != null) {
10981                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10982                        // Check for downgrading.
10983                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10984                            try {
10985                                checkDowngrade(pkg, pkgLite);
10986                            } catch (PackageManagerException e) {
10987                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10988                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10989                            }
10990                        }
10991                        // Check for updated system application.
10992                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10993                            if (onSd) {
10994                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10995                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10996                            }
10997                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10998                        } else {
10999                            if (onSd) {
11000                                // Install flag overrides everything.
11001                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11002                            }
11003                            // If current upgrade specifies particular preference
11004                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11005                                // Application explicitly specified internal.
11006                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11007                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11008                                // App explictly prefers external. Let policy decide
11009                            } else {
11010                                // Prefer previous location
11011                                if (isExternal(pkg)) {
11012                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11013                                }
11014                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11015                            }
11016                        }
11017                    } else {
11018                        // Invalid install. Return error code
11019                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11020                    }
11021                }
11022            }
11023            // All the special cases have been taken care of.
11024            // Return result based on recommended install location.
11025            if (onSd) {
11026                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11027            }
11028            return pkgLite.recommendedInstallLocation;
11029        }
11030
11031        /*
11032         * Invoke remote method to get package information and install
11033         * location values. Override install location based on default
11034         * policy if needed and then create install arguments based
11035         * on the install location.
11036         */
11037        public void handleStartCopy() throws RemoteException {
11038            int ret = PackageManager.INSTALL_SUCCEEDED;
11039
11040            // If we're already staged, we've firmly committed to an install location
11041            if (origin.staged) {
11042                if (origin.file != null) {
11043                    installFlags |= PackageManager.INSTALL_INTERNAL;
11044                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11045                } else if (origin.cid != null) {
11046                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11047                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11048                } else {
11049                    throw new IllegalStateException("Invalid stage location");
11050                }
11051            }
11052
11053            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11054            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11055            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11056            PackageInfoLite pkgLite = null;
11057
11058            if (onInt && onSd) {
11059                // Check if both bits are set.
11060                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11061                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11062            } else if (onSd && ephemeral) {
11063                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11064                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11065            } else {
11066                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11067                        packageAbiOverride);
11068
11069                if (DEBUG_EPHEMERAL && ephemeral) {
11070                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11071                }
11072
11073                /*
11074                 * If we have too little free space, try to free cache
11075                 * before giving up.
11076                 */
11077                if (!origin.staged && pkgLite.recommendedInstallLocation
11078                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11079                    // TODO: focus freeing disk space on the target device
11080                    final StorageManager storage = StorageManager.from(mContext);
11081                    final long lowThreshold = storage.getStorageLowBytes(
11082                            Environment.getDataDirectory());
11083
11084                    final long sizeBytes = mContainerService.calculateInstalledSize(
11085                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11086
11087                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11088                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11089                                installFlags, packageAbiOverride);
11090                    }
11091
11092                    /*
11093                     * The cache free must have deleted the file we
11094                     * downloaded to install.
11095                     *
11096                     * TODO: fix the "freeCache" call to not delete
11097                     *       the file we care about.
11098                     */
11099                    if (pkgLite.recommendedInstallLocation
11100                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11101                        pkgLite.recommendedInstallLocation
11102                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11103                    }
11104                }
11105            }
11106
11107            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11108                int loc = pkgLite.recommendedInstallLocation;
11109                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11110                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11111                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11112                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11113                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11114                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11115                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11116                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11117                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11118                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11119                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11120                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11121                } else {
11122                    // Override with defaults if needed.
11123                    loc = installLocationPolicy(pkgLite);
11124                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11125                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11126                    } else if (!onSd && !onInt) {
11127                        // Override install location with flags
11128                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11129                            // Set the flag to install on external media.
11130                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11131                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11132                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11133                            if (DEBUG_EPHEMERAL) {
11134                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11135                            }
11136                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11137                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11138                                    |PackageManager.INSTALL_INTERNAL);
11139                        } else {
11140                            // Make sure the flag for installing on external
11141                            // media is unset
11142                            installFlags |= PackageManager.INSTALL_INTERNAL;
11143                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11144                        }
11145                    }
11146                }
11147            }
11148
11149            final InstallArgs args = createInstallArgs(this);
11150            mArgs = args;
11151
11152            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11153                // TODO: http://b/22976637
11154                // Apps installed for "all" users use the device owner to verify the app
11155                UserHandle verifierUser = getUser();
11156                if (verifierUser == UserHandle.ALL) {
11157                    verifierUser = UserHandle.SYSTEM;
11158                }
11159
11160                /*
11161                 * Determine if we have any installed package verifiers. If we
11162                 * do, then we'll defer to them to verify the packages.
11163                 */
11164                final int requiredUid = mRequiredVerifierPackage == null ? -1
11165                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11166                if (!origin.existing && requiredUid != -1
11167                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11168                    final Intent verification = new Intent(
11169                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11170                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11171                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11172                            PACKAGE_MIME_TYPE);
11173                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11174
11175                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11176                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11177                            verifierUser.getIdentifier());
11178
11179                    if (DEBUG_VERIFY) {
11180                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11181                                + verification.toString() + " with " + pkgLite.verifiers.length
11182                                + " optional verifiers");
11183                    }
11184
11185                    final int verificationId = mPendingVerificationToken++;
11186
11187                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11188
11189                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11190                            installerPackageName);
11191
11192                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11193                            installFlags);
11194
11195                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11196                            pkgLite.packageName);
11197
11198                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11199                            pkgLite.versionCode);
11200
11201                    if (verificationParams != null) {
11202                        if (verificationParams.getVerificationURI() != null) {
11203                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11204                                 verificationParams.getVerificationURI());
11205                        }
11206                        if (verificationParams.getOriginatingURI() != null) {
11207                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11208                                  verificationParams.getOriginatingURI());
11209                        }
11210                        if (verificationParams.getReferrer() != null) {
11211                            verification.putExtra(Intent.EXTRA_REFERRER,
11212                                  verificationParams.getReferrer());
11213                        }
11214                        if (verificationParams.getOriginatingUid() >= 0) {
11215                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11216                                  verificationParams.getOriginatingUid());
11217                        }
11218                        if (verificationParams.getInstallerUid() >= 0) {
11219                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11220                                  verificationParams.getInstallerUid());
11221                        }
11222                    }
11223
11224                    final PackageVerificationState verificationState = new PackageVerificationState(
11225                            requiredUid, args);
11226
11227                    mPendingVerification.append(verificationId, verificationState);
11228
11229                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11230                            receivers, verificationState);
11231
11232                    /*
11233                     * If any sufficient verifiers were listed in the package
11234                     * manifest, attempt to ask them.
11235                     */
11236                    if (sufficientVerifiers != null) {
11237                        final int N = sufficientVerifiers.size();
11238                        if (N == 0) {
11239                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11240                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11241                        } else {
11242                            for (int i = 0; i < N; i++) {
11243                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11244
11245                                final Intent sufficientIntent = new Intent(verification);
11246                                sufficientIntent.setComponent(verifierComponent);
11247                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11248                            }
11249                        }
11250                    }
11251
11252                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11253                            mRequiredVerifierPackage, receivers);
11254                    if (ret == PackageManager.INSTALL_SUCCEEDED
11255                            && mRequiredVerifierPackage != null) {
11256                        Trace.asyncTraceBegin(
11257                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11258                        /*
11259                         * Send the intent to the required verification agent,
11260                         * but only start the verification timeout after the
11261                         * target BroadcastReceivers have run.
11262                         */
11263                        verification.setComponent(requiredVerifierComponent);
11264                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11265                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11266                                new BroadcastReceiver() {
11267                                    @Override
11268                                    public void onReceive(Context context, Intent intent) {
11269                                        final Message msg = mHandler
11270                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11271                                        msg.arg1 = verificationId;
11272                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11273                                    }
11274                                }, null, 0, null, null);
11275
11276                        /*
11277                         * We don't want the copy to proceed until verification
11278                         * succeeds, so null out this field.
11279                         */
11280                        mArgs = null;
11281                    }
11282                } else {
11283                    /*
11284                     * No package verification is enabled, so immediately start
11285                     * the remote call to initiate copy using temporary file.
11286                     */
11287                    ret = args.copyApk(mContainerService, true);
11288                }
11289            }
11290
11291            mRet = ret;
11292        }
11293
11294        @Override
11295        void handleReturnCode() {
11296            // If mArgs is null, then MCS couldn't be reached. When it
11297            // reconnects, it will try again to install. At that point, this
11298            // will succeed.
11299            if (mArgs != null) {
11300                processPendingInstall(mArgs, mRet);
11301            }
11302        }
11303
11304        @Override
11305        void handleServiceError() {
11306            mArgs = createInstallArgs(this);
11307            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11308        }
11309
11310        public boolean isForwardLocked() {
11311            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11312        }
11313    }
11314
11315    /**
11316     * Used during creation of InstallArgs
11317     *
11318     * @param installFlags package installation flags
11319     * @return true if should be installed on external storage
11320     */
11321    private static boolean installOnExternalAsec(int installFlags) {
11322        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11323            return false;
11324        }
11325        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11326            return true;
11327        }
11328        return false;
11329    }
11330
11331    /**
11332     * Used during creation of InstallArgs
11333     *
11334     * @param installFlags package installation flags
11335     * @return true if should be installed as forward locked
11336     */
11337    private static boolean installForwardLocked(int installFlags) {
11338        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11339    }
11340
11341    private InstallArgs createInstallArgs(InstallParams params) {
11342        if (params.move != null) {
11343            return new MoveInstallArgs(params);
11344        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11345            return new AsecInstallArgs(params);
11346        } else {
11347            return new FileInstallArgs(params);
11348        }
11349    }
11350
11351    /**
11352     * Create args that describe an existing installed package. Typically used
11353     * when cleaning up old installs, or used as a move source.
11354     */
11355    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11356            String resourcePath, String[] instructionSets) {
11357        final boolean isInAsec;
11358        if (installOnExternalAsec(installFlags)) {
11359            /* Apps on SD card are always in ASEC containers. */
11360            isInAsec = true;
11361        } else if (installForwardLocked(installFlags)
11362                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11363            /*
11364             * Forward-locked apps are only in ASEC containers if they're the
11365             * new style
11366             */
11367            isInAsec = true;
11368        } else {
11369            isInAsec = false;
11370        }
11371
11372        if (isInAsec) {
11373            return new AsecInstallArgs(codePath, instructionSets,
11374                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11375        } else {
11376            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11377        }
11378    }
11379
11380    static abstract class InstallArgs {
11381        /** @see InstallParams#origin */
11382        final OriginInfo origin;
11383        /** @see InstallParams#move */
11384        final MoveInfo move;
11385
11386        final IPackageInstallObserver2 observer;
11387        // Always refers to PackageManager flags only
11388        final int installFlags;
11389        final String installerPackageName;
11390        final String volumeUuid;
11391        final ManifestDigest manifestDigest;
11392        final UserHandle user;
11393        final String abiOverride;
11394        final String[] installGrantPermissions;
11395        /** If non-null, drop an async trace when the install completes */
11396        final String traceMethod;
11397        final int traceCookie;
11398
11399        // The list of instruction sets supported by this app. This is currently
11400        // only used during the rmdex() phase to clean up resources. We can get rid of this
11401        // if we move dex files under the common app path.
11402        /* nullable */ String[] instructionSets;
11403
11404        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11405                int installFlags, String installerPackageName, String volumeUuid,
11406                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11407                String abiOverride, String[] installGrantPermissions,
11408                String traceMethod, int traceCookie) {
11409            this.origin = origin;
11410            this.move = move;
11411            this.installFlags = installFlags;
11412            this.observer = observer;
11413            this.installerPackageName = installerPackageName;
11414            this.volumeUuid = volumeUuid;
11415            this.manifestDigest = manifestDigest;
11416            this.user = user;
11417            this.instructionSets = instructionSets;
11418            this.abiOverride = abiOverride;
11419            this.installGrantPermissions = installGrantPermissions;
11420            this.traceMethod = traceMethod;
11421            this.traceCookie = traceCookie;
11422        }
11423
11424        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11425        abstract int doPreInstall(int status);
11426
11427        /**
11428         * Rename package into final resting place. All paths on the given
11429         * scanned package should be updated to reflect the rename.
11430         */
11431        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11432        abstract int doPostInstall(int status, int uid);
11433
11434        /** @see PackageSettingBase#codePathString */
11435        abstract String getCodePath();
11436        /** @see PackageSettingBase#resourcePathString */
11437        abstract String getResourcePath();
11438
11439        // Need installer lock especially for dex file removal.
11440        abstract void cleanUpResourcesLI();
11441        abstract boolean doPostDeleteLI(boolean delete);
11442
11443        /**
11444         * Called before the source arguments are copied. This is used mostly
11445         * for MoveParams when it needs to read the source file to put it in the
11446         * destination.
11447         */
11448        int doPreCopy() {
11449            return PackageManager.INSTALL_SUCCEEDED;
11450        }
11451
11452        /**
11453         * Called after the source arguments are copied. This is used mostly for
11454         * MoveParams when it needs to read the source file to put it in the
11455         * destination.
11456         *
11457         * @return
11458         */
11459        int doPostCopy(int uid) {
11460            return PackageManager.INSTALL_SUCCEEDED;
11461        }
11462
11463        protected boolean isFwdLocked() {
11464            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11465        }
11466
11467        protected boolean isExternalAsec() {
11468            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11469        }
11470
11471        protected boolean isEphemeral() {
11472            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11473        }
11474
11475        UserHandle getUser() {
11476            return user;
11477        }
11478    }
11479
11480    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11481        if (!allCodePaths.isEmpty()) {
11482            if (instructionSets == null) {
11483                throw new IllegalStateException("instructionSet == null");
11484            }
11485            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11486            for (String codePath : allCodePaths) {
11487                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11488                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11489                    if (retCode < 0) {
11490                        Slog.w(TAG, "Couldn't remove dex file for package: "
11491                                + " at location " + codePath + ", retcode=" + retCode);
11492                        // we don't consider this to be a failure of the core package deletion
11493                    }
11494                }
11495            }
11496        }
11497    }
11498
11499    /**
11500     * Logic to handle installation of non-ASEC applications, including copying
11501     * and renaming logic.
11502     */
11503    class FileInstallArgs extends InstallArgs {
11504        private File codeFile;
11505        private File resourceFile;
11506
11507        // Example topology:
11508        // /data/app/com.example/base.apk
11509        // /data/app/com.example/split_foo.apk
11510        // /data/app/com.example/lib/arm/libfoo.so
11511        // /data/app/com.example/lib/arm64/libfoo.so
11512        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11513
11514        /** New install */
11515        FileInstallArgs(InstallParams params) {
11516            super(params.origin, params.move, params.observer, params.installFlags,
11517                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11518                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11519                    params.grantedRuntimePermissions,
11520                    params.traceMethod, params.traceCookie);
11521            if (isFwdLocked()) {
11522                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11523            }
11524        }
11525
11526        /** Existing install */
11527        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11528            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11529                    null, null, null, 0);
11530            this.codeFile = (codePath != null) ? new File(codePath) : null;
11531            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11532        }
11533
11534        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11535            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11536            try {
11537                return doCopyApk(imcs, temp);
11538            } finally {
11539                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11540            }
11541        }
11542
11543        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11544            if (origin.staged) {
11545                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11546                codeFile = origin.file;
11547                resourceFile = origin.file;
11548                return PackageManager.INSTALL_SUCCEEDED;
11549            }
11550
11551            try {
11552                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11553                final File tempDir =
11554                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11555                codeFile = tempDir;
11556                resourceFile = tempDir;
11557            } catch (IOException e) {
11558                Slog.w(TAG, "Failed to create copy file: " + e);
11559                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11560            }
11561
11562            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11563                @Override
11564                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11565                    if (!FileUtils.isValidExtFilename(name)) {
11566                        throw new IllegalArgumentException("Invalid filename: " + name);
11567                    }
11568                    try {
11569                        final File file = new File(codeFile, name);
11570                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11571                                O_RDWR | O_CREAT, 0644);
11572                        Os.chmod(file.getAbsolutePath(), 0644);
11573                        return new ParcelFileDescriptor(fd);
11574                    } catch (ErrnoException e) {
11575                        throw new RemoteException("Failed to open: " + e.getMessage());
11576                    }
11577                }
11578            };
11579
11580            int ret = PackageManager.INSTALL_SUCCEEDED;
11581            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11582            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11583                Slog.e(TAG, "Failed to copy package");
11584                return ret;
11585            }
11586
11587            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11588            NativeLibraryHelper.Handle handle = null;
11589            try {
11590                handle = NativeLibraryHelper.Handle.create(codeFile);
11591                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11592                        abiOverride);
11593            } catch (IOException e) {
11594                Slog.e(TAG, "Copying native libraries failed", e);
11595                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11596            } finally {
11597                IoUtils.closeQuietly(handle);
11598            }
11599
11600            return ret;
11601        }
11602
11603        int doPreInstall(int status) {
11604            if (status != PackageManager.INSTALL_SUCCEEDED) {
11605                cleanUp();
11606            }
11607            return status;
11608        }
11609
11610        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11611            if (status != PackageManager.INSTALL_SUCCEEDED) {
11612                cleanUp();
11613                return false;
11614            }
11615
11616            final File targetDir = codeFile.getParentFile();
11617            final File beforeCodeFile = codeFile;
11618            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11619
11620            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11621            try {
11622                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11623            } catch (ErrnoException e) {
11624                Slog.w(TAG, "Failed to rename", e);
11625                return false;
11626            }
11627
11628            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11629                Slog.w(TAG, "Failed to restorecon");
11630                return false;
11631            }
11632
11633            // Reflect the rename internally
11634            codeFile = afterCodeFile;
11635            resourceFile = afterCodeFile;
11636
11637            // Reflect the rename in scanned details
11638            pkg.codePath = afterCodeFile.getAbsolutePath();
11639            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11640                    pkg.baseCodePath);
11641            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11642                    pkg.splitCodePaths);
11643
11644            // Reflect the rename in app info
11645            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11646            pkg.applicationInfo.setCodePath(pkg.codePath);
11647            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11648            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11649            pkg.applicationInfo.setResourcePath(pkg.codePath);
11650            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11651            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11652
11653            return true;
11654        }
11655
11656        int doPostInstall(int status, int uid) {
11657            if (status != PackageManager.INSTALL_SUCCEEDED) {
11658                cleanUp();
11659            }
11660            return status;
11661        }
11662
11663        @Override
11664        String getCodePath() {
11665            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11666        }
11667
11668        @Override
11669        String getResourcePath() {
11670            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11671        }
11672
11673        private boolean cleanUp() {
11674            if (codeFile == null || !codeFile.exists()) {
11675                return false;
11676            }
11677
11678            if (codeFile.isDirectory()) {
11679                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11680            } else {
11681                codeFile.delete();
11682            }
11683
11684            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11685                resourceFile.delete();
11686            }
11687
11688            return true;
11689        }
11690
11691        void cleanUpResourcesLI() {
11692            // Try enumerating all code paths before deleting
11693            List<String> allCodePaths = Collections.EMPTY_LIST;
11694            if (codeFile != null && codeFile.exists()) {
11695                try {
11696                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11697                    allCodePaths = pkg.getAllCodePaths();
11698                } catch (PackageParserException e) {
11699                    // Ignored; we tried our best
11700                }
11701            }
11702
11703            cleanUp();
11704            removeDexFiles(allCodePaths, instructionSets);
11705        }
11706
11707        boolean doPostDeleteLI(boolean delete) {
11708            // XXX err, shouldn't we respect the delete flag?
11709            cleanUpResourcesLI();
11710            return true;
11711        }
11712    }
11713
11714    private boolean isAsecExternal(String cid) {
11715        final String asecPath = PackageHelper.getSdFilesystem(cid);
11716        return !asecPath.startsWith(mAsecInternalPath);
11717    }
11718
11719    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11720            PackageManagerException {
11721        if (copyRet < 0) {
11722            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11723                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11724                throw new PackageManagerException(copyRet, message);
11725            }
11726        }
11727    }
11728
11729    /**
11730     * Extract the MountService "container ID" from the full code path of an
11731     * .apk.
11732     */
11733    static String cidFromCodePath(String fullCodePath) {
11734        int eidx = fullCodePath.lastIndexOf("/");
11735        String subStr1 = fullCodePath.substring(0, eidx);
11736        int sidx = subStr1.lastIndexOf("/");
11737        return subStr1.substring(sidx+1, eidx);
11738    }
11739
11740    /**
11741     * Logic to handle installation of ASEC applications, including copying and
11742     * renaming logic.
11743     */
11744    class AsecInstallArgs extends InstallArgs {
11745        static final String RES_FILE_NAME = "pkg.apk";
11746        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11747
11748        String cid;
11749        String packagePath;
11750        String resourcePath;
11751
11752        /** New install */
11753        AsecInstallArgs(InstallParams params) {
11754            super(params.origin, params.move, params.observer, params.installFlags,
11755                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11756                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11757                    params.grantedRuntimePermissions,
11758                    params.traceMethod, params.traceCookie);
11759        }
11760
11761        /** Existing install */
11762        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11763                        boolean isExternal, boolean isForwardLocked) {
11764            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11765                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11766                    instructionSets, null, null, null, 0);
11767            // Hackily pretend we're still looking at a full code path
11768            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11769                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11770            }
11771
11772            // Extract cid from fullCodePath
11773            int eidx = fullCodePath.lastIndexOf("/");
11774            String subStr1 = fullCodePath.substring(0, eidx);
11775            int sidx = subStr1.lastIndexOf("/");
11776            cid = subStr1.substring(sidx+1, eidx);
11777            setMountPath(subStr1);
11778        }
11779
11780        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11781            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11782                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11783                    instructionSets, null, null, null, 0);
11784            this.cid = cid;
11785            setMountPath(PackageHelper.getSdDir(cid));
11786        }
11787
11788        void createCopyFile() {
11789            cid = mInstallerService.allocateExternalStageCidLegacy();
11790        }
11791
11792        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11793            if (origin.staged && origin.cid != null) {
11794                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11795                cid = origin.cid;
11796                setMountPath(PackageHelper.getSdDir(cid));
11797                return PackageManager.INSTALL_SUCCEEDED;
11798            }
11799
11800            if (temp) {
11801                createCopyFile();
11802            } else {
11803                /*
11804                 * Pre-emptively destroy the container since it's destroyed if
11805                 * copying fails due to it existing anyway.
11806                 */
11807                PackageHelper.destroySdDir(cid);
11808            }
11809
11810            final String newMountPath = imcs.copyPackageToContainer(
11811                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11812                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11813
11814            if (newMountPath != null) {
11815                setMountPath(newMountPath);
11816                return PackageManager.INSTALL_SUCCEEDED;
11817            } else {
11818                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11819            }
11820        }
11821
11822        @Override
11823        String getCodePath() {
11824            return packagePath;
11825        }
11826
11827        @Override
11828        String getResourcePath() {
11829            return resourcePath;
11830        }
11831
11832        int doPreInstall(int status) {
11833            if (status != PackageManager.INSTALL_SUCCEEDED) {
11834                // Destroy container
11835                PackageHelper.destroySdDir(cid);
11836            } else {
11837                boolean mounted = PackageHelper.isContainerMounted(cid);
11838                if (!mounted) {
11839                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11840                            Process.SYSTEM_UID);
11841                    if (newMountPath != null) {
11842                        setMountPath(newMountPath);
11843                    } else {
11844                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11845                    }
11846                }
11847            }
11848            return status;
11849        }
11850
11851        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11852            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11853            String newMountPath = null;
11854            if (PackageHelper.isContainerMounted(cid)) {
11855                // Unmount the container
11856                if (!PackageHelper.unMountSdDir(cid)) {
11857                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11858                    return false;
11859                }
11860            }
11861            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11862                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11863                        " which might be stale. Will try to clean up.");
11864                // Clean up the stale container and proceed to recreate.
11865                if (!PackageHelper.destroySdDir(newCacheId)) {
11866                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11867                    return false;
11868                }
11869                // Successfully cleaned up stale container. Try to rename again.
11870                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11871                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11872                            + " inspite of cleaning it up.");
11873                    return false;
11874                }
11875            }
11876            if (!PackageHelper.isContainerMounted(newCacheId)) {
11877                Slog.w(TAG, "Mounting container " + newCacheId);
11878                newMountPath = PackageHelper.mountSdDir(newCacheId,
11879                        getEncryptKey(), Process.SYSTEM_UID);
11880            } else {
11881                newMountPath = PackageHelper.getSdDir(newCacheId);
11882            }
11883            if (newMountPath == null) {
11884                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11885                return false;
11886            }
11887            Log.i(TAG, "Succesfully renamed " + cid +
11888                    " to " + newCacheId +
11889                    " at new path: " + newMountPath);
11890            cid = newCacheId;
11891
11892            final File beforeCodeFile = new File(packagePath);
11893            setMountPath(newMountPath);
11894            final File afterCodeFile = new File(packagePath);
11895
11896            // Reflect the rename in scanned details
11897            pkg.codePath = afterCodeFile.getAbsolutePath();
11898            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11899                    pkg.baseCodePath);
11900            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11901                    pkg.splitCodePaths);
11902
11903            // Reflect the rename in app info
11904            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11905            pkg.applicationInfo.setCodePath(pkg.codePath);
11906            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11907            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11908            pkg.applicationInfo.setResourcePath(pkg.codePath);
11909            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11910            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11911
11912            return true;
11913        }
11914
11915        private void setMountPath(String mountPath) {
11916            final File mountFile = new File(mountPath);
11917
11918            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11919            if (monolithicFile.exists()) {
11920                packagePath = monolithicFile.getAbsolutePath();
11921                if (isFwdLocked()) {
11922                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11923                } else {
11924                    resourcePath = packagePath;
11925                }
11926            } else {
11927                packagePath = mountFile.getAbsolutePath();
11928                resourcePath = packagePath;
11929            }
11930        }
11931
11932        int doPostInstall(int status, int uid) {
11933            if (status != PackageManager.INSTALL_SUCCEEDED) {
11934                cleanUp();
11935            } else {
11936                final int groupOwner;
11937                final String protectedFile;
11938                if (isFwdLocked()) {
11939                    groupOwner = UserHandle.getSharedAppGid(uid);
11940                    protectedFile = RES_FILE_NAME;
11941                } else {
11942                    groupOwner = -1;
11943                    protectedFile = null;
11944                }
11945
11946                if (uid < Process.FIRST_APPLICATION_UID
11947                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11948                    Slog.e(TAG, "Failed to finalize " + cid);
11949                    PackageHelper.destroySdDir(cid);
11950                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11951                }
11952
11953                boolean mounted = PackageHelper.isContainerMounted(cid);
11954                if (!mounted) {
11955                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11956                }
11957            }
11958            return status;
11959        }
11960
11961        private void cleanUp() {
11962            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11963
11964            // Destroy secure container
11965            PackageHelper.destroySdDir(cid);
11966        }
11967
11968        private List<String> getAllCodePaths() {
11969            final File codeFile = new File(getCodePath());
11970            if (codeFile != null && codeFile.exists()) {
11971                try {
11972                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11973                    return pkg.getAllCodePaths();
11974                } catch (PackageParserException e) {
11975                    // Ignored; we tried our best
11976                }
11977            }
11978            return Collections.EMPTY_LIST;
11979        }
11980
11981        void cleanUpResourcesLI() {
11982            // Enumerate all code paths before deleting
11983            cleanUpResourcesLI(getAllCodePaths());
11984        }
11985
11986        private void cleanUpResourcesLI(List<String> allCodePaths) {
11987            cleanUp();
11988            removeDexFiles(allCodePaths, instructionSets);
11989        }
11990
11991        String getPackageName() {
11992            return getAsecPackageName(cid);
11993        }
11994
11995        boolean doPostDeleteLI(boolean delete) {
11996            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11997            final List<String> allCodePaths = getAllCodePaths();
11998            boolean mounted = PackageHelper.isContainerMounted(cid);
11999            if (mounted) {
12000                // Unmount first
12001                if (PackageHelper.unMountSdDir(cid)) {
12002                    mounted = false;
12003                }
12004            }
12005            if (!mounted && delete) {
12006                cleanUpResourcesLI(allCodePaths);
12007            }
12008            return !mounted;
12009        }
12010
12011        @Override
12012        int doPreCopy() {
12013            if (isFwdLocked()) {
12014                if (!PackageHelper.fixSdPermissions(cid,
12015                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12016                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12017                }
12018            }
12019
12020            return PackageManager.INSTALL_SUCCEEDED;
12021        }
12022
12023        @Override
12024        int doPostCopy(int uid) {
12025            if (isFwdLocked()) {
12026                if (uid < Process.FIRST_APPLICATION_UID
12027                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12028                                RES_FILE_NAME)) {
12029                    Slog.e(TAG, "Failed to finalize " + cid);
12030                    PackageHelper.destroySdDir(cid);
12031                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12032                }
12033            }
12034
12035            return PackageManager.INSTALL_SUCCEEDED;
12036        }
12037    }
12038
12039    /**
12040     * Logic to handle movement of existing installed applications.
12041     */
12042    class MoveInstallArgs extends InstallArgs {
12043        private File codeFile;
12044        private File resourceFile;
12045
12046        /** New install */
12047        MoveInstallArgs(InstallParams params) {
12048            super(params.origin, params.move, params.observer, params.installFlags,
12049                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
12050                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12051                    params.grantedRuntimePermissions,
12052                    params.traceMethod, params.traceCookie);
12053        }
12054
12055        int copyApk(IMediaContainerService imcs, boolean temp) {
12056            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12057                    + move.fromUuid + " to " + move.toUuid);
12058            synchronized (mInstaller) {
12059                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12060                        move.dataAppName, move.appId, move.seinfo) != 0) {
12061                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12062                }
12063            }
12064
12065            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12066            resourceFile = codeFile;
12067            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12068
12069            return PackageManager.INSTALL_SUCCEEDED;
12070        }
12071
12072        int doPreInstall(int status) {
12073            if (status != PackageManager.INSTALL_SUCCEEDED) {
12074                cleanUp(move.toUuid);
12075            }
12076            return status;
12077        }
12078
12079        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12080            if (status != PackageManager.INSTALL_SUCCEEDED) {
12081                cleanUp(move.toUuid);
12082                return false;
12083            }
12084
12085            // Reflect the move in app info
12086            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12087            pkg.applicationInfo.setCodePath(pkg.codePath);
12088            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12089            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12090            pkg.applicationInfo.setResourcePath(pkg.codePath);
12091            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12092            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12093
12094            return true;
12095        }
12096
12097        int doPostInstall(int status, int uid) {
12098            if (status == PackageManager.INSTALL_SUCCEEDED) {
12099                cleanUp(move.fromUuid);
12100            } else {
12101                cleanUp(move.toUuid);
12102            }
12103            return status;
12104        }
12105
12106        @Override
12107        String getCodePath() {
12108            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12109        }
12110
12111        @Override
12112        String getResourcePath() {
12113            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12114        }
12115
12116        private boolean cleanUp(String volumeUuid) {
12117            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12118                    move.dataAppName);
12119            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12120            synchronized (mInstallLock) {
12121                // Clean up both app data and code
12122                removeDataDirsLI(volumeUuid, move.packageName);
12123                if (codeFile.isDirectory()) {
12124                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12125                } else {
12126                    codeFile.delete();
12127                }
12128            }
12129            return true;
12130        }
12131
12132        void cleanUpResourcesLI() {
12133            throw new UnsupportedOperationException();
12134        }
12135
12136        boolean doPostDeleteLI(boolean delete) {
12137            throw new UnsupportedOperationException();
12138        }
12139    }
12140
12141    static String getAsecPackageName(String packageCid) {
12142        int idx = packageCid.lastIndexOf("-");
12143        if (idx == -1) {
12144            return packageCid;
12145        }
12146        return packageCid.substring(0, idx);
12147    }
12148
12149    // Utility method used to create code paths based on package name and available index.
12150    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12151        String idxStr = "";
12152        int idx = 1;
12153        // Fall back to default value of idx=1 if prefix is not
12154        // part of oldCodePath
12155        if (oldCodePath != null) {
12156            String subStr = oldCodePath;
12157            // Drop the suffix right away
12158            if (suffix != null && subStr.endsWith(suffix)) {
12159                subStr = subStr.substring(0, subStr.length() - suffix.length());
12160            }
12161            // If oldCodePath already contains prefix find out the
12162            // ending index to either increment or decrement.
12163            int sidx = subStr.lastIndexOf(prefix);
12164            if (sidx != -1) {
12165                subStr = subStr.substring(sidx + prefix.length());
12166                if (subStr != null) {
12167                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12168                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12169                    }
12170                    try {
12171                        idx = Integer.parseInt(subStr);
12172                        if (idx <= 1) {
12173                            idx++;
12174                        } else {
12175                            idx--;
12176                        }
12177                    } catch(NumberFormatException e) {
12178                    }
12179                }
12180            }
12181        }
12182        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12183        return prefix + idxStr;
12184    }
12185
12186    private File getNextCodePath(File targetDir, String packageName) {
12187        int suffix = 1;
12188        File result;
12189        do {
12190            result = new File(targetDir, packageName + "-" + suffix);
12191            suffix++;
12192        } while (result.exists());
12193        return result;
12194    }
12195
12196    // Utility method that returns the relative package path with respect
12197    // to the installation directory. Like say for /data/data/com.test-1.apk
12198    // string com.test-1 is returned.
12199    static String deriveCodePathName(String codePath) {
12200        if (codePath == null) {
12201            return null;
12202        }
12203        final File codeFile = new File(codePath);
12204        final String name = codeFile.getName();
12205        if (codeFile.isDirectory()) {
12206            return name;
12207        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12208            final int lastDot = name.lastIndexOf('.');
12209            return name.substring(0, lastDot);
12210        } else {
12211            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12212            return null;
12213        }
12214    }
12215
12216    class PackageInstalledInfo {
12217        String name;
12218        int uid;
12219        // The set of users that originally had this package installed.
12220        int[] origUsers;
12221        // The set of users that now have this package installed.
12222        int[] newUsers;
12223        PackageParser.Package pkg;
12224        int returnCode;
12225        String returnMsg;
12226        PackageRemovedInfo removedInfo;
12227
12228        public void setError(int code, String msg) {
12229            returnCode = code;
12230            returnMsg = msg;
12231            Slog.w(TAG, msg);
12232        }
12233
12234        public void setError(String msg, PackageParserException e) {
12235            returnCode = e.error;
12236            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12237            Slog.w(TAG, msg, e);
12238        }
12239
12240        public void setError(String msg, PackageManagerException e) {
12241            returnCode = e.error;
12242            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12243            Slog.w(TAG, msg, e);
12244        }
12245
12246        // In some error cases we want to convey more info back to the observer
12247        String origPackage;
12248        String origPermission;
12249    }
12250
12251    /*
12252     * Install a non-existing package.
12253     */
12254    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12255            UserHandle user, String installerPackageName, String volumeUuid,
12256            PackageInstalledInfo res) {
12257        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12258
12259        // Remember this for later, in case we need to rollback this install
12260        String pkgName = pkg.packageName;
12261
12262        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12263        // TODO: b/23350563
12264        final boolean dataDirExists = Environment
12265                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12266
12267        synchronized(mPackages) {
12268            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12269                // A package with the same name is already installed, though
12270                // it has been renamed to an older name.  The package we
12271                // are trying to install should be installed as an update to
12272                // the existing one, but that has not been requested, so bail.
12273                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12274                        + " without first uninstalling package running as "
12275                        + mSettings.mRenamedPackages.get(pkgName));
12276                return;
12277            }
12278            if (mPackages.containsKey(pkgName)) {
12279                // Don't allow installation over an existing package with the same name.
12280                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12281                        + " without first uninstalling.");
12282                return;
12283            }
12284        }
12285
12286        try {
12287            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12288                    System.currentTimeMillis(), user);
12289
12290            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12291            // delete the partially installed application. the data directory will have to be
12292            // restored if it was already existing
12293            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12294                // remove package from internal structures.  Note that we want deletePackageX to
12295                // delete the package data and cache directories that it created in
12296                // scanPackageLocked, unless those directories existed before we even tried to
12297                // install.
12298                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12299                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12300                                res.removedInfo, true);
12301            }
12302
12303        } catch (PackageManagerException e) {
12304            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12305        }
12306
12307        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12308    }
12309
12310    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12311        // Can't rotate keys during boot or if sharedUser.
12312        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12313                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12314            return false;
12315        }
12316        // app is using upgradeKeySets; make sure all are valid
12317        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12318        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12319        for (int i = 0; i < upgradeKeySets.length; i++) {
12320            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12321                Slog.wtf(TAG, "Package "
12322                         + (oldPs.name != null ? oldPs.name : "<null>")
12323                         + " contains upgrade-key-set reference to unknown key-set: "
12324                         + upgradeKeySets[i]
12325                         + " reverting to signatures check.");
12326                return false;
12327            }
12328        }
12329        return true;
12330    }
12331
12332    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12333        // Upgrade keysets are being used.  Determine if new package has a superset of the
12334        // required keys.
12335        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12336        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12337        for (int i = 0; i < upgradeKeySets.length; i++) {
12338            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12339            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12340                return true;
12341            }
12342        }
12343        return false;
12344    }
12345
12346    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12347            UserHandle user, String installerPackageName, String volumeUuid,
12348            PackageInstalledInfo res) {
12349        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12350
12351        final PackageParser.Package oldPackage;
12352        final String pkgName = pkg.packageName;
12353        final int[] allUsers;
12354        final boolean[] perUserInstalled;
12355
12356        // First find the old package info and check signatures
12357        synchronized(mPackages) {
12358            oldPackage = mPackages.get(pkgName);
12359            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12360            if (isEphemeral && !oldIsEphemeral) {
12361                // can't downgrade from full to ephemeral
12362                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12363                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12364                return;
12365            }
12366            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12367            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12368            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12369                if(!checkUpgradeKeySetLP(ps, pkg)) {
12370                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12371                            "New package not signed by keys specified by upgrade-keysets: "
12372                            + pkgName);
12373                    return;
12374                }
12375            } else {
12376                // default to original signature matching
12377                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12378                    != PackageManager.SIGNATURE_MATCH) {
12379                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12380                            "New package has a different signature: " + pkgName);
12381                    return;
12382                }
12383            }
12384
12385            // In case of rollback, remember per-user/profile install state
12386            allUsers = sUserManager.getUserIds();
12387            perUserInstalled = new boolean[allUsers.length];
12388            for (int i = 0; i < allUsers.length; i++) {
12389                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12390            }
12391        }
12392
12393        boolean sysPkg = (isSystemApp(oldPackage));
12394        if (sysPkg) {
12395            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12396                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12397        } else {
12398            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12399                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12400        }
12401    }
12402
12403    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12404            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12405            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12406            String volumeUuid, PackageInstalledInfo res) {
12407        String pkgName = deletedPackage.packageName;
12408        boolean deletedPkg = true;
12409        boolean updatedSettings = false;
12410
12411        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12412                + deletedPackage);
12413        long origUpdateTime;
12414        if (pkg.mExtras != null) {
12415            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12416        } else {
12417            origUpdateTime = 0;
12418        }
12419
12420        // First delete the existing package while retaining the data directory
12421        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12422                res.removedInfo, true)) {
12423            // If the existing package wasn't successfully deleted
12424            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12425            deletedPkg = false;
12426        } else {
12427            // Successfully deleted the old package; proceed with replace.
12428
12429            // If deleted package lived in a container, give users a chance to
12430            // relinquish resources before killing.
12431            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12432                if (DEBUG_INSTALL) {
12433                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12434                }
12435                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12436                final ArrayList<String> pkgList = new ArrayList<String>(1);
12437                pkgList.add(deletedPackage.applicationInfo.packageName);
12438                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12439            }
12440
12441            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12442            try {
12443                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12444                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12445                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12446                        perUserInstalled, res, user);
12447                updatedSettings = true;
12448            } catch (PackageManagerException e) {
12449                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12450            }
12451        }
12452
12453        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12454            // remove package from internal structures.  Note that we want deletePackageX to
12455            // delete the package data and cache directories that it created in
12456            // scanPackageLocked, unless those directories existed before we even tried to
12457            // install.
12458            if(updatedSettings) {
12459                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12460                deletePackageLI(
12461                        pkgName, null, true, allUsers, perUserInstalled,
12462                        PackageManager.DELETE_KEEP_DATA,
12463                                res.removedInfo, true);
12464            }
12465            // Since we failed to install the new package we need to restore the old
12466            // package that we deleted.
12467            if (deletedPkg) {
12468                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12469                File restoreFile = new File(deletedPackage.codePath);
12470                // Parse old package
12471                boolean oldExternal = isExternal(deletedPackage);
12472                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12473                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12474                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12475                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12476                try {
12477                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12478                            null);
12479                } catch (PackageManagerException e) {
12480                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12481                            + e.getMessage());
12482                    return;
12483                }
12484                // Restore of old package succeeded. Update permissions.
12485                // writer
12486                synchronized (mPackages) {
12487                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12488                            UPDATE_PERMISSIONS_ALL);
12489                    // can downgrade to reader
12490                    mSettings.writeLPr();
12491                }
12492                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12493            }
12494        }
12495    }
12496
12497    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12498            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12499            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12500            String volumeUuid, PackageInstalledInfo res) {
12501        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12502                + ", old=" + deletedPackage);
12503        boolean disabledSystem = false;
12504        boolean updatedSettings = false;
12505        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12506        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12507                != 0) {
12508            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12509        }
12510        String packageName = deletedPackage.packageName;
12511        if (packageName == null) {
12512            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12513                    "Attempt to delete null packageName.");
12514            return;
12515        }
12516        PackageParser.Package oldPkg;
12517        PackageSetting oldPkgSetting;
12518        // reader
12519        synchronized (mPackages) {
12520            oldPkg = mPackages.get(packageName);
12521            oldPkgSetting = mSettings.mPackages.get(packageName);
12522            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12523                    (oldPkgSetting == null)) {
12524                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12525                        "Couldn't find package:" + packageName + " information");
12526                return;
12527            }
12528        }
12529
12530        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12531
12532        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12533        res.removedInfo.removedPackage = packageName;
12534        // Remove existing system package
12535        removePackageLI(oldPkgSetting, true);
12536        // writer
12537        synchronized (mPackages) {
12538            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12539            if (!disabledSystem && deletedPackage != null) {
12540                // We didn't need to disable the .apk as a current system package,
12541                // which means we are replacing another update that is already
12542                // installed.  We need to make sure to delete the older one's .apk.
12543                res.removedInfo.args = createInstallArgsForExisting(0,
12544                        deletedPackage.applicationInfo.getCodePath(),
12545                        deletedPackage.applicationInfo.getResourcePath(),
12546                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12547            } else {
12548                res.removedInfo.args = null;
12549            }
12550        }
12551
12552        // Successfully disabled the old package. Now proceed with re-installation
12553        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12554
12555        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12556        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12557
12558        PackageParser.Package newPackage = null;
12559        try {
12560            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12561            if (newPackage.mExtras != null) {
12562                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12563                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12564                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12565
12566                // is the update attempting to change shared user? that isn't going to work...
12567                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12568                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12569                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12570                            + " to " + newPkgSetting.sharedUser);
12571                    updatedSettings = true;
12572                }
12573            }
12574
12575            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12576                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12577                        perUserInstalled, res, user);
12578                updatedSettings = true;
12579            }
12580
12581        } catch (PackageManagerException e) {
12582            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12583        }
12584
12585        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12586            // Re installation failed. Restore old information
12587            // Remove new pkg information
12588            if (newPackage != null) {
12589                removeInstalledPackageLI(newPackage, true);
12590            }
12591            // Add back the old system package
12592            try {
12593                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12594            } catch (PackageManagerException e) {
12595                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12596            }
12597            // Restore the old system information in Settings
12598            synchronized (mPackages) {
12599                if (disabledSystem) {
12600                    mSettings.enableSystemPackageLPw(packageName);
12601                }
12602                if (updatedSettings) {
12603                    mSettings.setInstallerPackageName(packageName,
12604                            oldPkgSetting.installerPackageName);
12605                }
12606                mSettings.writeLPr();
12607            }
12608        }
12609    }
12610
12611    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12612        // Collect all used permissions in the UID
12613        ArraySet<String> usedPermissions = new ArraySet<>();
12614        final int packageCount = su.packages.size();
12615        for (int i = 0; i < packageCount; i++) {
12616            PackageSetting ps = su.packages.valueAt(i);
12617            if (ps.pkg == null) {
12618                continue;
12619            }
12620            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12621            for (int j = 0; j < requestedPermCount; j++) {
12622                String permission = ps.pkg.requestedPermissions.get(j);
12623                BasePermission bp = mSettings.mPermissions.get(permission);
12624                if (bp != null) {
12625                    usedPermissions.add(permission);
12626                }
12627            }
12628        }
12629
12630        PermissionsState permissionsState = su.getPermissionsState();
12631        // Prune install permissions
12632        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12633        final int installPermCount = installPermStates.size();
12634        for (int i = installPermCount - 1; i >= 0;  i--) {
12635            PermissionState permissionState = installPermStates.get(i);
12636            if (!usedPermissions.contains(permissionState.getName())) {
12637                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12638                if (bp != null) {
12639                    permissionsState.revokeInstallPermission(bp);
12640                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12641                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12642                }
12643            }
12644        }
12645
12646        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12647
12648        // Prune runtime permissions
12649        for (int userId : allUserIds) {
12650            List<PermissionState> runtimePermStates = permissionsState
12651                    .getRuntimePermissionStates(userId);
12652            final int runtimePermCount = runtimePermStates.size();
12653            for (int i = runtimePermCount - 1; i >= 0; i--) {
12654                PermissionState permissionState = runtimePermStates.get(i);
12655                if (!usedPermissions.contains(permissionState.getName())) {
12656                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12657                    if (bp != null) {
12658                        permissionsState.revokeRuntimePermission(bp, userId);
12659                        permissionsState.updatePermissionFlags(bp, userId,
12660                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12661                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12662                                runtimePermissionChangedUserIds, userId);
12663                    }
12664                }
12665            }
12666        }
12667
12668        return runtimePermissionChangedUserIds;
12669    }
12670
12671    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12672            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12673            UserHandle user) {
12674        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12675
12676        String pkgName = newPackage.packageName;
12677        synchronized (mPackages) {
12678            //write settings. the installStatus will be incomplete at this stage.
12679            //note that the new package setting would have already been
12680            //added to mPackages. It hasn't been persisted yet.
12681            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12682            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12683            mSettings.writeLPr();
12684            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12685        }
12686
12687        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12688        synchronized (mPackages) {
12689            updatePermissionsLPw(newPackage.packageName, newPackage,
12690                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12691                            ? UPDATE_PERMISSIONS_ALL : 0));
12692            // For system-bundled packages, we assume that installing an upgraded version
12693            // of the package implies that the user actually wants to run that new code,
12694            // so we enable the package.
12695            PackageSetting ps = mSettings.mPackages.get(pkgName);
12696            if (ps != null) {
12697                if (isSystemApp(newPackage)) {
12698                    // NB: implicit assumption that system package upgrades apply to all users
12699                    if (DEBUG_INSTALL) {
12700                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12701                    }
12702                    if (res.origUsers != null) {
12703                        for (int userHandle : res.origUsers) {
12704                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12705                                    userHandle, installerPackageName);
12706                        }
12707                    }
12708                    // Also convey the prior install/uninstall state
12709                    if (allUsers != null && perUserInstalled != null) {
12710                        for (int i = 0; i < allUsers.length; i++) {
12711                            if (DEBUG_INSTALL) {
12712                                Slog.d(TAG, "    user " + allUsers[i]
12713                                        + " => " + perUserInstalled[i]);
12714                            }
12715                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12716                        }
12717                        // these install state changes will be persisted in the
12718                        // upcoming call to mSettings.writeLPr().
12719                    }
12720                }
12721                // It's implied that when a user requests installation, they want the app to be
12722                // installed and enabled.
12723                int userId = user.getIdentifier();
12724                if (userId != UserHandle.USER_ALL) {
12725                    ps.setInstalled(true, userId);
12726                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12727                }
12728            }
12729            res.name = pkgName;
12730            res.uid = newPackage.applicationInfo.uid;
12731            res.pkg = newPackage;
12732            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12733            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12734            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12735            //to update install status
12736            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12737            mSettings.writeLPr();
12738            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12739        }
12740
12741        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12742    }
12743
12744    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12745        try {
12746            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12747            installPackageLI(args, res);
12748        } finally {
12749            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12750        }
12751    }
12752
12753    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12754        final int installFlags = args.installFlags;
12755        final String installerPackageName = args.installerPackageName;
12756        final String volumeUuid = args.volumeUuid;
12757        final File tmpPackageFile = new File(args.getCodePath());
12758        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12759        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12760                || (args.volumeUuid != null));
12761        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12762        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12763        boolean replace = false;
12764        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12765        if (args.move != null) {
12766            // moving a complete application; perfom an initial scan on the new install location
12767            scanFlags |= SCAN_INITIAL;
12768        }
12769        // Result object to be returned
12770        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12771
12772        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12773
12774        // Sanity check
12775        if (ephemeral && (forwardLocked || onExternal)) {
12776            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12777                    + " external=" + onExternal);
12778            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12779            return;
12780        }
12781
12782        // Retrieve PackageSettings and parse package
12783        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12784                | PackageParser.PARSE_ENFORCE_CODE
12785                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12786                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12787                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0)
12788                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12789        PackageParser pp = new PackageParser();
12790        pp.setSeparateProcesses(mSeparateProcesses);
12791        pp.setDisplayMetrics(mMetrics);
12792
12793        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12794        final PackageParser.Package pkg;
12795        try {
12796            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12797        } catch (PackageParserException e) {
12798            res.setError("Failed parse during installPackageLI", e);
12799            return;
12800        } finally {
12801            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12802        }
12803
12804        // Mark that we have an install time CPU ABI override.
12805        pkg.cpuAbiOverride = args.abiOverride;
12806
12807        String pkgName = res.name = pkg.packageName;
12808        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12809            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12810                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12811                return;
12812            }
12813        }
12814
12815        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12816        try {
12817            pp.collectCertificates(pkg, parseFlags);
12818        } catch (PackageParserException e) {
12819            res.setError("Failed collect during installPackageLI", e);
12820            return;
12821        } finally {
12822            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12823        }
12824
12825        /* If the installer passed in a manifest digest, compare it now. */
12826        if (args.manifestDigest != null) {
12827            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12828            try {
12829                pp.collectManifestDigest(pkg);
12830            } catch (PackageParserException e) {
12831                res.setError("Failed collect during installPackageLI", e);
12832                return;
12833            } finally {
12834                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12835            }
12836
12837            if (DEBUG_INSTALL) {
12838                final String parsedManifest = pkg.manifestDigest == null ? "null"
12839                        : pkg.manifestDigest.toString();
12840                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12841                        + parsedManifest);
12842            }
12843
12844            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12845                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12846                return;
12847            }
12848        } else if (DEBUG_INSTALL) {
12849            final String parsedManifest = pkg.manifestDigest == null
12850                    ? "null" : pkg.manifestDigest.toString();
12851            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12852        }
12853
12854        // Get rid of all references to package scan path via parser.
12855        pp = null;
12856        String oldCodePath = null;
12857        boolean systemApp = false;
12858        synchronized (mPackages) {
12859            // Check if installing already existing package
12860            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12861                String oldName = mSettings.mRenamedPackages.get(pkgName);
12862                if (pkg.mOriginalPackages != null
12863                        && pkg.mOriginalPackages.contains(oldName)
12864                        && mPackages.containsKey(oldName)) {
12865                    // This package is derived from an original package,
12866                    // and this device has been updating from that original
12867                    // name.  We must continue using the original name, so
12868                    // rename the new package here.
12869                    pkg.setPackageName(oldName);
12870                    pkgName = pkg.packageName;
12871                    replace = true;
12872                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12873                            + oldName + " pkgName=" + pkgName);
12874                } else if (mPackages.containsKey(pkgName)) {
12875                    // This package, under its official name, already exists
12876                    // on the device; we should replace it.
12877                    replace = true;
12878                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12879                }
12880
12881                // Prevent apps opting out from runtime permissions
12882                if (replace) {
12883                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12884                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12885                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12886                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12887                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12888                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12889                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12890                                        + " doesn't support runtime permissions but the old"
12891                                        + " target SDK " + oldTargetSdk + " does.");
12892                        return;
12893                    }
12894                }
12895            }
12896
12897            PackageSetting ps = mSettings.mPackages.get(pkgName);
12898            if (ps != null) {
12899                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12900
12901                // Quick sanity check that we're signed correctly if updating;
12902                // we'll check this again later when scanning, but we want to
12903                // bail early here before tripping over redefined permissions.
12904                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12905                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12906                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12907                                + pkg.packageName + " upgrade keys do not match the "
12908                                + "previously installed version");
12909                        return;
12910                    }
12911                } else {
12912                    try {
12913                        verifySignaturesLP(ps, pkg);
12914                    } catch (PackageManagerException e) {
12915                        res.setError(e.error, e.getMessage());
12916                        return;
12917                    }
12918                }
12919
12920                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12921                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12922                    systemApp = (ps.pkg.applicationInfo.flags &
12923                            ApplicationInfo.FLAG_SYSTEM) != 0;
12924                }
12925                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12926            }
12927
12928            // Check whether the newly-scanned package wants to define an already-defined perm
12929            int N = pkg.permissions.size();
12930            for (int i = N-1; i >= 0; i--) {
12931                PackageParser.Permission perm = pkg.permissions.get(i);
12932                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12933                if (bp != null) {
12934                    // If the defining package is signed with our cert, it's okay.  This
12935                    // also includes the "updating the same package" case, of course.
12936                    // "updating same package" could also involve key-rotation.
12937                    final boolean sigsOk;
12938                    if (bp.sourcePackage.equals(pkg.packageName)
12939                            && (bp.packageSetting instanceof PackageSetting)
12940                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12941                                    scanFlags))) {
12942                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12943                    } else {
12944                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12945                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12946                    }
12947                    if (!sigsOk) {
12948                        // If the owning package is the system itself, we log but allow
12949                        // install to proceed; we fail the install on all other permission
12950                        // redefinitions.
12951                        if (!bp.sourcePackage.equals("android")) {
12952                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12953                                    + pkg.packageName + " attempting to redeclare permission "
12954                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12955                            res.origPermission = perm.info.name;
12956                            res.origPackage = bp.sourcePackage;
12957                            return;
12958                        } else {
12959                            Slog.w(TAG, "Package " + pkg.packageName
12960                                    + " attempting to redeclare system permission "
12961                                    + perm.info.name + "; ignoring new declaration");
12962                            pkg.permissions.remove(i);
12963                        }
12964                    }
12965                }
12966            }
12967
12968        }
12969
12970        if (systemApp) {
12971            if (onExternal) {
12972                // Abort update; system app can't be replaced with app on sdcard
12973                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12974                        "Cannot install updates to system apps on sdcard");
12975                return;
12976            } else if (ephemeral) {
12977                // Abort update; system app can't be replaced with an ephemeral app
12978                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12979                        "Cannot update a system app with an ephemeral app");
12980                return;
12981            }
12982        }
12983
12984        if (args.move != null) {
12985            // We did an in-place move, so dex is ready to roll
12986            scanFlags |= SCAN_NO_DEX;
12987            scanFlags |= SCAN_MOVE;
12988
12989            synchronized (mPackages) {
12990                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12991                if (ps == null) {
12992                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12993                            "Missing settings for moved package " + pkgName);
12994                }
12995
12996                // We moved the entire application as-is, so bring over the
12997                // previously derived ABI information.
12998                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12999                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13000            }
13001
13002        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13003            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13004            scanFlags |= SCAN_NO_DEX;
13005
13006            try {
13007                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13008                        true /* extract libs */);
13009            } catch (PackageManagerException pme) {
13010                Slog.e(TAG, "Error deriving application ABI", pme);
13011                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13012                return;
13013            }
13014        }
13015
13016        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13017            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13018            return;
13019        }
13020
13021        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13022
13023        if (replace) {
13024            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13025                    installerPackageName, volumeUuid, res);
13026        } else {
13027            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13028                    args.user, installerPackageName, volumeUuid, res);
13029        }
13030        synchronized (mPackages) {
13031            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13032            if (ps != null) {
13033                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13034            }
13035        }
13036    }
13037
13038    private void startIntentFilterVerifications(int userId, boolean replacing,
13039            PackageParser.Package pkg) {
13040        if (mIntentFilterVerifierComponent == null) {
13041            Slog.w(TAG, "No IntentFilter verification will not be done as "
13042                    + "there is no IntentFilterVerifier available!");
13043            return;
13044        }
13045
13046        final int verifierUid = getPackageUid(
13047                mIntentFilterVerifierComponent.getPackageName(),
13048                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13049
13050        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13051        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13052        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13053        mHandler.sendMessage(msg);
13054    }
13055
13056    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13057            PackageParser.Package pkg) {
13058        int size = pkg.activities.size();
13059        if (size == 0) {
13060            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13061                    "No activity, so no need to verify any IntentFilter!");
13062            return;
13063        }
13064
13065        final boolean hasDomainURLs = hasDomainURLs(pkg);
13066        if (!hasDomainURLs) {
13067            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13068                    "No domain URLs, so no need to verify any IntentFilter!");
13069            return;
13070        }
13071
13072        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13073                + " if any IntentFilter from the " + size
13074                + " Activities needs verification ...");
13075
13076        int count = 0;
13077        final String packageName = pkg.packageName;
13078
13079        synchronized (mPackages) {
13080            // If this is a new install and we see that we've already run verification for this
13081            // package, we have nothing to do: it means the state was restored from backup.
13082            if (!replacing) {
13083                IntentFilterVerificationInfo ivi =
13084                        mSettings.getIntentFilterVerificationLPr(packageName);
13085                if (ivi != null) {
13086                    if (DEBUG_DOMAIN_VERIFICATION) {
13087                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13088                                + ivi.getStatusString());
13089                    }
13090                    return;
13091                }
13092            }
13093
13094            // If any filters need to be verified, then all need to be.
13095            boolean needToVerify = false;
13096            for (PackageParser.Activity a : pkg.activities) {
13097                for (ActivityIntentInfo filter : a.intents) {
13098                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13099                        if (DEBUG_DOMAIN_VERIFICATION) {
13100                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13101                        }
13102                        needToVerify = true;
13103                        break;
13104                    }
13105                }
13106            }
13107
13108            if (needToVerify) {
13109                final int verificationId = mIntentFilterVerificationToken++;
13110                for (PackageParser.Activity a : pkg.activities) {
13111                    for (ActivityIntentInfo filter : a.intents) {
13112                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13113                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13114                                    "Verification needed for IntentFilter:" + filter.toString());
13115                            mIntentFilterVerifier.addOneIntentFilterVerification(
13116                                    verifierUid, userId, verificationId, filter, packageName);
13117                            count++;
13118                        }
13119                    }
13120                }
13121            }
13122        }
13123
13124        if (count > 0) {
13125            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13126                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13127                    +  " for userId:" + userId);
13128            mIntentFilterVerifier.startVerifications(userId);
13129        } else {
13130            if (DEBUG_DOMAIN_VERIFICATION) {
13131                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13132            }
13133        }
13134    }
13135
13136    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13137        final ComponentName cn  = filter.activity.getComponentName();
13138        final String packageName = cn.getPackageName();
13139
13140        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13141                packageName);
13142        if (ivi == null) {
13143            return true;
13144        }
13145        int status = ivi.getStatus();
13146        switch (status) {
13147            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13148            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13149                return true;
13150
13151            default:
13152                // Nothing to do
13153                return false;
13154        }
13155    }
13156
13157    private static boolean isMultiArch(PackageSetting ps) {
13158        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13159    }
13160
13161    private static boolean isMultiArch(ApplicationInfo info) {
13162        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13163    }
13164
13165    private static boolean isExternal(PackageParser.Package pkg) {
13166        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13167    }
13168
13169    private static boolean isExternal(PackageSetting ps) {
13170        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13171    }
13172
13173    private static boolean isExternal(ApplicationInfo info) {
13174        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13175    }
13176
13177    private static boolean isEphemeral(PackageParser.Package pkg) {
13178        return pkg.applicationInfo.isEphemeralApp();
13179    }
13180
13181    private static boolean isEphemeral(PackageSetting ps) {
13182        return ps.pkg != null && isEphemeral(ps.pkg);
13183    }
13184
13185    private static boolean isSystemApp(PackageParser.Package pkg) {
13186        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13187    }
13188
13189    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13190        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13191    }
13192
13193    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13194        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13195    }
13196
13197    private static boolean isSystemApp(PackageSetting ps) {
13198        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13199    }
13200
13201    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13202        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13203    }
13204
13205    private int packageFlagsToInstallFlags(PackageSetting ps) {
13206        int installFlags = 0;
13207        if (isEphemeral(ps)) {
13208            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13209        }
13210        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13211            // This existing package was an external ASEC install when we have
13212            // the external flag without a UUID
13213            installFlags |= PackageManager.INSTALL_EXTERNAL;
13214        }
13215        if (ps.isForwardLocked()) {
13216            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13217        }
13218        return installFlags;
13219    }
13220
13221    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13222        if (isExternal(pkg)) {
13223            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13224                return StorageManager.UUID_PRIMARY_PHYSICAL;
13225            } else {
13226                return pkg.volumeUuid;
13227            }
13228        } else {
13229            return StorageManager.UUID_PRIVATE_INTERNAL;
13230        }
13231    }
13232
13233    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13234        if (isExternal(pkg)) {
13235            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13236                return mSettings.getExternalVersion();
13237            } else {
13238                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13239            }
13240        } else {
13241            return mSettings.getInternalVersion();
13242        }
13243    }
13244
13245    private void deleteTempPackageFiles() {
13246        final FilenameFilter filter = new FilenameFilter() {
13247            public boolean accept(File dir, String name) {
13248                return name.startsWith("vmdl") && name.endsWith(".tmp");
13249            }
13250        };
13251        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13252            file.delete();
13253        }
13254    }
13255
13256    @Override
13257    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13258            int flags) {
13259        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13260                flags);
13261    }
13262
13263    @Override
13264    public void deletePackage(final String packageName,
13265            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13266        mContext.enforceCallingOrSelfPermission(
13267                android.Manifest.permission.DELETE_PACKAGES, null);
13268        Preconditions.checkNotNull(packageName);
13269        Preconditions.checkNotNull(observer);
13270        final int uid = Binder.getCallingUid();
13271        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13272        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13273        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13274            mContext.enforceCallingOrSelfPermission(
13275                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13276                    "deletePackage for user " + userId);
13277        }
13278
13279        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13280            try {
13281                observer.onPackageDeleted(packageName,
13282                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13283            } catch (RemoteException re) {
13284            }
13285            return;
13286        }
13287
13288        for (int currentUserId : users) {
13289            if (getBlockUninstallForUser(packageName, currentUserId)) {
13290                try {
13291                    observer.onPackageDeleted(packageName,
13292                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13293                } catch (RemoteException re) {
13294                }
13295                return;
13296            }
13297        }
13298
13299        if (DEBUG_REMOVE) {
13300            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13301        }
13302        // Queue up an async operation since the package deletion may take a little while.
13303        mHandler.post(new Runnable() {
13304            public void run() {
13305                mHandler.removeCallbacks(this);
13306                final int returnCode = deletePackageX(packageName, userId, flags);
13307                try {
13308                    observer.onPackageDeleted(packageName, returnCode, null);
13309                } catch (RemoteException e) {
13310                    Log.i(TAG, "Observer no longer exists.");
13311                } //end catch
13312            } //end run
13313        });
13314    }
13315
13316    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13317        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13318                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13319        try {
13320            if (dpm != null) {
13321                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13322                        /* callingUserOnly =*/ false);
13323                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13324                        : deviceOwnerComponentName.getPackageName();
13325                // Does the package contains the device owner?
13326                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13327                // this check is probably not needed, since DO should be registered as a device
13328                // admin on some user too. (Original bug for this: b/17657954)
13329                if (packageName.equals(deviceOwnerPackageName)) {
13330                    return true;
13331                }
13332                // Does it contain a device admin for any user?
13333                int[] users;
13334                if (userId == UserHandle.USER_ALL) {
13335                    users = sUserManager.getUserIds();
13336                } else {
13337                    users = new int[]{userId};
13338                }
13339                for (int i = 0; i < users.length; ++i) {
13340                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13341                        return true;
13342                    }
13343                }
13344            }
13345        } catch (RemoteException e) {
13346        }
13347        return false;
13348    }
13349
13350    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13351        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13352    }
13353
13354    /**
13355     *  This method is an internal method that could be get invoked either
13356     *  to delete an installed package or to clean up a failed installation.
13357     *  After deleting an installed package, a broadcast is sent to notify any
13358     *  listeners that the package has been installed. For cleaning up a failed
13359     *  installation, the broadcast is not necessary since the package's
13360     *  installation wouldn't have sent the initial broadcast either
13361     *  The key steps in deleting a package are
13362     *  deleting the package information in internal structures like mPackages,
13363     *  deleting the packages base directories through installd
13364     *  updating mSettings to reflect current status
13365     *  persisting settings for later use
13366     *  sending a broadcast if necessary
13367     */
13368    private int deletePackageX(String packageName, int userId, int flags) {
13369        final PackageRemovedInfo info = new PackageRemovedInfo();
13370        final boolean res;
13371
13372        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13373                ? UserHandle.ALL : new UserHandle(userId);
13374
13375        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13376            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13377            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13378        }
13379
13380        boolean removedForAllUsers = false;
13381        boolean systemUpdate = false;
13382
13383        PackageParser.Package uninstalledPkg;
13384
13385        // for the uninstall-updates case and restricted profiles, remember the per-
13386        // userhandle installed state
13387        int[] allUsers;
13388        boolean[] perUserInstalled;
13389        synchronized (mPackages) {
13390            uninstalledPkg = mPackages.get(packageName);
13391            PackageSetting ps = mSettings.mPackages.get(packageName);
13392            allUsers = sUserManager.getUserIds();
13393            perUserInstalled = new boolean[allUsers.length];
13394            for (int i = 0; i < allUsers.length; i++) {
13395                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13396            }
13397        }
13398
13399        synchronized (mInstallLock) {
13400            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13401            res = deletePackageLI(packageName, removeForUser,
13402                    true, allUsers, perUserInstalled,
13403                    flags | REMOVE_CHATTY, info, true);
13404            systemUpdate = info.isRemovedPackageSystemUpdate;
13405            synchronized (mPackages) {
13406                if (res) {
13407                    if (!systemUpdate && mPackages.get(packageName) == null) {
13408                        removedForAllUsers = true;
13409                    }
13410                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13411                }
13412            }
13413            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13414                    + " removedForAllUsers=" + removedForAllUsers);
13415        }
13416
13417        if (res) {
13418            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13419
13420            // If the removed package was a system update, the old system package
13421            // was re-enabled; we need to broadcast this information
13422            if (systemUpdate) {
13423                Bundle extras = new Bundle(1);
13424                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13425                        ? info.removedAppId : info.uid);
13426                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13427
13428                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13429                        extras, 0, null, null, null);
13430                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13431                        extras, 0, null, null, null);
13432                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13433                        null, 0, packageName, null, null);
13434            }
13435        }
13436        // Force a gc here.
13437        Runtime.getRuntime().gc();
13438        // Delete the resources here after sending the broadcast to let
13439        // other processes clean up before deleting resources.
13440        if (info.args != null) {
13441            synchronized (mInstallLock) {
13442                info.args.doPostDeleteLI(true);
13443            }
13444        }
13445
13446        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13447    }
13448
13449    class PackageRemovedInfo {
13450        String removedPackage;
13451        int uid = -1;
13452        int removedAppId = -1;
13453        int[] removedUsers = null;
13454        boolean isRemovedPackageSystemUpdate = false;
13455        // Clean up resources deleted packages.
13456        InstallArgs args = null;
13457
13458        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13459            Bundle extras = new Bundle(1);
13460            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13461            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13462            if (replacing) {
13463                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13464            }
13465            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13466            if (removedPackage != null) {
13467                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13468                        extras, 0, null, null, removedUsers);
13469                if (fullRemove && !replacing) {
13470                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13471                            extras, 0, null, null, removedUsers);
13472                }
13473            }
13474            if (removedAppId >= 0) {
13475                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13476                        removedUsers);
13477            }
13478        }
13479    }
13480
13481    /*
13482     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13483     * flag is not set, the data directory is removed as well.
13484     * make sure this flag is set for partially installed apps. If not its meaningless to
13485     * delete a partially installed application.
13486     */
13487    private void removePackageDataLI(PackageSetting ps,
13488            int[] allUserHandles, boolean[] perUserInstalled,
13489            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13490        String packageName = ps.name;
13491        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13492        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13493        // Retrieve object to delete permissions for shared user later on
13494        final PackageSetting deletedPs;
13495        // reader
13496        synchronized (mPackages) {
13497            deletedPs = mSettings.mPackages.get(packageName);
13498            if (outInfo != null) {
13499                outInfo.removedPackage = packageName;
13500                outInfo.removedUsers = deletedPs != null
13501                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13502                        : null;
13503            }
13504        }
13505        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13506            removeDataDirsLI(ps.volumeUuid, packageName);
13507            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13508        }
13509        // writer
13510        synchronized (mPackages) {
13511            if (deletedPs != null) {
13512                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13513                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13514                    clearDefaultBrowserIfNeeded(packageName);
13515                    if (outInfo != null) {
13516                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13517                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13518                    }
13519                    updatePermissionsLPw(deletedPs.name, null, 0);
13520                    if (deletedPs.sharedUser != null) {
13521                        // Remove permissions associated with package. Since runtime
13522                        // permissions are per user we have to kill the removed package
13523                        // or packages running under the shared user of the removed
13524                        // package if revoking the permissions requested only by the removed
13525                        // package is successful and this causes a change in gids.
13526                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13527                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13528                                    userId);
13529                            if (userIdToKill == UserHandle.USER_ALL
13530                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13531                                // If gids changed for this user, kill all affected packages.
13532                                mHandler.post(new Runnable() {
13533                                    @Override
13534                                    public void run() {
13535                                        // This has to happen with no lock held.
13536                                        killApplication(deletedPs.name, deletedPs.appId,
13537                                                KILL_APP_REASON_GIDS_CHANGED);
13538                                    }
13539                                });
13540                                break;
13541                            }
13542                        }
13543                    }
13544                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13545                }
13546                // make sure to preserve per-user disabled state if this removal was just
13547                // a downgrade of a system app to the factory package
13548                if (allUserHandles != null && perUserInstalled != null) {
13549                    if (DEBUG_REMOVE) {
13550                        Slog.d(TAG, "Propagating install state across downgrade");
13551                    }
13552                    for (int i = 0; i < allUserHandles.length; i++) {
13553                        if (DEBUG_REMOVE) {
13554                            Slog.d(TAG, "    user " + allUserHandles[i]
13555                                    + " => " + perUserInstalled[i]);
13556                        }
13557                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13558                    }
13559                }
13560            }
13561            // can downgrade to reader
13562            if (writeSettings) {
13563                // Save settings now
13564                mSettings.writeLPr();
13565            }
13566        }
13567        if (outInfo != null) {
13568            // A user ID was deleted here. Go through all users and remove it
13569            // from KeyStore.
13570            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13571        }
13572    }
13573
13574    static boolean locationIsPrivileged(File path) {
13575        try {
13576            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13577                    .getCanonicalPath();
13578            return path.getCanonicalPath().startsWith(privilegedAppDir);
13579        } catch (IOException e) {
13580            Slog.e(TAG, "Unable to access code path " + path);
13581        }
13582        return false;
13583    }
13584
13585    /*
13586     * Tries to delete system package.
13587     */
13588    private boolean deleteSystemPackageLI(PackageSetting newPs,
13589            int[] allUserHandles, boolean[] perUserInstalled,
13590            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13591        final boolean applyUserRestrictions
13592                = (allUserHandles != null) && (perUserInstalled != null);
13593        PackageSetting disabledPs = null;
13594        // Confirm if the system package has been updated
13595        // An updated system app can be deleted. This will also have to restore
13596        // the system pkg from system partition
13597        // reader
13598        synchronized (mPackages) {
13599            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13600        }
13601        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13602                + " disabledPs=" + disabledPs);
13603        if (disabledPs == null) {
13604            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13605            return false;
13606        } else if (DEBUG_REMOVE) {
13607            Slog.d(TAG, "Deleting system pkg from data partition");
13608        }
13609        if (DEBUG_REMOVE) {
13610            if (applyUserRestrictions) {
13611                Slog.d(TAG, "Remembering install states:");
13612                for (int i = 0; i < allUserHandles.length; i++) {
13613                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13614                }
13615            }
13616        }
13617        // Delete the updated package
13618        outInfo.isRemovedPackageSystemUpdate = true;
13619        if (disabledPs.versionCode < newPs.versionCode) {
13620            // Delete data for downgrades
13621            flags &= ~PackageManager.DELETE_KEEP_DATA;
13622        } else {
13623            // Preserve data by setting flag
13624            flags |= PackageManager.DELETE_KEEP_DATA;
13625        }
13626        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13627                allUserHandles, perUserInstalled, outInfo, writeSettings);
13628        if (!ret) {
13629            return false;
13630        }
13631        // writer
13632        synchronized (mPackages) {
13633            // Reinstate the old system package
13634            mSettings.enableSystemPackageLPw(newPs.name);
13635            // Remove any native libraries from the upgraded package.
13636            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13637        }
13638        // Install the system package
13639        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13640        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13641        if (locationIsPrivileged(disabledPs.codePath)) {
13642            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13643        }
13644
13645        final PackageParser.Package newPkg;
13646        try {
13647            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13648        } catch (PackageManagerException e) {
13649            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13650            return false;
13651        }
13652
13653        // writer
13654        synchronized (mPackages) {
13655            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13656
13657            // Propagate the permissions state as we do not want to drop on the floor
13658            // runtime permissions. The update permissions method below will take
13659            // care of removing obsolete permissions and grant install permissions.
13660            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13661            updatePermissionsLPw(newPkg.packageName, newPkg,
13662                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13663
13664            if (applyUserRestrictions) {
13665                if (DEBUG_REMOVE) {
13666                    Slog.d(TAG, "Propagating install state across reinstall");
13667                }
13668                for (int i = 0; i < allUserHandles.length; i++) {
13669                    if (DEBUG_REMOVE) {
13670                        Slog.d(TAG, "    user " + allUserHandles[i]
13671                                + " => " + perUserInstalled[i]);
13672                    }
13673                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13674
13675                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13676                }
13677                // Regardless of writeSettings we need to ensure that this restriction
13678                // state propagation is persisted
13679                mSettings.writeAllUsersPackageRestrictionsLPr();
13680            }
13681            // can downgrade to reader here
13682            if (writeSettings) {
13683                mSettings.writeLPr();
13684            }
13685        }
13686        return true;
13687    }
13688
13689    private boolean deleteInstalledPackageLI(PackageSetting ps,
13690            boolean deleteCodeAndResources, int flags,
13691            int[] allUserHandles, boolean[] perUserInstalled,
13692            PackageRemovedInfo outInfo, boolean writeSettings) {
13693        if (outInfo != null) {
13694            outInfo.uid = ps.appId;
13695        }
13696
13697        // Delete package data from internal structures and also remove data if flag is set
13698        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13699
13700        // Delete application code and resources
13701        if (deleteCodeAndResources && (outInfo != null)) {
13702            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13703                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13704            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13705        }
13706        return true;
13707    }
13708
13709    @Override
13710    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13711            int userId) {
13712        mContext.enforceCallingOrSelfPermission(
13713                android.Manifest.permission.DELETE_PACKAGES, null);
13714        synchronized (mPackages) {
13715            PackageSetting ps = mSettings.mPackages.get(packageName);
13716            if (ps == null) {
13717                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13718                return false;
13719            }
13720            if (!ps.getInstalled(userId)) {
13721                // Can't block uninstall for an app that is not installed or enabled.
13722                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13723                return false;
13724            }
13725            ps.setBlockUninstall(blockUninstall, userId);
13726            mSettings.writePackageRestrictionsLPr(userId);
13727        }
13728        return true;
13729    }
13730
13731    @Override
13732    public boolean getBlockUninstallForUser(String packageName, int userId) {
13733        synchronized (mPackages) {
13734            PackageSetting ps = mSettings.mPackages.get(packageName);
13735            if (ps == null) {
13736                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13737                return false;
13738            }
13739            return ps.getBlockUninstall(userId);
13740        }
13741    }
13742
13743    /*
13744     * This method handles package deletion in general
13745     */
13746    private boolean deletePackageLI(String packageName, UserHandle user,
13747            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13748            int flags, PackageRemovedInfo outInfo,
13749            boolean writeSettings) {
13750        if (packageName == null) {
13751            Slog.w(TAG, "Attempt to delete null packageName.");
13752            return false;
13753        }
13754        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13755        PackageSetting ps;
13756        boolean dataOnly = false;
13757        int removeUser = -1;
13758        int appId = -1;
13759        synchronized (mPackages) {
13760            ps = mSettings.mPackages.get(packageName);
13761            if (ps == null) {
13762                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13763                return false;
13764            }
13765            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13766                    && user.getIdentifier() != UserHandle.USER_ALL) {
13767                // The caller is asking that the package only be deleted for a single
13768                // user.  To do this, we just mark its uninstalled state and delete
13769                // its data.  If this is a system app, we only allow this to happen if
13770                // they have set the special DELETE_SYSTEM_APP which requests different
13771                // semantics than normal for uninstalling system apps.
13772                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13773                final int userId = user.getIdentifier();
13774                ps.setUserState(userId,
13775                        COMPONENT_ENABLED_STATE_DEFAULT,
13776                        false, //installed
13777                        true,  //stopped
13778                        true,  //notLaunched
13779                        false, //hidden
13780                        null, null, null,
13781                        false, // blockUninstall
13782                        ps.readUserState(userId).domainVerificationStatus, 0);
13783                if (!isSystemApp(ps)) {
13784                    // Do not uninstall the APK if an app should be cached
13785                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13786                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13787                        // Other user still have this package installed, so all
13788                        // we need to do is clear this user's data and save that
13789                        // it is uninstalled.
13790                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13791                        removeUser = user.getIdentifier();
13792                        appId = ps.appId;
13793                        scheduleWritePackageRestrictionsLocked(removeUser);
13794                    } else {
13795                        // We need to set it back to 'installed' so the uninstall
13796                        // broadcasts will be sent correctly.
13797                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13798                        ps.setInstalled(true, user.getIdentifier());
13799                    }
13800                } else {
13801                    // This is a system app, so we assume that the
13802                    // other users still have this package installed, so all
13803                    // we need to do is clear this user's data and save that
13804                    // it is uninstalled.
13805                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13806                    removeUser = user.getIdentifier();
13807                    appId = ps.appId;
13808                    scheduleWritePackageRestrictionsLocked(removeUser);
13809                }
13810            }
13811        }
13812
13813        if (removeUser >= 0) {
13814            // From above, we determined that we are deleting this only
13815            // for a single user.  Continue the work here.
13816            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13817            if (outInfo != null) {
13818                outInfo.removedPackage = packageName;
13819                outInfo.removedAppId = appId;
13820                outInfo.removedUsers = new int[] {removeUser};
13821            }
13822            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13823            removeKeystoreDataIfNeeded(removeUser, appId);
13824            schedulePackageCleaning(packageName, removeUser, false);
13825            synchronized (mPackages) {
13826                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13827                    scheduleWritePackageRestrictionsLocked(removeUser);
13828                }
13829                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13830            }
13831            return true;
13832        }
13833
13834        if (dataOnly) {
13835            // Delete application data first
13836            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13837            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13838            return true;
13839        }
13840
13841        boolean ret = false;
13842        if (isSystemApp(ps)) {
13843            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13844            // When an updated system application is deleted we delete the existing resources as well and
13845            // fall back to existing code in system partition
13846            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13847                    flags, outInfo, writeSettings);
13848        } else {
13849            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13850            // Kill application pre-emptively especially for apps on sd.
13851            killApplication(packageName, ps.appId, "uninstall pkg");
13852            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13853                    allUserHandles, perUserInstalled,
13854                    outInfo, writeSettings);
13855        }
13856
13857        return ret;
13858    }
13859
13860    private final class ClearStorageConnection implements ServiceConnection {
13861        IMediaContainerService mContainerService;
13862
13863        @Override
13864        public void onServiceConnected(ComponentName name, IBinder service) {
13865            synchronized (this) {
13866                mContainerService = IMediaContainerService.Stub.asInterface(service);
13867                notifyAll();
13868            }
13869        }
13870
13871        @Override
13872        public void onServiceDisconnected(ComponentName name) {
13873        }
13874    }
13875
13876    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13877        final boolean mounted;
13878        if (Environment.isExternalStorageEmulated()) {
13879            mounted = true;
13880        } else {
13881            final String status = Environment.getExternalStorageState();
13882
13883            mounted = status.equals(Environment.MEDIA_MOUNTED)
13884                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13885        }
13886
13887        if (!mounted) {
13888            return;
13889        }
13890
13891        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13892        int[] users;
13893        if (userId == UserHandle.USER_ALL) {
13894            users = sUserManager.getUserIds();
13895        } else {
13896            users = new int[] { userId };
13897        }
13898        final ClearStorageConnection conn = new ClearStorageConnection();
13899        if (mContext.bindServiceAsUser(
13900                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13901            try {
13902                for (int curUser : users) {
13903                    long timeout = SystemClock.uptimeMillis() + 5000;
13904                    synchronized (conn) {
13905                        long now = SystemClock.uptimeMillis();
13906                        while (conn.mContainerService == null && now < timeout) {
13907                            try {
13908                                conn.wait(timeout - now);
13909                            } catch (InterruptedException e) {
13910                            }
13911                        }
13912                    }
13913                    if (conn.mContainerService == null) {
13914                        return;
13915                    }
13916
13917                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13918                    clearDirectory(conn.mContainerService,
13919                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13920                    if (allData) {
13921                        clearDirectory(conn.mContainerService,
13922                                userEnv.buildExternalStorageAppDataDirs(packageName));
13923                        clearDirectory(conn.mContainerService,
13924                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13925                    }
13926                }
13927            } finally {
13928                mContext.unbindService(conn);
13929            }
13930        }
13931    }
13932
13933    @Override
13934    public void clearApplicationUserData(final String packageName,
13935            final IPackageDataObserver observer, final int userId) {
13936        mContext.enforceCallingOrSelfPermission(
13937                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13938        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13939        // Queue up an async operation since the package deletion may take a little while.
13940        mHandler.post(new Runnable() {
13941            public void run() {
13942                mHandler.removeCallbacks(this);
13943                final boolean succeeded;
13944                synchronized (mInstallLock) {
13945                    succeeded = clearApplicationUserDataLI(packageName, userId);
13946                }
13947                clearExternalStorageDataSync(packageName, userId, true);
13948                if (succeeded) {
13949                    // invoke DeviceStorageMonitor's update method to clear any notifications
13950                    DeviceStorageMonitorInternal
13951                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13952                    if (dsm != null) {
13953                        dsm.checkMemory();
13954                    }
13955                }
13956                if(observer != null) {
13957                    try {
13958                        observer.onRemoveCompleted(packageName, succeeded);
13959                    } catch (RemoteException e) {
13960                        Log.i(TAG, "Observer no longer exists.");
13961                    }
13962                } //end if observer
13963            } //end run
13964        });
13965    }
13966
13967    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13968        if (packageName == null) {
13969            Slog.w(TAG, "Attempt to delete null packageName.");
13970            return false;
13971        }
13972
13973        // Try finding details about the requested package
13974        PackageParser.Package pkg;
13975        synchronized (mPackages) {
13976            pkg = mPackages.get(packageName);
13977            if (pkg == null) {
13978                final PackageSetting ps = mSettings.mPackages.get(packageName);
13979                if (ps != null) {
13980                    pkg = ps.pkg;
13981                }
13982            }
13983
13984            if (pkg == null) {
13985                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13986                return false;
13987            }
13988
13989            PackageSetting ps = (PackageSetting) pkg.mExtras;
13990            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13991        }
13992
13993        // Always delete data directories for package, even if we found no other
13994        // record of app. This helps users recover from UID mismatches without
13995        // resorting to a full data wipe.
13996        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13997        if (retCode < 0) {
13998            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13999            return false;
14000        }
14001
14002        final int appId = pkg.applicationInfo.uid;
14003        removeKeystoreDataIfNeeded(userId, appId);
14004
14005        // Create a native library symlink only if we have native libraries
14006        // and if the native libraries are 32 bit libraries. We do not provide
14007        // this symlink for 64 bit libraries.
14008        if (pkg.applicationInfo.primaryCpuAbi != null &&
14009                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14010            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14011            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14012                    nativeLibPath, userId) < 0) {
14013                Slog.w(TAG, "Failed linking native library dir");
14014                return false;
14015            }
14016        }
14017
14018        return true;
14019    }
14020
14021    /**
14022     * Reverts user permission state changes (permissions and flags) in
14023     * all packages for a given user.
14024     *
14025     * @param userId The device user for which to do a reset.
14026     */
14027    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14028        final int packageCount = mPackages.size();
14029        for (int i = 0; i < packageCount; i++) {
14030            PackageParser.Package pkg = mPackages.valueAt(i);
14031            PackageSetting ps = (PackageSetting) pkg.mExtras;
14032            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14033        }
14034    }
14035
14036    /**
14037     * Reverts user permission state changes (permissions and flags).
14038     *
14039     * @param ps The package for which to reset.
14040     * @param userId The device user for which to do a reset.
14041     */
14042    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14043            final PackageSetting ps, final int userId) {
14044        if (ps.pkg == null) {
14045            return;
14046        }
14047
14048        // These are flags that can change base on user actions.
14049        final int userSettableMask = FLAG_PERMISSION_USER_SET
14050                | FLAG_PERMISSION_USER_FIXED
14051                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14052                | FLAG_PERMISSION_REVIEW_REQUIRED;
14053
14054        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14055                | FLAG_PERMISSION_POLICY_FIXED;
14056
14057        boolean writeInstallPermissions = false;
14058        boolean writeRuntimePermissions = false;
14059
14060        final int permissionCount = ps.pkg.requestedPermissions.size();
14061        for (int i = 0; i < permissionCount; i++) {
14062            String permission = ps.pkg.requestedPermissions.get(i);
14063
14064            BasePermission bp = mSettings.mPermissions.get(permission);
14065            if (bp == null) {
14066                continue;
14067            }
14068
14069            // If shared user we just reset the state to which only this app contributed.
14070            if (ps.sharedUser != null) {
14071                boolean used = false;
14072                final int packageCount = ps.sharedUser.packages.size();
14073                for (int j = 0; j < packageCount; j++) {
14074                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14075                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14076                            && pkg.pkg.requestedPermissions.contains(permission)) {
14077                        used = true;
14078                        break;
14079                    }
14080                }
14081                if (used) {
14082                    continue;
14083                }
14084            }
14085
14086            PermissionsState permissionsState = ps.getPermissionsState();
14087
14088            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14089
14090            // Always clear the user settable flags.
14091            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14092                    bp.name) != null;
14093            // If permission review is enabled and this is a legacy app, mark the
14094            // permission as requiring a review as this is the initial state.
14095            int flags = 0;
14096            if (Build.PERMISSIONS_REVIEW_REQUIRED
14097                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14098                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14099            }
14100            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14101                if (hasInstallState) {
14102                    writeInstallPermissions = true;
14103                } else {
14104                    writeRuntimePermissions = true;
14105                }
14106            }
14107
14108            // Below is only runtime permission handling.
14109            if (!bp.isRuntime()) {
14110                continue;
14111            }
14112
14113            // Never clobber system or policy.
14114            if ((oldFlags & policyOrSystemFlags) != 0) {
14115                continue;
14116            }
14117
14118            // If this permission was granted by default, make sure it is.
14119            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14120                if (permissionsState.grantRuntimePermission(bp, userId)
14121                        != PERMISSION_OPERATION_FAILURE) {
14122                    writeRuntimePermissions = true;
14123                }
14124            // If permission review is enabled the permissions for a legacy apps
14125            // are represented as constantly granted runtime ones, so don't revoke.
14126            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14127                // Otherwise, reset the permission.
14128                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14129                switch (revokeResult) {
14130                    case PERMISSION_OPERATION_SUCCESS: {
14131                        writeRuntimePermissions = true;
14132                    } break;
14133
14134                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14135                        writeRuntimePermissions = true;
14136                        final int appId = ps.appId;
14137                        mHandler.post(new Runnable() {
14138                            @Override
14139                            public void run() {
14140                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14141                            }
14142                        });
14143                    } break;
14144                }
14145            }
14146        }
14147
14148        // Synchronously write as we are taking permissions away.
14149        if (writeRuntimePermissions) {
14150            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14151        }
14152
14153        // Synchronously write as we are taking permissions away.
14154        if (writeInstallPermissions) {
14155            mSettings.writeLPr();
14156        }
14157    }
14158
14159    /**
14160     * Remove entries from the keystore daemon. Will only remove it if the
14161     * {@code appId} is valid.
14162     */
14163    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14164        if (appId < 0) {
14165            return;
14166        }
14167
14168        final KeyStore keyStore = KeyStore.getInstance();
14169        if (keyStore != null) {
14170            if (userId == UserHandle.USER_ALL) {
14171                for (final int individual : sUserManager.getUserIds()) {
14172                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14173                }
14174            } else {
14175                keyStore.clearUid(UserHandle.getUid(userId, appId));
14176            }
14177        } else {
14178            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14179        }
14180    }
14181
14182    @Override
14183    public void deleteApplicationCacheFiles(final String packageName,
14184            final IPackageDataObserver observer) {
14185        mContext.enforceCallingOrSelfPermission(
14186                android.Manifest.permission.DELETE_CACHE_FILES, null);
14187        // Queue up an async operation since the package deletion may take a little while.
14188        final int userId = UserHandle.getCallingUserId();
14189        mHandler.post(new Runnable() {
14190            public void run() {
14191                mHandler.removeCallbacks(this);
14192                final boolean succeded;
14193                synchronized (mInstallLock) {
14194                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14195                }
14196                clearExternalStorageDataSync(packageName, userId, false);
14197                if (observer != null) {
14198                    try {
14199                        observer.onRemoveCompleted(packageName, succeded);
14200                    } catch (RemoteException e) {
14201                        Log.i(TAG, "Observer no longer exists.");
14202                    }
14203                } //end if observer
14204            } //end run
14205        });
14206    }
14207
14208    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14209        if (packageName == null) {
14210            Slog.w(TAG, "Attempt to delete null packageName.");
14211            return false;
14212        }
14213        PackageParser.Package p;
14214        synchronized (mPackages) {
14215            p = mPackages.get(packageName);
14216        }
14217        if (p == null) {
14218            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14219            return false;
14220        }
14221        final ApplicationInfo applicationInfo = p.applicationInfo;
14222        if (applicationInfo == null) {
14223            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14224            return false;
14225        }
14226        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14227        if (retCode < 0) {
14228            Slog.w(TAG, "Couldn't remove cache files for package: "
14229                       + packageName + " u" + userId);
14230            return false;
14231        }
14232        return true;
14233    }
14234
14235    @Override
14236    public void getPackageSizeInfo(final String packageName, int userHandle,
14237            final IPackageStatsObserver observer) {
14238        mContext.enforceCallingOrSelfPermission(
14239                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14240        if (packageName == null) {
14241            throw new IllegalArgumentException("Attempt to get size of null packageName");
14242        }
14243
14244        PackageStats stats = new PackageStats(packageName, userHandle);
14245
14246        /*
14247         * Queue up an async operation since the package measurement may take a
14248         * little while.
14249         */
14250        Message msg = mHandler.obtainMessage(INIT_COPY);
14251        msg.obj = new MeasureParams(stats, observer);
14252        mHandler.sendMessage(msg);
14253    }
14254
14255    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14256            PackageStats pStats) {
14257        if (packageName == null) {
14258            Slog.w(TAG, "Attempt to get size of null packageName.");
14259            return false;
14260        }
14261        PackageParser.Package p;
14262        boolean dataOnly = false;
14263        String libDirRoot = null;
14264        String asecPath = null;
14265        PackageSetting ps = null;
14266        synchronized (mPackages) {
14267            p = mPackages.get(packageName);
14268            ps = mSettings.mPackages.get(packageName);
14269            if(p == null) {
14270                dataOnly = true;
14271                if((ps == null) || (ps.pkg == null)) {
14272                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14273                    return false;
14274                }
14275                p = ps.pkg;
14276            }
14277            if (ps != null) {
14278                libDirRoot = ps.legacyNativeLibraryPathString;
14279            }
14280            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14281                final long token = Binder.clearCallingIdentity();
14282                try {
14283                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14284                    if (secureContainerId != null) {
14285                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14286                    }
14287                } finally {
14288                    Binder.restoreCallingIdentity(token);
14289                }
14290            }
14291        }
14292        String publicSrcDir = null;
14293        if(!dataOnly) {
14294            final ApplicationInfo applicationInfo = p.applicationInfo;
14295            if (applicationInfo == null) {
14296                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14297                return false;
14298            }
14299            if (p.isForwardLocked()) {
14300                publicSrcDir = applicationInfo.getBaseResourcePath();
14301            }
14302        }
14303        // TODO: extend to measure size of split APKs
14304        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14305        // not just the first level.
14306        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14307        // just the primary.
14308        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14309
14310        String apkPath;
14311        File packageDir = new File(p.codePath);
14312
14313        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14314            apkPath = packageDir.getAbsolutePath();
14315            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14316            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14317                libDirRoot = null;
14318            }
14319        } else {
14320            apkPath = p.baseCodePath;
14321        }
14322
14323        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14324                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14325        if (res < 0) {
14326            return false;
14327        }
14328
14329        // Fix-up for forward-locked applications in ASEC containers.
14330        if (!isExternal(p)) {
14331            pStats.codeSize += pStats.externalCodeSize;
14332            pStats.externalCodeSize = 0L;
14333        }
14334
14335        return true;
14336    }
14337
14338
14339    @Override
14340    public void addPackageToPreferred(String packageName) {
14341        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14342    }
14343
14344    @Override
14345    public void removePackageFromPreferred(String packageName) {
14346        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14347    }
14348
14349    @Override
14350    public List<PackageInfo> getPreferredPackages(int flags) {
14351        return new ArrayList<PackageInfo>();
14352    }
14353
14354    private int getUidTargetSdkVersionLockedLPr(int uid) {
14355        Object obj = mSettings.getUserIdLPr(uid);
14356        if (obj instanceof SharedUserSetting) {
14357            final SharedUserSetting sus = (SharedUserSetting) obj;
14358            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14359            final Iterator<PackageSetting> it = sus.packages.iterator();
14360            while (it.hasNext()) {
14361                final PackageSetting ps = it.next();
14362                if (ps.pkg != null) {
14363                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14364                    if (v < vers) vers = v;
14365                }
14366            }
14367            return vers;
14368        } else if (obj instanceof PackageSetting) {
14369            final PackageSetting ps = (PackageSetting) obj;
14370            if (ps.pkg != null) {
14371                return ps.pkg.applicationInfo.targetSdkVersion;
14372            }
14373        }
14374        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14375    }
14376
14377    @Override
14378    public void addPreferredActivity(IntentFilter filter, int match,
14379            ComponentName[] set, ComponentName activity, int userId) {
14380        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14381                "Adding preferred");
14382    }
14383
14384    private void addPreferredActivityInternal(IntentFilter filter, int match,
14385            ComponentName[] set, ComponentName activity, boolean always, int userId,
14386            String opname) {
14387        // writer
14388        int callingUid = Binder.getCallingUid();
14389        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14390        if (filter.countActions() == 0) {
14391            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14392            return;
14393        }
14394        synchronized (mPackages) {
14395            if (mContext.checkCallingOrSelfPermission(
14396                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14397                    != PackageManager.PERMISSION_GRANTED) {
14398                if (getUidTargetSdkVersionLockedLPr(callingUid)
14399                        < Build.VERSION_CODES.FROYO) {
14400                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14401                            + callingUid);
14402                    return;
14403                }
14404                mContext.enforceCallingOrSelfPermission(
14405                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14406            }
14407
14408            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14409            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14410                    + userId + ":");
14411            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14412            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14413            scheduleWritePackageRestrictionsLocked(userId);
14414        }
14415    }
14416
14417    @Override
14418    public void replacePreferredActivity(IntentFilter filter, int match,
14419            ComponentName[] set, ComponentName activity, int userId) {
14420        if (filter.countActions() != 1) {
14421            throw new IllegalArgumentException(
14422                    "replacePreferredActivity expects filter to have only 1 action.");
14423        }
14424        if (filter.countDataAuthorities() != 0
14425                || filter.countDataPaths() != 0
14426                || filter.countDataSchemes() > 1
14427                || filter.countDataTypes() != 0) {
14428            throw new IllegalArgumentException(
14429                    "replacePreferredActivity expects filter to have no data authorities, " +
14430                    "paths, or types; and at most one scheme.");
14431        }
14432
14433        final int callingUid = Binder.getCallingUid();
14434        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14435        synchronized (mPackages) {
14436            if (mContext.checkCallingOrSelfPermission(
14437                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14438                    != PackageManager.PERMISSION_GRANTED) {
14439                if (getUidTargetSdkVersionLockedLPr(callingUid)
14440                        < Build.VERSION_CODES.FROYO) {
14441                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14442                            + Binder.getCallingUid());
14443                    return;
14444                }
14445                mContext.enforceCallingOrSelfPermission(
14446                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14447            }
14448
14449            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14450            if (pir != null) {
14451                // Get all of the existing entries that exactly match this filter.
14452                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14453                if (existing != null && existing.size() == 1) {
14454                    PreferredActivity cur = existing.get(0);
14455                    if (DEBUG_PREFERRED) {
14456                        Slog.i(TAG, "Checking replace of preferred:");
14457                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14458                        if (!cur.mPref.mAlways) {
14459                            Slog.i(TAG, "  -- CUR; not mAlways!");
14460                        } else {
14461                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14462                            Slog.i(TAG, "  -- CUR: mSet="
14463                                    + Arrays.toString(cur.mPref.mSetComponents));
14464                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14465                            Slog.i(TAG, "  -- NEW: mMatch="
14466                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14467                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14468                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14469                        }
14470                    }
14471                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14472                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14473                            && cur.mPref.sameSet(set)) {
14474                        // Setting the preferred activity to what it happens to be already
14475                        if (DEBUG_PREFERRED) {
14476                            Slog.i(TAG, "Replacing with same preferred activity "
14477                                    + cur.mPref.mShortComponent + " for user "
14478                                    + userId + ":");
14479                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14480                        }
14481                        return;
14482                    }
14483                }
14484
14485                if (existing != null) {
14486                    if (DEBUG_PREFERRED) {
14487                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14488                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14489                    }
14490                    for (int i = 0; i < existing.size(); i++) {
14491                        PreferredActivity pa = existing.get(i);
14492                        if (DEBUG_PREFERRED) {
14493                            Slog.i(TAG, "Removing existing preferred activity "
14494                                    + pa.mPref.mComponent + ":");
14495                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14496                        }
14497                        pir.removeFilter(pa);
14498                    }
14499                }
14500            }
14501            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14502                    "Replacing preferred");
14503        }
14504    }
14505
14506    @Override
14507    public void clearPackagePreferredActivities(String packageName) {
14508        final int uid = Binder.getCallingUid();
14509        // writer
14510        synchronized (mPackages) {
14511            PackageParser.Package pkg = mPackages.get(packageName);
14512            if (pkg == null || pkg.applicationInfo.uid != uid) {
14513                if (mContext.checkCallingOrSelfPermission(
14514                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14515                        != PackageManager.PERMISSION_GRANTED) {
14516                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14517                            < Build.VERSION_CODES.FROYO) {
14518                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14519                                + Binder.getCallingUid());
14520                        return;
14521                    }
14522                    mContext.enforceCallingOrSelfPermission(
14523                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14524                }
14525            }
14526
14527            int user = UserHandle.getCallingUserId();
14528            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14529                scheduleWritePackageRestrictionsLocked(user);
14530            }
14531        }
14532    }
14533
14534    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14535    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14536        ArrayList<PreferredActivity> removed = null;
14537        boolean changed = false;
14538        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14539            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14540            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14541            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14542                continue;
14543            }
14544            Iterator<PreferredActivity> it = pir.filterIterator();
14545            while (it.hasNext()) {
14546                PreferredActivity pa = it.next();
14547                // Mark entry for removal only if it matches the package name
14548                // and the entry is of type "always".
14549                if (packageName == null ||
14550                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14551                                && pa.mPref.mAlways)) {
14552                    if (removed == null) {
14553                        removed = new ArrayList<PreferredActivity>();
14554                    }
14555                    removed.add(pa);
14556                }
14557            }
14558            if (removed != null) {
14559                for (int j=0; j<removed.size(); j++) {
14560                    PreferredActivity pa = removed.get(j);
14561                    pir.removeFilter(pa);
14562                }
14563                changed = true;
14564            }
14565        }
14566        return changed;
14567    }
14568
14569    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14570    private void clearIntentFilterVerificationsLPw(int userId) {
14571        final int packageCount = mPackages.size();
14572        for (int i = 0; i < packageCount; i++) {
14573            PackageParser.Package pkg = mPackages.valueAt(i);
14574            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14575        }
14576    }
14577
14578    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14579    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14580        if (userId == UserHandle.USER_ALL) {
14581            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14582                    sUserManager.getUserIds())) {
14583                for (int oneUserId : sUserManager.getUserIds()) {
14584                    scheduleWritePackageRestrictionsLocked(oneUserId);
14585                }
14586            }
14587        } else {
14588            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14589                scheduleWritePackageRestrictionsLocked(userId);
14590            }
14591        }
14592    }
14593
14594    void clearDefaultBrowserIfNeeded(String packageName) {
14595        for (int oneUserId : sUserManager.getUserIds()) {
14596            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14597            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14598            if (packageName.equals(defaultBrowserPackageName)) {
14599                setDefaultBrowserPackageName(null, oneUserId);
14600            }
14601        }
14602    }
14603
14604    @Override
14605    public void resetApplicationPreferences(int userId) {
14606        mContext.enforceCallingOrSelfPermission(
14607                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14608        // writer
14609        synchronized (mPackages) {
14610            final long identity = Binder.clearCallingIdentity();
14611            try {
14612                clearPackagePreferredActivitiesLPw(null, userId);
14613                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14614                // TODO: We have to reset the default SMS and Phone. This requires
14615                // significant refactoring to keep all default apps in the package
14616                // manager (cleaner but more work) or have the services provide
14617                // callbacks to the package manager to request a default app reset.
14618                applyFactoryDefaultBrowserLPw(userId);
14619                clearIntentFilterVerificationsLPw(userId);
14620                primeDomainVerificationsLPw(userId);
14621                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14622                scheduleWritePackageRestrictionsLocked(userId);
14623            } finally {
14624                Binder.restoreCallingIdentity(identity);
14625            }
14626        }
14627    }
14628
14629    @Override
14630    public int getPreferredActivities(List<IntentFilter> outFilters,
14631            List<ComponentName> outActivities, String packageName) {
14632
14633        int num = 0;
14634        final int userId = UserHandle.getCallingUserId();
14635        // reader
14636        synchronized (mPackages) {
14637            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14638            if (pir != null) {
14639                final Iterator<PreferredActivity> it = pir.filterIterator();
14640                while (it.hasNext()) {
14641                    final PreferredActivity pa = it.next();
14642                    if (packageName == null
14643                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14644                                    && pa.mPref.mAlways)) {
14645                        if (outFilters != null) {
14646                            outFilters.add(new IntentFilter(pa));
14647                        }
14648                        if (outActivities != null) {
14649                            outActivities.add(pa.mPref.mComponent);
14650                        }
14651                    }
14652                }
14653            }
14654        }
14655
14656        return num;
14657    }
14658
14659    @Override
14660    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14661            int userId) {
14662        int callingUid = Binder.getCallingUid();
14663        if (callingUid != Process.SYSTEM_UID) {
14664            throw new SecurityException(
14665                    "addPersistentPreferredActivity can only be run by the system");
14666        }
14667        if (filter.countActions() == 0) {
14668            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14669            return;
14670        }
14671        synchronized (mPackages) {
14672            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14673                    " :");
14674            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14675            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14676                    new PersistentPreferredActivity(filter, activity));
14677            scheduleWritePackageRestrictionsLocked(userId);
14678        }
14679    }
14680
14681    @Override
14682    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14683        int callingUid = Binder.getCallingUid();
14684        if (callingUid != Process.SYSTEM_UID) {
14685            throw new SecurityException(
14686                    "clearPackagePersistentPreferredActivities can only be run by the system");
14687        }
14688        ArrayList<PersistentPreferredActivity> removed = null;
14689        boolean changed = false;
14690        synchronized (mPackages) {
14691            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14692                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14693                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14694                        .valueAt(i);
14695                if (userId != thisUserId) {
14696                    continue;
14697                }
14698                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14699                while (it.hasNext()) {
14700                    PersistentPreferredActivity ppa = it.next();
14701                    // Mark entry for removal only if it matches the package name.
14702                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14703                        if (removed == null) {
14704                            removed = new ArrayList<PersistentPreferredActivity>();
14705                        }
14706                        removed.add(ppa);
14707                    }
14708                }
14709                if (removed != null) {
14710                    for (int j=0; j<removed.size(); j++) {
14711                        PersistentPreferredActivity ppa = removed.get(j);
14712                        ppir.removeFilter(ppa);
14713                    }
14714                    changed = true;
14715                }
14716            }
14717
14718            if (changed) {
14719                scheduleWritePackageRestrictionsLocked(userId);
14720            }
14721        }
14722    }
14723
14724    /**
14725     * Common machinery for picking apart a restored XML blob and passing
14726     * it to a caller-supplied functor to be applied to the running system.
14727     */
14728    private void restoreFromXml(XmlPullParser parser, int userId,
14729            String expectedStartTag, BlobXmlRestorer functor)
14730            throws IOException, XmlPullParserException {
14731        int type;
14732        while ((type = parser.next()) != XmlPullParser.START_TAG
14733                && type != XmlPullParser.END_DOCUMENT) {
14734        }
14735        if (type != XmlPullParser.START_TAG) {
14736            // oops didn't find a start tag?!
14737            if (DEBUG_BACKUP) {
14738                Slog.e(TAG, "Didn't find start tag during restore");
14739            }
14740            return;
14741        }
14742
14743        // this is supposed to be TAG_PREFERRED_BACKUP
14744        if (!expectedStartTag.equals(parser.getName())) {
14745            if (DEBUG_BACKUP) {
14746                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14747            }
14748            return;
14749        }
14750
14751        // skip interfering stuff, then we're aligned with the backing implementation
14752        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14753        functor.apply(parser, userId);
14754    }
14755
14756    private interface BlobXmlRestorer {
14757        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14758    }
14759
14760    /**
14761     * Non-Binder method, support for the backup/restore mechanism: write the
14762     * full set of preferred activities in its canonical XML format.  Returns the
14763     * XML output as a byte array, or null if there is none.
14764     */
14765    @Override
14766    public byte[] getPreferredActivityBackup(int userId) {
14767        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14768            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14769        }
14770
14771        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14772        try {
14773            final XmlSerializer serializer = new FastXmlSerializer();
14774            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14775            serializer.startDocument(null, true);
14776            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14777
14778            synchronized (mPackages) {
14779                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14780            }
14781
14782            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14783            serializer.endDocument();
14784            serializer.flush();
14785        } catch (Exception e) {
14786            if (DEBUG_BACKUP) {
14787                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14788            }
14789            return null;
14790        }
14791
14792        return dataStream.toByteArray();
14793    }
14794
14795    @Override
14796    public void restorePreferredActivities(byte[] backup, int userId) {
14797        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14798            throw new SecurityException("Only the system may call restorePreferredActivities()");
14799        }
14800
14801        try {
14802            final XmlPullParser parser = Xml.newPullParser();
14803            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14804            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14805                    new BlobXmlRestorer() {
14806                        @Override
14807                        public void apply(XmlPullParser parser, int userId)
14808                                throws XmlPullParserException, IOException {
14809                            synchronized (mPackages) {
14810                                mSettings.readPreferredActivitiesLPw(parser, userId);
14811                            }
14812                        }
14813                    } );
14814        } catch (Exception e) {
14815            if (DEBUG_BACKUP) {
14816                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14817            }
14818        }
14819    }
14820
14821    /**
14822     * Non-Binder method, support for the backup/restore mechanism: write the
14823     * default browser (etc) settings in its canonical XML format.  Returns the default
14824     * browser XML representation as a byte array, or null if there is none.
14825     */
14826    @Override
14827    public byte[] getDefaultAppsBackup(int userId) {
14828        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14829            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14830        }
14831
14832        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14833        try {
14834            final XmlSerializer serializer = new FastXmlSerializer();
14835            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14836            serializer.startDocument(null, true);
14837            serializer.startTag(null, TAG_DEFAULT_APPS);
14838
14839            synchronized (mPackages) {
14840                mSettings.writeDefaultAppsLPr(serializer, userId);
14841            }
14842
14843            serializer.endTag(null, TAG_DEFAULT_APPS);
14844            serializer.endDocument();
14845            serializer.flush();
14846        } catch (Exception e) {
14847            if (DEBUG_BACKUP) {
14848                Slog.e(TAG, "Unable to write default apps for backup", e);
14849            }
14850            return null;
14851        }
14852
14853        return dataStream.toByteArray();
14854    }
14855
14856    @Override
14857    public void restoreDefaultApps(byte[] backup, int userId) {
14858        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14859            throw new SecurityException("Only the system may call restoreDefaultApps()");
14860        }
14861
14862        try {
14863            final XmlPullParser parser = Xml.newPullParser();
14864            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14865            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14866                    new BlobXmlRestorer() {
14867                        @Override
14868                        public void apply(XmlPullParser parser, int userId)
14869                                throws XmlPullParserException, IOException {
14870                            synchronized (mPackages) {
14871                                mSettings.readDefaultAppsLPw(parser, userId);
14872                            }
14873                        }
14874                    } );
14875        } catch (Exception e) {
14876            if (DEBUG_BACKUP) {
14877                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14878            }
14879        }
14880    }
14881
14882    @Override
14883    public byte[] getIntentFilterVerificationBackup(int userId) {
14884        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14885            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14886        }
14887
14888        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14889        try {
14890            final XmlSerializer serializer = new FastXmlSerializer();
14891            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14892            serializer.startDocument(null, true);
14893            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14894
14895            synchronized (mPackages) {
14896                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14897            }
14898
14899            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14900            serializer.endDocument();
14901            serializer.flush();
14902        } catch (Exception e) {
14903            if (DEBUG_BACKUP) {
14904                Slog.e(TAG, "Unable to write default apps for backup", e);
14905            }
14906            return null;
14907        }
14908
14909        return dataStream.toByteArray();
14910    }
14911
14912    @Override
14913    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14914        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14915            throw new SecurityException("Only the system may call restorePreferredActivities()");
14916        }
14917
14918        try {
14919            final XmlPullParser parser = Xml.newPullParser();
14920            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14921            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14922                    new BlobXmlRestorer() {
14923                        @Override
14924                        public void apply(XmlPullParser parser, int userId)
14925                                throws XmlPullParserException, IOException {
14926                            synchronized (mPackages) {
14927                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14928                                mSettings.writeLPr();
14929                            }
14930                        }
14931                    } );
14932        } catch (Exception e) {
14933            if (DEBUG_BACKUP) {
14934                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14935            }
14936        }
14937    }
14938
14939    @Override
14940    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14941            int sourceUserId, int targetUserId, int flags) {
14942        mContext.enforceCallingOrSelfPermission(
14943                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14944        int callingUid = Binder.getCallingUid();
14945        enforceOwnerRights(ownerPackage, callingUid);
14946        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14947        if (intentFilter.countActions() == 0) {
14948            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14949            return;
14950        }
14951        synchronized (mPackages) {
14952            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14953                    ownerPackage, targetUserId, flags);
14954            CrossProfileIntentResolver resolver =
14955                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14956            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14957            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14958            if (existing != null) {
14959                int size = existing.size();
14960                for (int i = 0; i < size; i++) {
14961                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14962                        return;
14963                    }
14964                }
14965            }
14966            resolver.addFilter(newFilter);
14967            scheduleWritePackageRestrictionsLocked(sourceUserId);
14968        }
14969    }
14970
14971    @Override
14972    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14973        mContext.enforceCallingOrSelfPermission(
14974                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14975        int callingUid = Binder.getCallingUid();
14976        enforceOwnerRights(ownerPackage, callingUid);
14977        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14978        synchronized (mPackages) {
14979            CrossProfileIntentResolver resolver =
14980                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14981            ArraySet<CrossProfileIntentFilter> set =
14982                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14983            for (CrossProfileIntentFilter filter : set) {
14984                if (filter.getOwnerPackage().equals(ownerPackage)) {
14985                    resolver.removeFilter(filter);
14986                }
14987            }
14988            scheduleWritePackageRestrictionsLocked(sourceUserId);
14989        }
14990    }
14991
14992    // Enforcing that callingUid is owning pkg on userId
14993    private void enforceOwnerRights(String pkg, int callingUid) {
14994        // The system owns everything.
14995        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14996            return;
14997        }
14998        int callingUserId = UserHandle.getUserId(callingUid);
14999        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15000        if (pi == null) {
15001            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15002                    + callingUserId);
15003        }
15004        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15005            throw new SecurityException("Calling uid " + callingUid
15006                    + " does not own package " + pkg);
15007        }
15008    }
15009
15010    @Override
15011    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15012        Intent intent = new Intent(Intent.ACTION_MAIN);
15013        intent.addCategory(Intent.CATEGORY_HOME);
15014
15015        final int callingUserId = UserHandle.getCallingUserId();
15016        List<ResolveInfo> list = queryIntentActivities(intent, null,
15017                PackageManager.GET_META_DATA, callingUserId);
15018        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15019                true, false, false, callingUserId);
15020
15021        allHomeCandidates.clear();
15022        if (list != null) {
15023            for (ResolveInfo ri : list) {
15024                allHomeCandidates.add(ri);
15025            }
15026        }
15027        return (preferred == null || preferred.activityInfo == null)
15028                ? null
15029                : new ComponentName(preferred.activityInfo.packageName,
15030                        preferred.activityInfo.name);
15031    }
15032
15033    @Override
15034    public void setApplicationEnabledSetting(String appPackageName,
15035            int newState, int flags, int userId, String callingPackage) {
15036        if (!sUserManager.exists(userId)) return;
15037        if (callingPackage == null) {
15038            callingPackage = Integer.toString(Binder.getCallingUid());
15039        }
15040        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15041    }
15042
15043    @Override
15044    public void setComponentEnabledSetting(ComponentName componentName,
15045            int newState, int flags, int userId) {
15046        if (!sUserManager.exists(userId)) return;
15047        setEnabledSetting(componentName.getPackageName(),
15048                componentName.getClassName(), newState, flags, userId, null);
15049    }
15050
15051    private void setEnabledSetting(final String packageName, String className, int newState,
15052            final int flags, int userId, String callingPackage) {
15053        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15054              || newState == COMPONENT_ENABLED_STATE_ENABLED
15055              || newState == COMPONENT_ENABLED_STATE_DISABLED
15056              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15057              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15058            throw new IllegalArgumentException("Invalid new component state: "
15059                    + newState);
15060        }
15061        PackageSetting pkgSetting;
15062        final int uid = Binder.getCallingUid();
15063        final int permission = mContext.checkCallingOrSelfPermission(
15064                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15065        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15066        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15067        boolean sendNow = false;
15068        boolean isApp = (className == null);
15069        String componentName = isApp ? packageName : className;
15070        int packageUid = -1;
15071        ArrayList<String> components;
15072
15073        // writer
15074        synchronized (mPackages) {
15075            pkgSetting = mSettings.mPackages.get(packageName);
15076            if (pkgSetting == null) {
15077                if (className == null) {
15078                    throw new IllegalArgumentException(
15079                            "Unknown package: " + packageName);
15080                }
15081                throw new IllegalArgumentException(
15082                        "Unknown component: " + packageName
15083                        + "/" + className);
15084            }
15085            // Allow root and verify that userId is not being specified by a different user
15086            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15087                throw new SecurityException(
15088                        "Permission Denial: attempt to change component state from pid="
15089                        + Binder.getCallingPid()
15090                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15091            }
15092            if (className == null) {
15093                // We're dealing with an application/package level state change
15094                if (pkgSetting.getEnabled(userId) == newState) {
15095                    // Nothing to do
15096                    return;
15097                }
15098                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15099                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15100                    // Don't care about who enables an app.
15101                    callingPackage = null;
15102                }
15103                pkgSetting.setEnabled(newState, userId, callingPackage);
15104                // pkgSetting.pkg.mSetEnabled = newState;
15105            } else {
15106                // We're dealing with a component level state change
15107                // First, verify that this is a valid class name.
15108                PackageParser.Package pkg = pkgSetting.pkg;
15109                if (pkg == null || !pkg.hasComponentClassName(className)) {
15110                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
15111                        throw new IllegalArgumentException("Component class " + className
15112                                + " does not exist in " + packageName);
15113                    } else {
15114                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15115                                + className + " does not exist in " + packageName);
15116                    }
15117                }
15118                switch (newState) {
15119                case COMPONENT_ENABLED_STATE_ENABLED:
15120                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15121                        return;
15122                    }
15123                    break;
15124                case COMPONENT_ENABLED_STATE_DISABLED:
15125                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15126                        return;
15127                    }
15128                    break;
15129                case COMPONENT_ENABLED_STATE_DEFAULT:
15130                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15131                        return;
15132                    }
15133                    break;
15134                default:
15135                    Slog.e(TAG, "Invalid new component state: " + newState);
15136                    return;
15137                }
15138            }
15139            scheduleWritePackageRestrictionsLocked(userId);
15140            components = mPendingBroadcasts.get(userId, packageName);
15141            final boolean newPackage = components == null;
15142            if (newPackage) {
15143                components = new ArrayList<String>();
15144            }
15145            if (!components.contains(componentName)) {
15146                components.add(componentName);
15147            }
15148            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15149                sendNow = true;
15150                // Purge entry from pending broadcast list if another one exists already
15151                // since we are sending one right away.
15152                mPendingBroadcasts.remove(userId, packageName);
15153            } else {
15154                if (newPackage) {
15155                    mPendingBroadcasts.put(userId, packageName, components);
15156                }
15157                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15158                    // Schedule a message
15159                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15160                }
15161            }
15162        }
15163
15164        long callingId = Binder.clearCallingIdentity();
15165        try {
15166            if (sendNow) {
15167                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15168                sendPackageChangedBroadcast(packageName,
15169                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15170            }
15171        } finally {
15172            Binder.restoreCallingIdentity(callingId);
15173        }
15174    }
15175
15176    private void sendPackageChangedBroadcast(String packageName,
15177            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15178        if (DEBUG_INSTALL)
15179            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15180                    + componentNames);
15181        Bundle extras = new Bundle(4);
15182        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15183        String nameList[] = new String[componentNames.size()];
15184        componentNames.toArray(nameList);
15185        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15186        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15187        extras.putInt(Intent.EXTRA_UID, packageUid);
15188        // If this is not reporting a change of the overall package, then only send it
15189        // to registered receivers.  We don't want to launch a swath of apps for every
15190        // little component state change.
15191        final int flags = !componentNames.contains(packageName)
15192                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15193        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15194                new int[] {UserHandle.getUserId(packageUid)});
15195    }
15196
15197    @Override
15198    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15199        if (!sUserManager.exists(userId)) return;
15200        final int uid = Binder.getCallingUid();
15201        final int permission = mContext.checkCallingOrSelfPermission(
15202                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15203        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15204        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15205        // writer
15206        synchronized (mPackages) {
15207            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15208                    allowedByPermission, uid, userId)) {
15209                scheduleWritePackageRestrictionsLocked(userId);
15210            }
15211        }
15212    }
15213
15214    @Override
15215    public String getInstallerPackageName(String packageName) {
15216        // reader
15217        synchronized (mPackages) {
15218            return mSettings.getInstallerPackageNameLPr(packageName);
15219        }
15220    }
15221
15222    @Override
15223    public int getApplicationEnabledSetting(String packageName, int userId) {
15224        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15225        int uid = Binder.getCallingUid();
15226        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15227        // reader
15228        synchronized (mPackages) {
15229            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15230        }
15231    }
15232
15233    @Override
15234    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15235        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15236        int uid = Binder.getCallingUid();
15237        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15238        // reader
15239        synchronized (mPackages) {
15240            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15241        }
15242    }
15243
15244    @Override
15245    public void enterSafeMode() {
15246        enforceSystemOrRoot("Only the system can request entering safe mode");
15247
15248        if (!mSystemReady) {
15249            mSafeMode = true;
15250        }
15251    }
15252
15253    @Override
15254    public void systemReady() {
15255        mSystemReady = true;
15256
15257        // Read the compatibilty setting when the system is ready.
15258        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15259                mContext.getContentResolver(),
15260                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15261        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15262        if (DEBUG_SETTINGS) {
15263            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15264        }
15265
15266        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15267
15268        synchronized (mPackages) {
15269            // Verify that all of the preferred activity components actually
15270            // exist.  It is possible for applications to be updated and at
15271            // that point remove a previously declared activity component that
15272            // had been set as a preferred activity.  We try to clean this up
15273            // the next time we encounter that preferred activity, but it is
15274            // possible for the user flow to never be able to return to that
15275            // situation so here we do a sanity check to make sure we haven't
15276            // left any junk around.
15277            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15278            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15279                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15280                removed.clear();
15281                for (PreferredActivity pa : pir.filterSet()) {
15282                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15283                        removed.add(pa);
15284                    }
15285                }
15286                if (removed.size() > 0) {
15287                    for (int r=0; r<removed.size(); r++) {
15288                        PreferredActivity pa = removed.get(r);
15289                        Slog.w(TAG, "Removing dangling preferred activity: "
15290                                + pa.mPref.mComponent);
15291                        pir.removeFilter(pa);
15292                    }
15293                    mSettings.writePackageRestrictionsLPr(
15294                            mSettings.mPreferredActivities.keyAt(i));
15295                }
15296            }
15297
15298            for (int userId : UserManagerService.getInstance().getUserIds()) {
15299                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15300                    grantPermissionsUserIds = ArrayUtils.appendInt(
15301                            grantPermissionsUserIds, userId);
15302                }
15303            }
15304        }
15305        sUserManager.systemReady();
15306
15307        // If we upgraded grant all default permissions before kicking off.
15308        for (int userId : grantPermissionsUserIds) {
15309            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15310        }
15311
15312        // Kick off any messages waiting for system ready
15313        if (mPostSystemReadyMessages != null) {
15314            for (Message msg : mPostSystemReadyMessages) {
15315                msg.sendToTarget();
15316            }
15317            mPostSystemReadyMessages = null;
15318        }
15319
15320        // Watch for external volumes that come and go over time
15321        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15322        storage.registerListener(mStorageListener);
15323
15324        mInstallerService.systemReady();
15325        mPackageDexOptimizer.systemReady();
15326
15327        MountServiceInternal mountServiceInternal = LocalServices.getService(
15328                MountServiceInternal.class);
15329        mountServiceInternal.addExternalStoragePolicy(
15330                new MountServiceInternal.ExternalStorageMountPolicy() {
15331            @Override
15332            public int getMountMode(int uid, String packageName) {
15333                if (Process.isIsolated(uid)) {
15334                    return Zygote.MOUNT_EXTERNAL_NONE;
15335                }
15336                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15337                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15338                }
15339                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15340                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15341                }
15342                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15343                    return Zygote.MOUNT_EXTERNAL_READ;
15344                }
15345                return Zygote.MOUNT_EXTERNAL_WRITE;
15346            }
15347
15348            @Override
15349            public boolean hasExternalStorage(int uid, String packageName) {
15350                return true;
15351            }
15352        });
15353    }
15354
15355    @Override
15356    public boolean isSafeMode() {
15357        return mSafeMode;
15358    }
15359
15360    @Override
15361    public boolean hasSystemUidErrors() {
15362        return mHasSystemUidErrors;
15363    }
15364
15365    static String arrayToString(int[] array) {
15366        StringBuffer buf = new StringBuffer(128);
15367        buf.append('[');
15368        if (array != null) {
15369            for (int i=0; i<array.length; i++) {
15370                if (i > 0) buf.append(", ");
15371                buf.append(array[i]);
15372            }
15373        }
15374        buf.append(']');
15375        return buf.toString();
15376    }
15377
15378    static class DumpState {
15379        public static final int DUMP_LIBS = 1 << 0;
15380        public static final int DUMP_FEATURES = 1 << 1;
15381        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15382        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15383        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15384        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15385        public static final int DUMP_PERMISSIONS = 1 << 6;
15386        public static final int DUMP_PACKAGES = 1 << 7;
15387        public static final int DUMP_SHARED_USERS = 1 << 8;
15388        public static final int DUMP_MESSAGES = 1 << 9;
15389        public static final int DUMP_PROVIDERS = 1 << 10;
15390        public static final int DUMP_VERIFIERS = 1 << 11;
15391        public static final int DUMP_PREFERRED = 1 << 12;
15392        public static final int DUMP_PREFERRED_XML = 1 << 13;
15393        public static final int DUMP_KEYSETS = 1 << 14;
15394        public static final int DUMP_VERSION = 1 << 15;
15395        public static final int DUMP_INSTALLS = 1 << 16;
15396        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15397        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15398
15399        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15400
15401        private int mTypes;
15402
15403        private int mOptions;
15404
15405        private boolean mTitlePrinted;
15406
15407        private SharedUserSetting mSharedUser;
15408
15409        public boolean isDumping(int type) {
15410            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15411                return true;
15412            }
15413
15414            return (mTypes & type) != 0;
15415        }
15416
15417        public void setDump(int type) {
15418            mTypes |= type;
15419        }
15420
15421        public boolean isOptionEnabled(int option) {
15422            return (mOptions & option) != 0;
15423        }
15424
15425        public void setOptionEnabled(int option) {
15426            mOptions |= option;
15427        }
15428
15429        public boolean onTitlePrinted() {
15430            final boolean printed = mTitlePrinted;
15431            mTitlePrinted = true;
15432            return printed;
15433        }
15434
15435        public boolean getTitlePrinted() {
15436            return mTitlePrinted;
15437        }
15438
15439        public void setTitlePrinted(boolean enabled) {
15440            mTitlePrinted = enabled;
15441        }
15442
15443        public SharedUserSetting getSharedUser() {
15444            return mSharedUser;
15445        }
15446
15447        public void setSharedUser(SharedUserSetting user) {
15448            mSharedUser = user;
15449        }
15450    }
15451
15452    @Override
15453    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15454            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15455        (new PackageManagerShellCommand(this)).exec(
15456                this, in, out, err, args, resultReceiver);
15457    }
15458
15459    @Override
15460    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15461        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15462                != PackageManager.PERMISSION_GRANTED) {
15463            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15464                    + Binder.getCallingPid()
15465                    + ", uid=" + Binder.getCallingUid()
15466                    + " without permission "
15467                    + android.Manifest.permission.DUMP);
15468            return;
15469        }
15470
15471        DumpState dumpState = new DumpState();
15472        boolean fullPreferred = false;
15473        boolean checkin = false;
15474
15475        String packageName = null;
15476        ArraySet<String> permissionNames = null;
15477
15478        int opti = 0;
15479        while (opti < args.length) {
15480            String opt = args[opti];
15481            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15482                break;
15483            }
15484            opti++;
15485
15486            if ("-a".equals(opt)) {
15487                // Right now we only know how to print all.
15488            } else if ("-h".equals(opt)) {
15489                pw.println("Package manager dump options:");
15490                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15491                pw.println("    --checkin: dump for a checkin");
15492                pw.println("    -f: print details of intent filters");
15493                pw.println("    -h: print this help");
15494                pw.println("  cmd may be one of:");
15495                pw.println("    l[ibraries]: list known shared libraries");
15496                pw.println("    f[eatures]: list device features");
15497                pw.println("    k[eysets]: print known keysets");
15498                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15499                pw.println("    perm[issions]: dump permissions");
15500                pw.println("    permission [name ...]: dump declaration and use of given permission");
15501                pw.println("    pref[erred]: print preferred package settings");
15502                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15503                pw.println("    prov[iders]: dump content providers");
15504                pw.println("    p[ackages]: dump installed packages");
15505                pw.println("    s[hared-users]: dump shared user IDs");
15506                pw.println("    m[essages]: print collected runtime messages");
15507                pw.println("    v[erifiers]: print package verifier info");
15508                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15509                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15510                pw.println("    version: print database version info");
15511                pw.println("    write: write current settings now");
15512                pw.println("    installs: details about install sessions");
15513                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15514                pw.println("    <package.name>: info about given package");
15515                return;
15516            } else if ("--checkin".equals(opt)) {
15517                checkin = true;
15518            } else if ("-f".equals(opt)) {
15519                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15520            } else {
15521                pw.println("Unknown argument: " + opt + "; use -h for help");
15522            }
15523        }
15524
15525        // Is the caller requesting to dump a particular piece of data?
15526        if (opti < args.length) {
15527            String cmd = args[opti];
15528            opti++;
15529            // Is this a package name?
15530            if ("android".equals(cmd) || cmd.contains(".")) {
15531                packageName = cmd;
15532                // When dumping a single package, we always dump all of its
15533                // filter information since the amount of data will be reasonable.
15534                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15535            } else if ("check-permission".equals(cmd)) {
15536                if (opti >= args.length) {
15537                    pw.println("Error: check-permission missing permission argument");
15538                    return;
15539                }
15540                String perm = args[opti];
15541                opti++;
15542                if (opti >= args.length) {
15543                    pw.println("Error: check-permission missing package argument");
15544                    return;
15545                }
15546                String pkg = args[opti];
15547                opti++;
15548                int user = UserHandle.getUserId(Binder.getCallingUid());
15549                if (opti < args.length) {
15550                    try {
15551                        user = Integer.parseInt(args[opti]);
15552                    } catch (NumberFormatException e) {
15553                        pw.println("Error: check-permission user argument is not a number: "
15554                                + args[opti]);
15555                        return;
15556                    }
15557                }
15558                pw.println(checkPermission(perm, pkg, user));
15559                return;
15560            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15561                dumpState.setDump(DumpState.DUMP_LIBS);
15562            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15563                dumpState.setDump(DumpState.DUMP_FEATURES);
15564            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15565                if (opti >= args.length) {
15566                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15567                            | DumpState.DUMP_SERVICE_RESOLVERS
15568                            | DumpState.DUMP_RECEIVER_RESOLVERS
15569                            | DumpState.DUMP_CONTENT_RESOLVERS);
15570                } else {
15571                    while (opti < args.length) {
15572                        String name = args[opti];
15573                        if ("a".equals(name) || "activity".equals(name)) {
15574                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15575                        } else if ("s".equals(name) || "service".equals(name)) {
15576                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15577                        } else if ("r".equals(name) || "receiver".equals(name)) {
15578                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15579                        } else if ("c".equals(name) || "content".equals(name)) {
15580                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15581                        } else {
15582                            pw.println("Error: unknown resolver table type: " + name);
15583                            return;
15584                        }
15585                        opti++;
15586                    }
15587                }
15588            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15589                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15590            } else if ("permission".equals(cmd)) {
15591                if (opti >= args.length) {
15592                    pw.println("Error: permission requires permission name");
15593                    return;
15594                }
15595                permissionNames = new ArraySet<>();
15596                while (opti < args.length) {
15597                    permissionNames.add(args[opti]);
15598                    opti++;
15599                }
15600                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15601                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15602            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15603                dumpState.setDump(DumpState.DUMP_PREFERRED);
15604            } else if ("preferred-xml".equals(cmd)) {
15605                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15606                if (opti < args.length && "--full".equals(args[opti])) {
15607                    fullPreferred = true;
15608                    opti++;
15609                }
15610            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15611                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15612            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15613                dumpState.setDump(DumpState.DUMP_PACKAGES);
15614            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15615                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15616            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15617                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15618            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15619                dumpState.setDump(DumpState.DUMP_MESSAGES);
15620            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15621                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15622            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15623                    || "intent-filter-verifiers".equals(cmd)) {
15624                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15625            } else if ("version".equals(cmd)) {
15626                dumpState.setDump(DumpState.DUMP_VERSION);
15627            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15628                dumpState.setDump(DumpState.DUMP_KEYSETS);
15629            } else if ("installs".equals(cmd)) {
15630                dumpState.setDump(DumpState.DUMP_INSTALLS);
15631            } else if ("write".equals(cmd)) {
15632                synchronized (mPackages) {
15633                    mSettings.writeLPr();
15634                    pw.println("Settings written.");
15635                    return;
15636                }
15637            }
15638        }
15639
15640        if (checkin) {
15641            pw.println("vers,1");
15642        }
15643
15644        // reader
15645        synchronized (mPackages) {
15646            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15647                if (!checkin) {
15648                    if (dumpState.onTitlePrinted())
15649                        pw.println();
15650                    pw.println("Database versions:");
15651                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15652                }
15653            }
15654
15655            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15656                if (!checkin) {
15657                    if (dumpState.onTitlePrinted())
15658                        pw.println();
15659                    pw.println("Verifiers:");
15660                    pw.print("  Required: ");
15661                    pw.print(mRequiredVerifierPackage);
15662                    pw.print(" (uid=");
15663                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15664                    pw.println(")");
15665                } else if (mRequiredVerifierPackage != null) {
15666                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15667                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15668                }
15669            }
15670
15671            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15672                    packageName == null) {
15673                if (mIntentFilterVerifierComponent != null) {
15674                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15675                    if (!checkin) {
15676                        if (dumpState.onTitlePrinted())
15677                            pw.println();
15678                        pw.println("Intent Filter Verifier:");
15679                        pw.print("  Using: ");
15680                        pw.print(verifierPackageName);
15681                        pw.print(" (uid=");
15682                        pw.print(getPackageUid(verifierPackageName, 0));
15683                        pw.println(")");
15684                    } else if (verifierPackageName != null) {
15685                        pw.print("ifv,"); pw.print(verifierPackageName);
15686                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15687                    }
15688                } else {
15689                    pw.println();
15690                    pw.println("No Intent Filter Verifier available!");
15691                }
15692            }
15693
15694            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15695                boolean printedHeader = false;
15696                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15697                while (it.hasNext()) {
15698                    String name = it.next();
15699                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15700                    if (!checkin) {
15701                        if (!printedHeader) {
15702                            if (dumpState.onTitlePrinted())
15703                                pw.println();
15704                            pw.println("Libraries:");
15705                            printedHeader = true;
15706                        }
15707                        pw.print("  ");
15708                    } else {
15709                        pw.print("lib,");
15710                    }
15711                    pw.print(name);
15712                    if (!checkin) {
15713                        pw.print(" -> ");
15714                    }
15715                    if (ent.path != null) {
15716                        if (!checkin) {
15717                            pw.print("(jar) ");
15718                            pw.print(ent.path);
15719                        } else {
15720                            pw.print(",jar,");
15721                            pw.print(ent.path);
15722                        }
15723                    } else {
15724                        if (!checkin) {
15725                            pw.print("(apk) ");
15726                            pw.print(ent.apk);
15727                        } else {
15728                            pw.print(",apk,");
15729                            pw.print(ent.apk);
15730                        }
15731                    }
15732                    pw.println();
15733                }
15734            }
15735
15736            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15737                if (dumpState.onTitlePrinted())
15738                    pw.println();
15739                if (!checkin) {
15740                    pw.println("Features:");
15741                }
15742                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15743                while (it.hasNext()) {
15744                    String name = it.next();
15745                    if (!checkin) {
15746                        pw.print("  ");
15747                    } else {
15748                        pw.print("feat,");
15749                    }
15750                    pw.println(name);
15751                }
15752            }
15753
15754            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15755                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15756                        : "Activity Resolver Table:", "  ", packageName,
15757                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15758                    dumpState.setTitlePrinted(true);
15759                }
15760            }
15761            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15762                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15763                        : "Receiver Resolver Table:", "  ", packageName,
15764                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15765                    dumpState.setTitlePrinted(true);
15766                }
15767            }
15768            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15769                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15770                        : "Service Resolver Table:", "  ", packageName,
15771                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15772                    dumpState.setTitlePrinted(true);
15773                }
15774            }
15775            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15776                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15777                        : "Provider Resolver Table:", "  ", packageName,
15778                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15779                    dumpState.setTitlePrinted(true);
15780                }
15781            }
15782
15783            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15784                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15785                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15786                    int user = mSettings.mPreferredActivities.keyAt(i);
15787                    if (pir.dump(pw,
15788                            dumpState.getTitlePrinted()
15789                                ? "\nPreferred Activities User " + user + ":"
15790                                : "Preferred Activities User " + user + ":", "  ",
15791                            packageName, true, false)) {
15792                        dumpState.setTitlePrinted(true);
15793                    }
15794                }
15795            }
15796
15797            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15798                pw.flush();
15799                FileOutputStream fout = new FileOutputStream(fd);
15800                BufferedOutputStream str = new BufferedOutputStream(fout);
15801                XmlSerializer serializer = new FastXmlSerializer();
15802                try {
15803                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15804                    serializer.startDocument(null, true);
15805                    serializer.setFeature(
15806                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15807                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15808                    serializer.endDocument();
15809                    serializer.flush();
15810                } catch (IllegalArgumentException e) {
15811                    pw.println("Failed writing: " + e);
15812                } catch (IllegalStateException e) {
15813                    pw.println("Failed writing: " + e);
15814                } catch (IOException e) {
15815                    pw.println("Failed writing: " + e);
15816                }
15817            }
15818
15819            if (!checkin
15820                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15821                    && packageName == null) {
15822                pw.println();
15823                int count = mSettings.mPackages.size();
15824                if (count == 0) {
15825                    pw.println("No applications!");
15826                    pw.println();
15827                } else {
15828                    final String prefix = "  ";
15829                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15830                    if (allPackageSettings.size() == 0) {
15831                        pw.println("No domain preferred apps!");
15832                        pw.println();
15833                    } else {
15834                        pw.println("App verification status:");
15835                        pw.println();
15836                        count = 0;
15837                        for (PackageSetting ps : allPackageSettings) {
15838                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15839                            if (ivi == null || ivi.getPackageName() == null) continue;
15840                            pw.println(prefix + "Package: " + ivi.getPackageName());
15841                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15842                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15843                            pw.println();
15844                            count++;
15845                        }
15846                        if (count == 0) {
15847                            pw.println(prefix + "No app verification established.");
15848                            pw.println();
15849                        }
15850                        for (int userId : sUserManager.getUserIds()) {
15851                            pw.println("App linkages for user " + userId + ":");
15852                            pw.println();
15853                            count = 0;
15854                            for (PackageSetting ps : allPackageSettings) {
15855                                final long status = ps.getDomainVerificationStatusForUser(userId);
15856                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15857                                    continue;
15858                                }
15859                                pw.println(prefix + "Package: " + ps.name);
15860                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15861                                String statusStr = IntentFilterVerificationInfo.
15862                                        getStatusStringFromValue(status);
15863                                pw.println(prefix + "Status:  " + statusStr);
15864                                pw.println();
15865                                count++;
15866                            }
15867                            if (count == 0) {
15868                                pw.println(prefix + "No configured app linkages.");
15869                                pw.println();
15870                            }
15871                        }
15872                    }
15873                }
15874            }
15875
15876            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15877                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15878                if (packageName == null && permissionNames == null) {
15879                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15880                        if (iperm == 0) {
15881                            if (dumpState.onTitlePrinted())
15882                                pw.println();
15883                            pw.println("AppOp Permissions:");
15884                        }
15885                        pw.print("  AppOp Permission ");
15886                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15887                        pw.println(":");
15888                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15889                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15890                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15891                        }
15892                    }
15893                }
15894            }
15895
15896            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15897                boolean printedSomething = false;
15898                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15899                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15900                        continue;
15901                    }
15902                    if (!printedSomething) {
15903                        if (dumpState.onTitlePrinted())
15904                            pw.println();
15905                        pw.println("Registered ContentProviders:");
15906                        printedSomething = true;
15907                    }
15908                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15909                    pw.print("    "); pw.println(p.toString());
15910                }
15911                printedSomething = false;
15912                for (Map.Entry<String, PackageParser.Provider> entry :
15913                        mProvidersByAuthority.entrySet()) {
15914                    PackageParser.Provider p = entry.getValue();
15915                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15916                        continue;
15917                    }
15918                    if (!printedSomething) {
15919                        if (dumpState.onTitlePrinted())
15920                            pw.println();
15921                        pw.println("ContentProvider Authorities:");
15922                        printedSomething = true;
15923                    }
15924                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15925                    pw.print("    "); pw.println(p.toString());
15926                    if (p.info != null && p.info.applicationInfo != null) {
15927                        final String appInfo = p.info.applicationInfo.toString();
15928                        pw.print("      applicationInfo="); pw.println(appInfo);
15929                    }
15930                }
15931            }
15932
15933            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15934                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15935            }
15936
15937            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15938                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15939            }
15940
15941            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15942                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15943            }
15944
15945            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15946                // XXX should handle packageName != null by dumping only install data that
15947                // the given package is involved with.
15948                if (dumpState.onTitlePrinted()) pw.println();
15949                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15950            }
15951
15952            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15953                if (dumpState.onTitlePrinted()) pw.println();
15954                mSettings.dumpReadMessagesLPr(pw, dumpState);
15955
15956                pw.println();
15957                pw.println("Package warning messages:");
15958                BufferedReader in = null;
15959                String line = null;
15960                try {
15961                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15962                    while ((line = in.readLine()) != null) {
15963                        if (line.contains("ignored: updated version")) continue;
15964                        pw.println(line);
15965                    }
15966                } catch (IOException ignored) {
15967                } finally {
15968                    IoUtils.closeQuietly(in);
15969                }
15970            }
15971
15972            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15973                BufferedReader in = null;
15974                String line = null;
15975                try {
15976                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15977                    while ((line = in.readLine()) != null) {
15978                        if (line.contains("ignored: updated version")) continue;
15979                        pw.print("msg,");
15980                        pw.println(line);
15981                    }
15982                } catch (IOException ignored) {
15983                } finally {
15984                    IoUtils.closeQuietly(in);
15985                }
15986            }
15987        }
15988    }
15989
15990    private String dumpDomainString(String packageName) {
15991        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15992        List<IntentFilter> filters = getAllIntentFilters(packageName);
15993
15994        ArraySet<String> result = new ArraySet<>();
15995        if (iviList.size() > 0) {
15996            for (IntentFilterVerificationInfo ivi : iviList) {
15997                for (String host : ivi.getDomains()) {
15998                    result.add(host);
15999                }
16000            }
16001        }
16002        if (filters != null && filters.size() > 0) {
16003            for (IntentFilter filter : filters) {
16004                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16005                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16006                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16007                    result.addAll(filter.getHostsList());
16008                }
16009            }
16010        }
16011
16012        StringBuilder sb = new StringBuilder(result.size() * 16);
16013        for (String domain : result) {
16014            if (sb.length() > 0) sb.append(" ");
16015            sb.append(domain);
16016        }
16017        return sb.toString();
16018    }
16019
16020    // ------- apps on sdcard specific code -------
16021    static final boolean DEBUG_SD_INSTALL = false;
16022
16023    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16024
16025    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16026
16027    private boolean mMediaMounted = false;
16028
16029    static String getEncryptKey() {
16030        try {
16031            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16032                    SD_ENCRYPTION_KEYSTORE_NAME);
16033            if (sdEncKey == null) {
16034                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16035                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16036                if (sdEncKey == null) {
16037                    Slog.e(TAG, "Failed to create encryption keys");
16038                    return null;
16039                }
16040            }
16041            return sdEncKey;
16042        } catch (NoSuchAlgorithmException nsae) {
16043            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16044            return null;
16045        } catch (IOException ioe) {
16046            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16047            return null;
16048        }
16049    }
16050
16051    /*
16052     * Update media status on PackageManager.
16053     */
16054    @Override
16055    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16056        int callingUid = Binder.getCallingUid();
16057        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16058            throw new SecurityException("Media status can only be updated by the system");
16059        }
16060        // reader; this apparently protects mMediaMounted, but should probably
16061        // be a different lock in that case.
16062        synchronized (mPackages) {
16063            Log.i(TAG, "Updating external media status from "
16064                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16065                    + (mediaStatus ? "mounted" : "unmounted"));
16066            if (DEBUG_SD_INSTALL)
16067                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16068                        + ", mMediaMounted=" + mMediaMounted);
16069            if (mediaStatus == mMediaMounted) {
16070                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16071                        : 0, -1);
16072                mHandler.sendMessage(msg);
16073                return;
16074            }
16075            mMediaMounted = mediaStatus;
16076        }
16077        // Queue up an async operation since the package installation may take a
16078        // little while.
16079        mHandler.post(new Runnable() {
16080            public void run() {
16081                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16082            }
16083        });
16084    }
16085
16086    /**
16087     * Called by MountService when the initial ASECs to scan are available.
16088     * Should block until all the ASEC containers are finished being scanned.
16089     */
16090    public void scanAvailableAsecs() {
16091        updateExternalMediaStatusInner(true, false, false);
16092        if (mShouldRestoreconData) {
16093            SELinuxMMAC.setRestoreconDone();
16094            mShouldRestoreconData = false;
16095        }
16096    }
16097
16098    /*
16099     * Collect information of applications on external media, map them against
16100     * existing containers and update information based on current mount status.
16101     * Please note that we always have to report status if reportStatus has been
16102     * set to true especially when unloading packages.
16103     */
16104    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16105            boolean externalStorage) {
16106        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16107        int[] uidArr = EmptyArray.INT;
16108
16109        final String[] list = PackageHelper.getSecureContainerList();
16110        if (ArrayUtils.isEmpty(list)) {
16111            Log.i(TAG, "No secure containers found");
16112        } else {
16113            // Process list of secure containers and categorize them
16114            // as active or stale based on their package internal state.
16115
16116            // reader
16117            synchronized (mPackages) {
16118                for (String cid : list) {
16119                    // Leave stages untouched for now; installer service owns them
16120                    if (PackageInstallerService.isStageName(cid)) continue;
16121
16122                    if (DEBUG_SD_INSTALL)
16123                        Log.i(TAG, "Processing container " + cid);
16124                    String pkgName = getAsecPackageName(cid);
16125                    if (pkgName == null) {
16126                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16127                        continue;
16128                    }
16129                    if (DEBUG_SD_INSTALL)
16130                        Log.i(TAG, "Looking for pkg : " + pkgName);
16131
16132                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16133                    if (ps == null) {
16134                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16135                        continue;
16136                    }
16137
16138                    /*
16139                     * Skip packages that are not external if we're unmounting
16140                     * external storage.
16141                     */
16142                    if (externalStorage && !isMounted && !isExternal(ps)) {
16143                        continue;
16144                    }
16145
16146                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16147                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16148                    // The package status is changed only if the code path
16149                    // matches between settings and the container id.
16150                    if (ps.codePathString != null
16151                            && ps.codePathString.startsWith(args.getCodePath())) {
16152                        if (DEBUG_SD_INSTALL) {
16153                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16154                                    + " at code path: " + ps.codePathString);
16155                        }
16156
16157                        // We do have a valid package installed on sdcard
16158                        processCids.put(args, ps.codePathString);
16159                        final int uid = ps.appId;
16160                        if (uid != -1) {
16161                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16162                        }
16163                    } else {
16164                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16165                                + ps.codePathString);
16166                    }
16167                }
16168            }
16169
16170            Arrays.sort(uidArr);
16171        }
16172
16173        // Process packages with valid entries.
16174        if (isMounted) {
16175            if (DEBUG_SD_INSTALL)
16176                Log.i(TAG, "Loading packages");
16177            loadMediaPackages(processCids, uidArr, externalStorage);
16178            startCleaningPackages();
16179            mInstallerService.onSecureContainersAvailable();
16180        } else {
16181            if (DEBUG_SD_INSTALL)
16182                Log.i(TAG, "Unloading packages");
16183            unloadMediaPackages(processCids, uidArr, reportStatus);
16184        }
16185    }
16186
16187    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16188            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16189        final int size = infos.size();
16190        final String[] packageNames = new String[size];
16191        final int[] packageUids = new int[size];
16192        for (int i = 0; i < size; i++) {
16193            final ApplicationInfo info = infos.get(i);
16194            packageNames[i] = info.packageName;
16195            packageUids[i] = info.uid;
16196        }
16197        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16198                finishedReceiver);
16199    }
16200
16201    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16202            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16203        sendResourcesChangedBroadcast(mediaStatus, replacing,
16204                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16205    }
16206
16207    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16208            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16209        int size = pkgList.length;
16210        if (size > 0) {
16211            // Send broadcasts here
16212            Bundle extras = new Bundle();
16213            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16214            if (uidArr != null) {
16215                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16216            }
16217            if (replacing) {
16218                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16219            }
16220            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16221                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16222            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16223        }
16224    }
16225
16226   /*
16227     * Look at potentially valid container ids from processCids If package
16228     * information doesn't match the one on record or package scanning fails,
16229     * the cid is added to list of removeCids. We currently don't delete stale
16230     * containers.
16231     */
16232    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16233            boolean externalStorage) {
16234        ArrayList<String> pkgList = new ArrayList<String>();
16235        Set<AsecInstallArgs> keys = processCids.keySet();
16236
16237        for (AsecInstallArgs args : keys) {
16238            String codePath = processCids.get(args);
16239            if (DEBUG_SD_INSTALL)
16240                Log.i(TAG, "Loading container : " + args.cid);
16241            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16242            try {
16243                // Make sure there are no container errors first.
16244                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16245                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16246                            + " when installing from sdcard");
16247                    continue;
16248                }
16249                // Check code path here.
16250                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16251                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16252                            + " does not match one in settings " + codePath);
16253                    continue;
16254                }
16255                // Parse package
16256                int parseFlags = mDefParseFlags;
16257                if (args.isExternalAsec()) {
16258                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16259                }
16260                if (args.isFwdLocked()) {
16261                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16262                }
16263
16264                synchronized (mInstallLock) {
16265                    PackageParser.Package pkg = null;
16266                    try {
16267                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16268                    } catch (PackageManagerException e) {
16269                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16270                    }
16271                    // Scan the package
16272                    if (pkg != null) {
16273                        /*
16274                         * TODO why is the lock being held? doPostInstall is
16275                         * called in other places without the lock. This needs
16276                         * to be straightened out.
16277                         */
16278                        // writer
16279                        synchronized (mPackages) {
16280                            retCode = PackageManager.INSTALL_SUCCEEDED;
16281                            pkgList.add(pkg.packageName);
16282                            // Post process args
16283                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16284                                    pkg.applicationInfo.uid);
16285                        }
16286                    } else {
16287                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16288                    }
16289                }
16290
16291            } finally {
16292                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16293                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16294                }
16295            }
16296        }
16297        // writer
16298        synchronized (mPackages) {
16299            // If the platform SDK has changed since the last time we booted,
16300            // we need to re-grant app permission to catch any new ones that
16301            // appear. This is really a hack, and means that apps can in some
16302            // cases get permissions that the user didn't initially explicitly
16303            // allow... it would be nice to have some better way to handle
16304            // this situation.
16305            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16306                    : mSettings.getInternalVersion();
16307            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16308                    : StorageManager.UUID_PRIVATE_INTERNAL;
16309
16310            int updateFlags = UPDATE_PERMISSIONS_ALL;
16311            if (ver.sdkVersion != mSdkVersion) {
16312                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16313                        + mSdkVersion + "; regranting permissions for external");
16314                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16315            }
16316            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16317
16318            // Yay, everything is now upgraded
16319            ver.forceCurrent();
16320
16321            // can downgrade to reader
16322            // Persist settings
16323            mSettings.writeLPr();
16324        }
16325        // Send a broadcast to let everyone know we are done processing
16326        if (pkgList.size() > 0) {
16327            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16328        }
16329    }
16330
16331   /*
16332     * Utility method to unload a list of specified containers
16333     */
16334    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16335        // Just unmount all valid containers.
16336        for (AsecInstallArgs arg : cidArgs) {
16337            synchronized (mInstallLock) {
16338                arg.doPostDeleteLI(false);
16339           }
16340       }
16341   }
16342
16343    /*
16344     * Unload packages mounted on external media. This involves deleting package
16345     * data from internal structures, sending broadcasts about diabled packages,
16346     * gc'ing to free up references, unmounting all secure containers
16347     * corresponding to packages on external media, and posting a
16348     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16349     * that we always have to post this message if status has been requested no
16350     * matter what.
16351     */
16352    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16353            final boolean reportStatus) {
16354        if (DEBUG_SD_INSTALL)
16355            Log.i(TAG, "unloading media packages");
16356        ArrayList<String> pkgList = new ArrayList<String>();
16357        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16358        final Set<AsecInstallArgs> keys = processCids.keySet();
16359        for (AsecInstallArgs args : keys) {
16360            String pkgName = args.getPackageName();
16361            if (DEBUG_SD_INSTALL)
16362                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16363            // Delete package internally
16364            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16365            synchronized (mInstallLock) {
16366                boolean res = deletePackageLI(pkgName, null, false, null, null,
16367                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16368                if (res) {
16369                    pkgList.add(pkgName);
16370                } else {
16371                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16372                    failedList.add(args);
16373                }
16374            }
16375        }
16376
16377        // reader
16378        synchronized (mPackages) {
16379            // We didn't update the settings after removing each package;
16380            // write them now for all packages.
16381            mSettings.writeLPr();
16382        }
16383
16384        // We have to absolutely send UPDATED_MEDIA_STATUS only
16385        // after confirming that all the receivers processed the ordered
16386        // broadcast when packages get disabled, force a gc to clean things up.
16387        // and unload all the containers.
16388        if (pkgList.size() > 0) {
16389            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16390                    new IIntentReceiver.Stub() {
16391                public void performReceive(Intent intent, int resultCode, String data,
16392                        Bundle extras, boolean ordered, boolean sticky,
16393                        int sendingUser) throws RemoteException {
16394                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16395                            reportStatus ? 1 : 0, 1, keys);
16396                    mHandler.sendMessage(msg);
16397                }
16398            });
16399        } else {
16400            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16401                    keys);
16402            mHandler.sendMessage(msg);
16403        }
16404    }
16405
16406    private void loadPrivatePackages(final VolumeInfo vol) {
16407        mHandler.post(new Runnable() {
16408            @Override
16409            public void run() {
16410                loadPrivatePackagesInner(vol);
16411            }
16412        });
16413    }
16414
16415    private void loadPrivatePackagesInner(VolumeInfo vol) {
16416        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16417        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16418
16419        final VersionInfo ver;
16420        final List<PackageSetting> packages;
16421        synchronized (mPackages) {
16422            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16423            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16424        }
16425
16426        for (PackageSetting ps : packages) {
16427            synchronized (mInstallLock) {
16428                final PackageParser.Package pkg;
16429                try {
16430                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16431                    loaded.add(pkg.applicationInfo);
16432                } catch (PackageManagerException e) {
16433                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16434                }
16435
16436                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16437                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16438                }
16439            }
16440        }
16441
16442        synchronized (mPackages) {
16443            int updateFlags = UPDATE_PERMISSIONS_ALL;
16444            if (ver.sdkVersion != mSdkVersion) {
16445                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16446                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16447                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16448            }
16449            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16450
16451            // Yay, everything is now upgraded
16452            ver.forceCurrent();
16453
16454            mSettings.writeLPr();
16455        }
16456
16457        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16458        sendResourcesChangedBroadcast(true, false, loaded, null);
16459    }
16460
16461    private void unloadPrivatePackages(final VolumeInfo vol) {
16462        mHandler.post(new Runnable() {
16463            @Override
16464            public void run() {
16465                unloadPrivatePackagesInner(vol);
16466            }
16467        });
16468    }
16469
16470    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16471        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16472        synchronized (mInstallLock) {
16473        synchronized (mPackages) {
16474            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16475            for (PackageSetting ps : packages) {
16476                if (ps.pkg == null) continue;
16477
16478                final ApplicationInfo info = ps.pkg.applicationInfo;
16479                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16480                if (deletePackageLI(ps.name, null, false, null, null,
16481                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16482                    unloaded.add(info);
16483                } else {
16484                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16485                }
16486            }
16487
16488            mSettings.writeLPr();
16489        }
16490        }
16491
16492        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16493        sendResourcesChangedBroadcast(false, false, unloaded, null);
16494    }
16495
16496    /**
16497     * Examine all users present on given mounted volume, and destroy data
16498     * belonging to users that are no longer valid, or whose user ID has been
16499     * recycled.
16500     */
16501    private void reconcileUsers(String volumeUuid) {
16502        final File[] files = FileUtils
16503                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16504        for (File file : files) {
16505            if (!file.isDirectory()) continue;
16506
16507            final int userId;
16508            final UserInfo info;
16509            try {
16510                userId = Integer.parseInt(file.getName());
16511                info = sUserManager.getUserInfo(userId);
16512            } catch (NumberFormatException e) {
16513                Slog.w(TAG, "Invalid user directory " + file);
16514                continue;
16515            }
16516
16517            boolean destroyUser = false;
16518            if (info == null) {
16519                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16520                        + " because no matching user was found");
16521                destroyUser = true;
16522            } else {
16523                try {
16524                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16525                } catch (IOException e) {
16526                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16527                            + " because we failed to enforce serial number: " + e);
16528                    destroyUser = true;
16529                }
16530            }
16531
16532            if (destroyUser) {
16533                synchronized (mInstallLock) {
16534                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16535                }
16536            }
16537        }
16538
16539        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16540        final UserManager um = mContext.getSystemService(UserManager.class);
16541        for (UserInfo user : um.getUsers()) {
16542            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16543            if (userDir.exists()) continue;
16544
16545            try {
16546                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16547                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16548            } catch (IOException e) {
16549                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16550            }
16551        }
16552    }
16553
16554    /**
16555     * Examine all apps present on given mounted volume, and destroy apps that
16556     * aren't expected, either due to uninstallation or reinstallation on
16557     * another volume.
16558     */
16559    private void reconcileApps(String volumeUuid) {
16560        final File[] files = FileUtils
16561                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16562        for (File file : files) {
16563            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16564                    && !PackageInstallerService.isStageName(file.getName());
16565            if (!isPackage) {
16566                // Ignore entries which are not packages
16567                continue;
16568            }
16569
16570            boolean destroyApp = false;
16571            String packageName = null;
16572            try {
16573                final PackageLite pkg = PackageParser.parsePackageLite(file,
16574                        PackageParser.PARSE_MUST_BE_APK);
16575                packageName = pkg.packageName;
16576
16577                synchronized (mPackages) {
16578                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16579                    if (ps == null) {
16580                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16581                                + volumeUuid + " because we found no install record");
16582                        destroyApp = true;
16583                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16584                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16585                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16586                        destroyApp = true;
16587                    }
16588                }
16589
16590            } catch (PackageParserException e) {
16591                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16592                destroyApp = true;
16593            }
16594
16595            if (destroyApp) {
16596                synchronized (mInstallLock) {
16597                    if (packageName != null) {
16598                        removeDataDirsLI(volumeUuid, packageName);
16599                    }
16600                    if (file.isDirectory()) {
16601                        mInstaller.rmPackageDir(file.getAbsolutePath());
16602                    } else {
16603                        file.delete();
16604                    }
16605                }
16606            }
16607        }
16608    }
16609
16610    private void unfreezePackage(String packageName) {
16611        synchronized (mPackages) {
16612            final PackageSetting ps = mSettings.mPackages.get(packageName);
16613            if (ps != null) {
16614                ps.frozen = false;
16615            }
16616        }
16617    }
16618
16619    @Override
16620    public int movePackage(final String packageName, final String volumeUuid) {
16621        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16622
16623        final int moveId = mNextMoveId.getAndIncrement();
16624        mHandler.post(new Runnable() {
16625            @Override
16626            public void run() {
16627                try {
16628                    movePackageInternal(packageName, volumeUuid, moveId);
16629                } catch (PackageManagerException e) {
16630                    Slog.w(TAG, "Failed to move " + packageName, e);
16631                    mMoveCallbacks.notifyStatusChanged(moveId,
16632                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16633                }
16634            }
16635        });
16636        return moveId;
16637    }
16638
16639    private void movePackageInternal(final String packageName, final String volumeUuid,
16640            final int moveId) throws PackageManagerException {
16641        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16642        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16643        final PackageManager pm = mContext.getPackageManager();
16644
16645        final boolean currentAsec;
16646        final String currentVolumeUuid;
16647        final File codeFile;
16648        final String installerPackageName;
16649        final String packageAbiOverride;
16650        final int appId;
16651        final String seinfo;
16652        final String label;
16653
16654        // reader
16655        synchronized (mPackages) {
16656            final PackageParser.Package pkg = mPackages.get(packageName);
16657            final PackageSetting ps = mSettings.mPackages.get(packageName);
16658            if (pkg == null || ps == null) {
16659                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16660            }
16661
16662            if (pkg.applicationInfo.isSystemApp()) {
16663                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16664                        "Cannot move system application");
16665            }
16666
16667            if (pkg.applicationInfo.isExternalAsec()) {
16668                currentAsec = true;
16669                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16670            } else if (pkg.applicationInfo.isForwardLocked()) {
16671                currentAsec = true;
16672                currentVolumeUuid = "forward_locked";
16673            } else {
16674                currentAsec = false;
16675                currentVolumeUuid = ps.volumeUuid;
16676
16677                final File probe = new File(pkg.codePath);
16678                final File probeOat = new File(probe, "oat");
16679                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16680                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16681                            "Move only supported for modern cluster style installs");
16682                }
16683            }
16684
16685            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16686                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16687                        "Package already moved to " + volumeUuid);
16688            }
16689
16690            if (ps.frozen) {
16691                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16692                        "Failed to move already frozen package");
16693            }
16694            ps.frozen = true;
16695
16696            codeFile = new File(pkg.codePath);
16697            installerPackageName = ps.installerPackageName;
16698            packageAbiOverride = ps.cpuAbiOverrideString;
16699            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16700            seinfo = pkg.applicationInfo.seinfo;
16701            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16702        }
16703
16704        // Now that we're guarded by frozen state, kill app during move
16705        final long token = Binder.clearCallingIdentity();
16706        try {
16707            killApplication(packageName, appId, "move pkg");
16708        } finally {
16709            Binder.restoreCallingIdentity(token);
16710        }
16711
16712        final Bundle extras = new Bundle();
16713        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16714        extras.putString(Intent.EXTRA_TITLE, label);
16715        mMoveCallbacks.notifyCreated(moveId, extras);
16716
16717        int installFlags;
16718        final boolean moveCompleteApp;
16719        final File measurePath;
16720
16721        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16722            installFlags = INSTALL_INTERNAL;
16723            moveCompleteApp = !currentAsec;
16724            measurePath = Environment.getDataAppDirectory(volumeUuid);
16725        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16726            installFlags = INSTALL_EXTERNAL;
16727            moveCompleteApp = false;
16728            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16729        } else {
16730            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16731            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16732                    || !volume.isMountedWritable()) {
16733                unfreezePackage(packageName);
16734                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16735                        "Move location not mounted private volume");
16736            }
16737
16738            Preconditions.checkState(!currentAsec);
16739
16740            installFlags = INSTALL_INTERNAL;
16741            moveCompleteApp = true;
16742            measurePath = Environment.getDataAppDirectory(volumeUuid);
16743        }
16744
16745        final PackageStats stats = new PackageStats(null, -1);
16746        synchronized (mInstaller) {
16747            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16748                unfreezePackage(packageName);
16749                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16750                        "Failed to measure package size");
16751            }
16752        }
16753
16754        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16755                + stats.dataSize);
16756
16757        final long startFreeBytes = measurePath.getFreeSpace();
16758        final long sizeBytes;
16759        if (moveCompleteApp) {
16760            sizeBytes = stats.codeSize + stats.dataSize;
16761        } else {
16762            sizeBytes = stats.codeSize;
16763        }
16764
16765        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16766            unfreezePackage(packageName);
16767            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16768                    "Not enough free space to move");
16769        }
16770
16771        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16772
16773        final CountDownLatch installedLatch = new CountDownLatch(1);
16774        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16775            @Override
16776            public void onUserActionRequired(Intent intent) throws RemoteException {
16777                throw new IllegalStateException();
16778            }
16779
16780            @Override
16781            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16782                    Bundle extras) throws RemoteException {
16783                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16784                        + PackageManager.installStatusToString(returnCode, msg));
16785
16786                installedLatch.countDown();
16787
16788                // Regardless of success or failure of the move operation,
16789                // always unfreeze the package
16790                unfreezePackage(packageName);
16791
16792                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16793                switch (status) {
16794                    case PackageInstaller.STATUS_SUCCESS:
16795                        mMoveCallbacks.notifyStatusChanged(moveId,
16796                                PackageManager.MOVE_SUCCEEDED);
16797                        break;
16798                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16799                        mMoveCallbacks.notifyStatusChanged(moveId,
16800                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16801                        break;
16802                    default:
16803                        mMoveCallbacks.notifyStatusChanged(moveId,
16804                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16805                        break;
16806                }
16807            }
16808        };
16809
16810        final MoveInfo move;
16811        if (moveCompleteApp) {
16812            // Kick off a thread to report progress estimates
16813            new Thread() {
16814                @Override
16815                public void run() {
16816                    while (true) {
16817                        try {
16818                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16819                                break;
16820                            }
16821                        } catch (InterruptedException ignored) {
16822                        }
16823
16824                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16825                        final int progress = 10 + (int) MathUtils.constrain(
16826                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16827                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16828                    }
16829                }
16830            }.start();
16831
16832            final String dataAppName = codeFile.getName();
16833            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16834                    dataAppName, appId, seinfo);
16835        } else {
16836            move = null;
16837        }
16838
16839        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16840
16841        final Message msg = mHandler.obtainMessage(INIT_COPY);
16842        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16843        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16844                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16845        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16846        msg.obj = params;
16847
16848        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16849                System.identityHashCode(msg.obj));
16850        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16851                System.identityHashCode(msg.obj));
16852
16853        mHandler.sendMessage(msg);
16854    }
16855
16856    @Override
16857    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16858        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16859
16860        final int realMoveId = mNextMoveId.getAndIncrement();
16861        final Bundle extras = new Bundle();
16862        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16863        mMoveCallbacks.notifyCreated(realMoveId, extras);
16864
16865        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16866            @Override
16867            public void onCreated(int moveId, Bundle extras) {
16868                // Ignored
16869            }
16870
16871            @Override
16872            public void onStatusChanged(int moveId, int status, long estMillis) {
16873                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16874            }
16875        };
16876
16877        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16878        storage.setPrimaryStorageUuid(volumeUuid, callback);
16879        return realMoveId;
16880    }
16881
16882    @Override
16883    public int getMoveStatus(int moveId) {
16884        mContext.enforceCallingOrSelfPermission(
16885                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16886        return mMoveCallbacks.mLastStatus.get(moveId);
16887    }
16888
16889    @Override
16890    public void registerMoveCallback(IPackageMoveObserver callback) {
16891        mContext.enforceCallingOrSelfPermission(
16892                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16893        mMoveCallbacks.register(callback);
16894    }
16895
16896    @Override
16897    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16898        mContext.enforceCallingOrSelfPermission(
16899                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16900        mMoveCallbacks.unregister(callback);
16901    }
16902
16903    @Override
16904    public boolean setInstallLocation(int loc) {
16905        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16906                null);
16907        if (getInstallLocation() == loc) {
16908            return true;
16909        }
16910        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16911                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16912            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16913                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16914            return true;
16915        }
16916        return false;
16917   }
16918
16919    @Override
16920    public int getInstallLocation() {
16921        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16922                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16923                PackageHelper.APP_INSTALL_AUTO);
16924    }
16925
16926    /** Called by UserManagerService */
16927    void cleanUpUser(UserManagerService userManager, int userHandle) {
16928        synchronized (mPackages) {
16929            mDirtyUsers.remove(userHandle);
16930            mUserNeedsBadging.delete(userHandle);
16931            mSettings.removeUserLPw(userHandle);
16932            mPendingBroadcasts.remove(userHandle);
16933            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16934        }
16935        synchronized (mInstallLock) {
16936            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16937            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16938                final String volumeUuid = vol.getFsUuid();
16939                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16940                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16941            }
16942            synchronized (mPackages) {
16943                removeUnusedPackagesLILPw(userManager, userHandle);
16944            }
16945        }
16946    }
16947
16948    /**
16949     * We're removing userHandle and would like to remove any downloaded packages
16950     * that are no longer in use by any other user.
16951     * @param userHandle the user being removed
16952     */
16953    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16954        final boolean DEBUG_CLEAN_APKS = false;
16955        int [] users = userManager.getUserIds();
16956        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16957        while (psit.hasNext()) {
16958            PackageSetting ps = psit.next();
16959            if (ps.pkg == null) {
16960                continue;
16961            }
16962            final String packageName = ps.pkg.packageName;
16963            // Skip over if system app
16964            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16965                continue;
16966            }
16967            if (DEBUG_CLEAN_APKS) {
16968                Slog.i(TAG, "Checking package " + packageName);
16969            }
16970            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16971            if (keep) {
16972                if (DEBUG_CLEAN_APKS) {
16973                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16974                }
16975            } else {
16976                for (int i = 0; i < users.length; i++) {
16977                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16978                        keep = true;
16979                        if (DEBUG_CLEAN_APKS) {
16980                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
16981                                    + users[i]);
16982                        }
16983                        break;
16984                    }
16985                }
16986            }
16987            if (!keep) {
16988                if (DEBUG_CLEAN_APKS) {
16989                    Slog.i(TAG, "  Removing package " + packageName);
16990                }
16991                mHandler.post(new Runnable() {
16992                    public void run() {
16993                        deletePackageX(packageName, userHandle, 0);
16994                    } //end run
16995                });
16996            }
16997        }
16998    }
16999
17000    /** Called by UserManagerService */
17001    void createNewUser(int userHandle) {
17002        synchronized (mInstallLock) {
17003            mInstaller.createUserConfig(userHandle);
17004            mSettings.createNewUserLI(this, mInstaller, userHandle);
17005        }
17006        synchronized (mPackages) {
17007            applyFactoryDefaultBrowserLPw(userHandle);
17008            primeDomainVerificationsLPw(userHandle);
17009        }
17010    }
17011
17012    void newUserCreated(final int userHandle) {
17013        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17014        // If permission review for legacy apps is required, we represent
17015        // dagerous permissions for such apps as always granted runtime
17016        // permissions to keep per user flag state whether review is needed.
17017        // Hence, if a new user is added we have to propagate dangerous
17018        // permission grants for these legacy apps.
17019        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17020            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17021                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17022        }
17023    }
17024
17025    @Override
17026    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17027        mContext.enforceCallingOrSelfPermission(
17028                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17029                "Only package verification agents can read the verifier device identity");
17030
17031        synchronized (mPackages) {
17032            return mSettings.getVerifierDeviceIdentityLPw();
17033        }
17034    }
17035
17036    @Override
17037    public void setPermissionEnforced(String permission, boolean enforced) {
17038        // TODO: Now that we no longer change GID for storage, this should to away.
17039        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17040                "setPermissionEnforced");
17041        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17042            synchronized (mPackages) {
17043                if (mSettings.mReadExternalStorageEnforced == null
17044                        || mSettings.mReadExternalStorageEnforced != enforced) {
17045                    mSettings.mReadExternalStorageEnforced = enforced;
17046                    mSettings.writeLPr();
17047                }
17048            }
17049            // kill any non-foreground processes so we restart them and
17050            // grant/revoke the GID.
17051            final IActivityManager am = ActivityManagerNative.getDefault();
17052            if (am != null) {
17053                final long token = Binder.clearCallingIdentity();
17054                try {
17055                    am.killProcessesBelowForeground("setPermissionEnforcement");
17056                } catch (RemoteException e) {
17057                } finally {
17058                    Binder.restoreCallingIdentity(token);
17059                }
17060            }
17061        } else {
17062            throw new IllegalArgumentException("No selective enforcement for " + permission);
17063        }
17064    }
17065
17066    @Override
17067    @Deprecated
17068    public boolean isPermissionEnforced(String permission) {
17069        return true;
17070    }
17071
17072    @Override
17073    public boolean isStorageLow() {
17074        final long token = Binder.clearCallingIdentity();
17075        try {
17076            final DeviceStorageMonitorInternal
17077                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17078            if (dsm != null) {
17079                return dsm.isMemoryLow();
17080            } else {
17081                return false;
17082            }
17083        } finally {
17084            Binder.restoreCallingIdentity(token);
17085        }
17086    }
17087
17088    @Override
17089    public IPackageInstaller getPackageInstaller() {
17090        return mInstallerService;
17091    }
17092
17093    private boolean userNeedsBadging(int userId) {
17094        int index = mUserNeedsBadging.indexOfKey(userId);
17095        if (index < 0) {
17096            final UserInfo userInfo;
17097            final long token = Binder.clearCallingIdentity();
17098            try {
17099                userInfo = sUserManager.getUserInfo(userId);
17100            } finally {
17101                Binder.restoreCallingIdentity(token);
17102            }
17103            final boolean b;
17104            if (userInfo != null && userInfo.isManagedProfile()) {
17105                b = true;
17106            } else {
17107                b = false;
17108            }
17109            mUserNeedsBadging.put(userId, b);
17110            return b;
17111        }
17112        return mUserNeedsBadging.valueAt(index);
17113    }
17114
17115    @Override
17116    public KeySet getKeySetByAlias(String packageName, String alias) {
17117        if (packageName == null || alias == null) {
17118            return null;
17119        }
17120        synchronized(mPackages) {
17121            final PackageParser.Package pkg = mPackages.get(packageName);
17122            if (pkg == null) {
17123                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17124                throw new IllegalArgumentException("Unknown package: " + packageName);
17125            }
17126            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17127            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17128        }
17129    }
17130
17131    @Override
17132    public KeySet getSigningKeySet(String packageName) {
17133        if (packageName == null) {
17134            return null;
17135        }
17136        synchronized(mPackages) {
17137            final PackageParser.Package pkg = mPackages.get(packageName);
17138            if (pkg == null) {
17139                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17140                throw new IllegalArgumentException("Unknown package: " + packageName);
17141            }
17142            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17143                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17144                throw new SecurityException("May not access signing KeySet of other apps.");
17145            }
17146            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17147            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17148        }
17149    }
17150
17151    @Override
17152    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17153        if (packageName == null || ks == null) {
17154            return false;
17155        }
17156        synchronized(mPackages) {
17157            final PackageParser.Package pkg = mPackages.get(packageName);
17158            if (pkg == null) {
17159                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17160                throw new IllegalArgumentException("Unknown package: " + packageName);
17161            }
17162            IBinder ksh = ks.getToken();
17163            if (ksh instanceof KeySetHandle) {
17164                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17165                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17166            }
17167            return false;
17168        }
17169    }
17170
17171    @Override
17172    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17173        if (packageName == null || ks == null) {
17174            return false;
17175        }
17176        synchronized(mPackages) {
17177            final PackageParser.Package pkg = mPackages.get(packageName);
17178            if (pkg == null) {
17179                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17180                throw new IllegalArgumentException("Unknown package: " + packageName);
17181            }
17182            IBinder ksh = ks.getToken();
17183            if (ksh instanceof KeySetHandle) {
17184                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17185                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17186            }
17187            return false;
17188        }
17189    }
17190
17191    private void deletePackageIfUnusedLPr(final String packageName) {
17192        PackageSetting ps = mSettings.mPackages.get(packageName);
17193        if (ps == null) {
17194            return;
17195        }
17196        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17197            // TODO Implement atomic delete if package is unused
17198            // It is currently possible that the package will be deleted even if it is installed
17199            // after this method returns.
17200            mHandler.post(new Runnable() {
17201                public void run() {
17202                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17203                }
17204            });
17205        }
17206    }
17207
17208    /**
17209     * Check and throw if the given before/after packages would be considered a
17210     * downgrade.
17211     */
17212    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17213            throws PackageManagerException {
17214        if (after.versionCode < before.mVersionCode) {
17215            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17216                    "Update version code " + after.versionCode + " is older than current "
17217                    + before.mVersionCode);
17218        } else if (after.versionCode == before.mVersionCode) {
17219            if (after.baseRevisionCode < before.baseRevisionCode) {
17220                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17221                        "Update base revision code " + after.baseRevisionCode
17222                        + " is older than current " + before.baseRevisionCode);
17223            }
17224
17225            if (!ArrayUtils.isEmpty(after.splitNames)) {
17226                for (int i = 0; i < after.splitNames.length; i++) {
17227                    final String splitName = after.splitNames[i];
17228                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17229                    if (j != -1) {
17230                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17231                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17232                                    "Update split " + splitName + " revision code "
17233                                    + after.splitRevisionCodes[i] + " is older than current "
17234                                    + before.splitRevisionCodes[j]);
17235                        }
17236                    }
17237                }
17238            }
17239        }
17240    }
17241
17242    private static class MoveCallbacks extends Handler {
17243        private static final int MSG_CREATED = 1;
17244        private static final int MSG_STATUS_CHANGED = 2;
17245
17246        private final RemoteCallbackList<IPackageMoveObserver>
17247                mCallbacks = new RemoteCallbackList<>();
17248
17249        private final SparseIntArray mLastStatus = new SparseIntArray();
17250
17251        public MoveCallbacks(Looper looper) {
17252            super(looper);
17253        }
17254
17255        public void register(IPackageMoveObserver callback) {
17256            mCallbacks.register(callback);
17257        }
17258
17259        public void unregister(IPackageMoveObserver callback) {
17260            mCallbacks.unregister(callback);
17261        }
17262
17263        @Override
17264        public void handleMessage(Message msg) {
17265            final SomeArgs args = (SomeArgs) msg.obj;
17266            final int n = mCallbacks.beginBroadcast();
17267            for (int i = 0; i < n; i++) {
17268                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17269                try {
17270                    invokeCallback(callback, msg.what, args);
17271                } catch (RemoteException ignored) {
17272                }
17273            }
17274            mCallbacks.finishBroadcast();
17275            args.recycle();
17276        }
17277
17278        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17279                throws RemoteException {
17280            switch (what) {
17281                case MSG_CREATED: {
17282                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17283                    break;
17284                }
17285                case MSG_STATUS_CHANGED: {
17286                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17287                    break;
17288                }
17289            }
17290        }
17291
17292        private void notifyCreated(int moveId, Bundle extras) {
17293            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17294
17295            final SomeArgs args = SomeArgs.obtain();
17296            args.argi1 = moveId;
17297            args.arg2 = extras;
17298            obtainMessage(MSG_CREATED, args).sendToTarget();
17299        }
17300
17301        private void notifyStatusChanged(int moveId, int status) {
17302            notifyStatusChanged(moveId, status, -1);
17303        }
17304
17305        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17306            Slog.v(TAG, "Move " + moveId + " status " + status);
17307
17308            final SomeArgs args = SomeArgs.obtain();
17309            args.argi1 = moveId;
17310            args.argi2 = status;
17311            args.arg3 = estMillis;
17312            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17313
17314            synchronized (mLastStatus) {
17315                mLastStatus.put(moveId, status);
17316            }
17317        }
17318    }
17319
17320    private final class OnPermissionChangeListeners extends Handler {
17321        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17322
17323        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17324                new RemoteCallbackList<>();
17325
17326        public OnPermissionChangeListeners(Looper looper) {
17327            super(looper);
17328        }
17329
17330        @Override
17331        public void handleMessage(Message msg) {
17332            switch (msg.what) {
17333                case MSG_ON_PERMISSIONS_CHANGED: {
17334                    final int uid = msg.arg1;
17335                    handleOnPermissionsChanged(uid);
17336                } break;
17337            }
17338        }
17339
17340        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17341            mPermissionListeners.register(listener);
17342
17343        }
17344
17345        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17346            mPermissionListeners.unregister(listener);
17347        }
17348
17349        public void onPermissionsChanged(int uid) {
17350            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17351                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17352            }
17353        }
17354
17355        private void handleOnPermissionsChanged(int uid) {
17356            final int count = mPermissionListeners.beginBroadcast();
17357            try {
17358                for (int i = 0; i < count; i++) {
17359                    IOnPermissionsChangeListener callback = mPermissionListeners
17360                            .getBroadcastItem(i);
17361                    try {
17362                        callback.onPermissionsChanged(uid);
17363                    } catch (RemoteException e) {
17364                        Log.e(TAG, "Permission listener is dead", e);
17365                    }
17366                }
17367            } finally {
17368                mPermissionListeners.finishBroadcast();
17369            }
17370        }
17371    }
17372
17373    private class PackageManagerInternalImpl extends PackageManagerInternal {
17374        @Override
17375        public void setLocationPackagesProvider(PackagesProvider provider) {
17376            synchronized (mPackages) {
17377                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17378            }
17379        }
17380
17381        @Override
17382        public void setImePackagesProvider(PackagesProvider provider) {
17383            synchronized (mPackages) {
17384                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17385            }
17386        }
17387
17388        @Override
17389        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17390            synchronized (mPackages) {
17391                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17392            }
17393        }
17394
17395        @Override
17396        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17397            synchronized (mPackages) {
17398                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17399            }
17400        }
17401
17402        @Override
17403        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17404            synchronized (mPackages) {
17405                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17406            }
17407        }
17408
17409        @Override
17410        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17411            synchronized (mPackages) {
17412                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17413            }
17414        }
17415
17416        @Override
17417        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17418            synchronized (mPackages) {
17419                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17420            }
17421        }
17422
17423        @Override
17424        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17425            synchronized (mPackages) {
17426                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17427                        packageName, userId);
17428            }
17429        }
17430
17431        @Override
17432        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17433            synchronized (mPackages) {
17434                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17435                        packageName, userId);
17436            }
17437        }
17438
17439        @Override
17440        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17441            synchronized (mPackages) {
17442                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17443                        packageName, userId);
17444            }
17445        }
17446
17447        @Override
17448        public void setKeepUninstalledPackages(final List<String> packageList) {
17449            Preconditions.checkNotNull(packageList);
17450            List<String> removedFromList = null;
17451            synchronized (mPackages) {
17452                if (mKeepUninstalledPackages != null) {
17453                    final int packagesCount = mKeepUninstalledPackages.size();
17454                    for (int i = 0; i < packagesCount; i++) {
17455                        String oldPackage = mKeepUninstalledPackages.get(i);
17456                        if (packageList != null && packageList.contains(oldPackage)) {
17457                            continue;
17458                        }
17459                        if (removedFromList == null) {
17460                            removedFromList = new ArrayList<>();
17461                        }
17462                        removedFromList.add(oldPackage);
17463                    }
17464                }
17465                mKeepUninstalledPackages = new ArrayList<>(packageList);
17466                if (removedFromList != null) {
17467                    final int removedCount = removedFromList.size();
17468                    for (int i = 0; i < removedCount; i++) {
17469                        deletePackageIfUnusedLPr(removedFromList.get(i));
17470                    }
17471                }
17472            }
17473        }
17474
17475        @Override
17476        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17477            synchronized (mPackages) {
17478                // If we do not support permission review, done.
17479                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17480                    return false;
17481                }
17482
17483                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17484                if (packageSetting == null) {
17485                    return false;
17486                }
17487
17488                // Permission review applies only to apps not supporting the new permission model.
17489                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17490                    return false;
17491                }
17492
17493                // Legacy apps have the permission and get user consent on launch.
17494                PermissionsState permissionsState = packageSetting.getPermissionsState();
17495                return permissionsState.isPermissionReviewRequired(userId);
17496            }
17497        }
17498    }
17499
17500    @Override
17501    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17502        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17503        synchronized (mPackages) {
17504            final long identity = Binder.clearCallingIdentity();
17505            try {
17506                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17507                        packageNames, userId);
17508            } finally {
17509                Binder.restoreCallingIdentity(identity);
17510            }
17511        }
17512    }
17513
17514    private static void enforceSystemOrPhoneCaller(String tag) {
17515        int callingUid = Binder.getCallingUid();
17516        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17517            throw new SecurityException(
17518                    "Cannot call " + tag + " from UID " + callingUid);
17519        }
17520    }
17521}
17522