PackageManagerService.java revision 4267eacc3bd6c781423a871e135bac03cd93718a
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                // TODO: remove these terrible hacks
4107                if (actionName.startsWith("android.net.netmon.lingerExpired")
4108                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4109                    return true;
4110                }
4111            }
4112        }
4113        return false;
4114    }
4115
4116    @Override
4117    public int checkSignatures(String pkg1, String pkg2) {
4118        synchronized (mPackages) {
4119            final PackageParser.Package p1 = mPackages.get(pkg1);
4120            final PackageParser.Package p2 = mPackages.get(pkg2);
4121            if (p1 == null || p1.mExtras == null
4122                    || p2 == null || p2.mExtras == null) {
4123                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4124            }
4125            return compareSignatures(p1.mSignatures, p2.mSignatures);
4126        }
4127    }
4128
4129    @Override
4130    public int checkUidSignatures(int uid1, int uid2) {
4131        // Map to base uids.
4132        uid1 = UserHandle.getAppId(uid1);
4133        uid2 = UserHandle.getAppId(uid2);
4134        // reader
4135        synchronized (mPackages) {
4136            Signature[] s1;
4137            Signature[] s2;
4138            Object obj = mSettings.getUserIdLPr(uid1);
4139            if (obj != null) {
4140                if (obj instanceof SharedUserSetting) {
4141                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4142                } else if (obj instanceof PackageSetting) {
4143                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4144                } else {
4145                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4146                }
4147            } else {
4148                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4149            }
4150            obj = mSettings.getUserIdLPr(uid2);
4151            if (obj != null) {
4152                if (obj instanceof SharedUserSetting) {
4153                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4154                } else if (obj instanceof PackageSetting) {
4155                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4156                } else {
4157                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4158                }
4159            } else {
4160                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4161            }
4162            return compareSignatures(s1, s2);
4163        }
4164    }
4165
4166    private void killUid(int appId, int userId, String reason) {
4167        final long identity = Binder.clearCallingIdentity();
4168        try {
4169            IActivityManager am = ActivityManagerNative.getDefault();
4170            if (am != null) {
4171                try {
4172                    am.killUid(appId, userId, reason);
4173                } catch (RemoteException e) {
4174                    /* ignore - same process */
4175                }
4176            }
4177        } finally {
4178            Binder.restoreCallingIdentity(identity);
4179        }
4180    }
4181
4182    /**
4183     * Compares two sets of signatures. Returns:
4184     * <br />
4185     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4186     * <br />
4187     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4188     * <br />
4189     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4190     * <br />
4191     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4192     * <br />
4193     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4194     */
4195    static int compareSignatures(Signature[] s1, Signature[] s2) {
4196        if (s1 == null) {
4197            return s2 == null
4198                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4199                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4200        }
4201
4202        if (s2 == null) {
4203            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4204        }
4205
4206        if (s1.length != s2.length) {
4207            return PackageManager.SIGNATURE_NO_MATCH;
4208        }
4209
4210        // Since both signature sets are of size 1, we can compare without HashSets.
4211        if (s1.length == 1) {
4212            return s1[0].equals(s2[0]) ?
4213                    PackageManager.SIGNATURE_MATCH :
4214                    PackageManager.SIGNATURE_NO_MATCH;
4215        }
4216
4217        ArraySet<Signature> set1 = new ArraySet<Signature>();
4218        for (Signature sig : s1) {
4219            set1.add(sig);
4220        }
4221        ArraySet<Signature> set2 = new ArraySet<Signature>();
4222        for (Signature sig : s2) {
4223            set2.add(sig);
4224        }
4225        // Make sure s2 contains all signatures in s1.
4226        if (set1.equals(set2)) {
4227            return PackageManager.SIGNATURE_MATCH;
4228        }
4229        return PackageManager.SIGNATURE_NO_MATCH;
4230    }
4231
4232    /**
4233     * If the database version for this type of package (internal storage or
4234     * external storage) is less than the version where package signatures
4235     * were updated, return true.
4236     */
4237    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4238        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4239        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4240    }
4241
4242    /**
4243     * Used for backward compatibility to make sure any packages with
4244     * certificate chains get upgraded to the new style. {@code existingSigs}
4245     * will be in the old format (since they were stored on disk from before the
4246     * system upgrade) and {@code scannedSigs} will be in the newer format.
4247     */
4248    private int compareSignaturesCompat(PackageSignatures existingSigs,
4249            PackageParser.Package scannedPkg) {
4250        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4251            return PackageManager.SIGNATURE_NO_MATCH;
4252        }
4253
4254        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4255        for (Signature sig : existingSigs.mSignatures) {
4256            existingSet.add(sig);
4257        }
4258        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4259        for (Signature sig : scannedPkg.mSignatures) {
4260            try {
4261                Signature[] chainSignatures = sig.getChainSignatures();
4262                for (Signature chainSig : chainSignatures) {
4263                    scannedCompatSet.add(chainSig);
4264                }
4265            } catch (CertificateEncodingException e) {
4266                scannedCompatSet.add(sig);
4267            }
4268        }
4269        /*
4270         * Make sure the expanded scanned set contains all signatures in the
4271         * existing one.
4272         */
4273        if (scannedCompatSet.equals(existingSet)) {
4274            // Migrate the old signatures to the new scheme.
4275            existingSigs.assignSignatures(scannedPkg.mSignatures);
4276            // The new KeySets will be re-added later in the scanning process.
4277            synchronized (mPackages) {
4278                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4279            }
4280            return PackageManager.SIGNATURE_MATCH;
4281        }
4282        return PackageManager.SIGNATURE_NO_MATCH;
4283    }
4284
4285    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4286        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4287        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4288    }
4289
4290    private int compareSignaturesRecover(PackageSignatures existingSigs,
4291            PackageParser.Package scannedPkg) {
4292        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4293            return PackageManager.SIGNATURE_NO_MATCH;
4294        }
4295
4296        String msg = null;
4297        try {
4298            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4299                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4300                        + scannedPkg.packageName);
4301                return PackageManager.SIGNATURE_MATCH;
4302            }
4303        } catch (CertificateException e) {
4304            msg = e.getMessage();
4305        }
4306
4307        logCriticalInfo(Log.INFO,
4308                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4309        return PackageManager.SIGNATURE_NO_MATCH;
4310    }
4311
4312    @Override
4313    public String[] getPackagesForUid(int uid) {
4314        uid = UserHandle.getAppId(uid);
4315        // reader
4316        synchronized (mPackages) {
4317            Object obj = mSettings.getUserIdLPr(uid);
4318            if (obj instanceof SharedUserSetting) {
4319                final SharedUserSetting sus = (SharedUserSetting) obj;
4320                final int N = sus.packages.size();
4321                final String[] res = new String[N];
4322                final Iterator<PackageSetting> it = sus.packages.iterator();
4323                int i = 0;
4324                while (it.hasNext()) {
4325                    res[i++] = it.next().name;
4326                }
4327                return res;
4328            } else if (obj instanceof PackageSetting) {
4329                final PackageSetting ps = (PackageSetting) obj;
4330                return new String[] { ps.name };
4331            }
4332        }
4333        return null;
4334    }
4335
4336    @Override
4337    public String getNameForUid(int uid) {
4338        // reader
4339        synchronized (mPackages) {
4340            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4341            if (obj instanceof SharedUserSetting) {
4342                final SharedUserSetting sus = (SharedUserSetting) obj;
4343                return sus.name + ":" + sus.userId;
4344            } else if (obj instanceof PackageSetting) {
4345                final PackageSetting ps = (PackageSetting) obj;
4346                return ps.name;
4347            }
4348        }
4349        return null;
4350    }
4351
4352    @Override
4353    public int getUidForSharedUser(String sharedUserName) {
4354        if(sharedUserName == null) {
4355            return -1;
4356        }
4357        // reader
4358        synchronized (mPackages) {
4359            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4360            if (suid == null) {
4361                return -1;
4362            }
4363            return suid.userId;
4364        }
4365    }
4366
4367    @Override
4368    public int getFlagsForUid(int uid) {
4369        synchronized (mPackages) {
4370            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4371            if (obj instanceof SharedUserSetting) {
4372                final SharedUserSetting sus = (SharedUserSetting) obj;
4373                return sus.pkgFlags;
4374            } else if (obj instanceof PackageSetting) {
4375                final PackageSetting ps = (PackageSetting) obj;
4376                return ps.pkgFlags;
4377            }
4378        }
4379        return 0;
4380    }
4381
4382    @Override
4383    public int getPrivateFlagsForUid(int uid) {
4384        synchronized (mPackages) {
4385            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4386            if (obj instanceof SharedUserSetting) {
4387                final SharedUserSetting sus = (SharedUserSetting) obj;
4388                return sus.pkgPrivateFlags;
4389            } else if (obj instanceof PackageSetting) {
4390                final PackageSetting ps = (PackageSetting) obj;
4391                return ps.pkgPrivateFlags;
4392            }
4393        }
4394        return 0;
4395    }
4396
4397    @Override
4398    public boolean isUidPrivileged(int uid) {
4399        uid = UserHandle.getAppId(uid);
4400        // reader
4401        synchronized (mPackages) {
4402            Object obj = mSettings.getUserIdLPr(uid);
4403            if (obj instanceof SharedUserSetting) {
4404                final SharedUserSetting sus = (SharedUserSetting) obj;
4405                final Iterator<PackageSetting> it = sus.packages.iterator();
4406                while (it.hasNext()) {
4407                    if (it.next().isPrivileged()) {
4408                        return true;
4409                    }
4410                }
4411            } else if (obj instanceof PackageSetting) {
4412                final PackageSetting ps = (PackageSetting) obj;
4413                return ps.isPrivileged();
4414            }
4415        }
4416        return false;
4417    }
4418
4419    @Override
4420    public String[] getAppOpPermissionPackages(String permissionName) {
4421        synchronized (mPackages) {
4422            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4423            if (pkgs == null) {
4424                return null;
4425            }
4426            return pkgs.toArray(new String[pkgs.size()]);
4427        }
4428    }
4429
4430    @Override
4431    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4432            int flags, int userId) {
4433        if (!sUserManager.exists(userId)) return null;
4434        flags = augmentFlagsForUser(flags, userId);
4435        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4436        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4437        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4438    }
4439
4440    @Override
4441    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4442            IntentFilter filter, int match, ComponentName activity) {
4443        final int userId = UserHandle.getCallingUserId();
4444        if (DEBUG_PREFERRED) {
4445            Log.v(TAG, "setLastChosenActivity intent=" + intent
4446                + " resolvedType=" + resolvedType
4447                + " flags=" + flags
4448                + " filter=" + filter
4449                + " match=" + match
4450                + " activity=" + activity);
4451            filter.dump(new PrintStreamPrinter(System.out), "    ");
4452        }
4453        intent.setComponent(null);
4454        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4455        // Find any earlier preferred or last chosen entries and nuke them
4456        findPreferredActivity(intent, resolvedType,
4457                flags, query, 0, false, true, false, userId);
4458        // Add the new activity as the last chosen for this filter
4459        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4460                "Setting last chosen");
4461    }
4462
4463    @Override
4464    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4465        final int userId = UserHandle.getCallingUserId();
4466        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4467        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4468        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4469                false, false, false, userId);
4470    }
4471
4472    private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) {
4473        MessageDigest digest = null;
4474        try {
4475            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4476        } catch (NoSuchAlgorithmException e) {
4477            // If we can't create a digest, ignore ephemeral apps.
4478            return false;
4479        }
4480
4481        final byte[] hostBytes = intent.getData().getHost().getBytes();
4482        final byte[] digestBytes = digest.digest(hostBytes);
4483        int shaPrefix =
4484                digestBytes[0] << 24
4485                | digestBytes[1] << 16
4486                | digestBytes[2] << 8
4487                | digestBytes[3] << 0;
4488        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4489                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4490        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4491            // No hash prefix match; there are no ephemeral apps for this domain.
4492            return false;
4493        }
4494        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4495            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4496            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4497                continue;
4498            }
4499            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4500            // No filters; this should never happen.
4501            if (filters.isEmpty()) {
4502                continue;
4503            }
4504            // We have a domain match; resolve the filters to see if anything matches.
4505            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4506            for (int j = filters.size() - 1; j >= 0; --j) {
4507                ephemeralResolver.addFilter(filters.get(j));
4508            }
4509            List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent(
4510                    intent, resolvedType, false /*defaultOnly*/, userId);
4511            return !ephemeralResolveList.isEmpty();
4512        }
4513        // Hash or filter mis-match; no ephemeral apps for this domain.
4514        return false;
4515    }
4516
4517    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4518            int flags, List<ResolveInfo> query, int userId) {
4519        final boolean isWebUri = hasWebURI(intent);
4520        // Check whether or not an ephemeral app exists to handle the URI.
4521        if (isWebUri && mEphemeralResolverConnection != null) {
4522            // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution.
4523            boolean hasAlwaysHandler = false;
4524            synchronized (mPackages) {
4525                final int count = query.size();
4526                for (int n=0; n<count; n++) {
4527                    ResolveInfo info = query.get(n);
4528                    String packageName = info.activityInfo.packageName;
4529                    PackageSetting ps = mSettings.mPackages.get(packageName);
4530                    if (ps != null) {
4531                        // Try to get the status from User settings first
4532                        long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4533                        int status = (int) (packedStatus >> 32);
4534                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4535                                || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4536                            hasAlwaysHandler = true;
4537                            break;
4538                        }
4539                    }
4540                }
4541            }
4542
4543            // Only consider installing an ephemeral app if there isn't already a verified handler.
4544            // We've determined that there's an ephemeral app available for the URI, ignore any
4545            // ResolveInfo's and just return the ephemeral installer
4546            if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) {
4547                if (DEBUG_EPHEMERAL) {
4548                    Slog.v(TAG, "Resolving to the ephemeral installer");
4549                }
4550                // ditch the result and return a ResolveInfo to launch the ephemeral installer
4551                ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo);
4552                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4553                // make a deep copy of the applicationInfo
4554                ri.activityInfo.applicationInfo = new ApplicationInfo(
4555                        ri.activityInfo.applicationInfo);
4556                if (userId != 0) {
4557                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4558                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4559                }
4560                return ri;
4561            }
4562        }
4563        if (query != null) {
4564            final int N = query.size();
4565            if (N == 1) {
4566                return query.get(0);
4567            } else if (N > 1) {
4568                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4569                // If there is more than one activity with the same priority,
4570                // then let the user decide between them.
4571                ResolveInfo r0 = query.get(0);
4572                ResolveInfo r1 = query.get(1);
4573                if (DEBUG_INTENT_MATCHING || debug) {
4574                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4575                            + r1.activityInfo.name + "=" + r1.priority);
4576                }
4577                // If the first activity has a higher priority, or a different
4578                // default, then it is always desireable to pick it.
4579                if (r0.priority != r1.priority
4580                        || r0.preferredOrder != r1.preferredOrder
4581                        || r0.isDefault != r1.isDefault) {
4582                    return query.get(0);
4583                }
4584                // If we have saved a preference for a preferred activity for
4585                // this Intent, use that.
4586                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4587                        flags, query, r0.priority, true, false, debug, userId);
4588                if (ri != null) {
4589                    return ri;
4590                }
4591                ri = new ResolveInfo(mResolveInfo);
4592                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4593                ri.activityInfo.applicationInfo = new ApplicationInfo(
4594                        ri.activityInfo.applicationInfo);
4595                if (userId != 0) {
4596                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4597                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4598                }
4599                // Make sure that the resolver is displayable in car mode
4600                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4601                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4602                return ri;
4603            }
4604        }
4605        return null;
4606    }
4607
4608    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4609            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4610        final int N = query.size();
4611        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4612                .get(userId);
4613        // Get the list of persistent preferred activities that handle the intent
4614        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4615        List<PersistentPreferredActivity> pprefs = ppir != null
4616                ? ppir.queryIntent(intent, resolvedType,
4617                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4618                : null;
4619        if (pprefs != null && pprefs.size() > 0) {
4620            final int M = pprefs.size();
4621            for (int i=0; i<M; i++) {
4622                final PersistentPreferredActivity ppa = pprefs.get(i);
4623                if (DEBUG_PREFERRED || debug) {
4624                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4625                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4626                            + "\n  component=" + ppa.mComponent);
4627                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4628                }
4629                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4630                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4631                if (DEBUG_PREFERRED || debug) {
4632                    Slog.v(TAG, "Found persistent preferred activity:");
4633                    if (ai != null) {
4634                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4635                    } else {
4636                        Slog.v(TAG, "  null");
4637                    }
4638                }
4639                if (ai == null) {
4640                    // This previously registered persistent preferred activity
4641                    // component is no longer known. Ignore it and do NOT remove it.
4642                    continue;
4643                }
4644                for (int j=0; j<N; j++) {
4645                    final ResolveInfo ri = query.get(j);
4646                    if (!ri.activityInfo.applicationInfo.packageName
4647                            .equals(ai.applicationInfo.packageName)) {
4648                        continue;
4649                    }
4650                    if (!ri.activityInfo.name.equals(ai.name)) {
4651                        continue;
4652                    }
4653                    //  Found a persistent preference that can handle the intent.
4654                    if (DEBUG_PREFERRED || debug) {
4655                        Slog.v(TAG, "Returning persistent preferred activity: " +
4656                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4657                    }
4658                    return ri;
4659                }
4660            }
4661        }
4662        return null;
4663    }
4664
4665    // TODO: handle preferred activities missing while user has amnesia
4666    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4667            List<ResolveInfo> query, int priority, boolean always,
4668            boolean removeMatches, boolean debug, int userId) {
4669        if (!sUserManager.exists(userId)) return null;
4670        flags = augmentFlagsForUser(flags, userId);
4671        // writer
4672        synchronized (mPackages) {
4673            if (intent.getSelector() != null) {
4674                intent = intent.getSelector();
4675            }
4676            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4677
4678            // Try to find a matching persistent preferred activity.
4679            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4680                    debug, userId);
4681
4682            // If a persistent preferred activity matched, use it.
4683            if (pri != null) {
4684                return pri;
4685            }
4686
4687            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4688            // Get the list of preferred activities that handle the intent
4689            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4690            List<PreferredActivity> prefs = pir != null
4691                    ? pir.queryIntent(intent, resolvedType,
4692                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4693                    : null;
4694            if (prefs != null && prefs.size() > 0) {
4695                boolean changed = false;
4696                try {
4697                    // First figure out how good the original match set is.
4698                    // We will only allow preferred activities that came
4699                    // from the same match quality.
4700                    int match = 0;
4701
4702                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4703
4704                    final int N = query.size();
4705                    for (int j=0; j<N; j++) {
4706                        final ResolveInfo ri = query.get(j);
4707                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4708                                + ": 0x" + Integer.toHexString(match));
4709                        if (ri.match > match) {
4710                            match = ri.match;
4711                        }
4712                    }
4713
4714                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4715                            + Integer.toHexString(match));
4716
4717                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4718                    final int M = prefs.size();
4719                    for (int i=0; i<M; i++) {
4720                        final PreferredActivity pa = prefs.get(i);
4721                        if (DEBUG_PREFERRED || debug) {
4722                            Slog.v(TAG, "Checking PreferredActivity ds="
4723                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4724                                    + "\n  component=" + pa.mPref.mComponent);
4725                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4726                        }
4727                        if (pa.mPref.mMatch != match) {
4728                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4729                                    + Integer.toHexString(pa.mPref.mMatch));
4730                            continue;
4731                        }
4732                        // If it's not an "always" type preferred activity and that's what we're
4733                        // looking for, skip it.
4734                        if (always && !pa.mPref.mAlways) {
4735                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4736                            continue;
4737                        }
4738                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4739                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4740                        if (DEBUG_PREFERRED || debug) {
4741                            Slog.v(TAG, "Found preferred activity:");
4742                            if (ai != null) {
4743                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4744                            } else {
4745                                Slog.v(TAG, "  null");
4746                            }
4747                        }
4748                        if (ai == null) {
4749                            // This previously registered preferred activity
4750                            // component is no longer known.  Most likely an update
4751                            // to the app was installed and in the new version this
4752                            // component no longer exists.  Clean it up by removing
4753                            // it from the preferred activities list, and skip it.
4754                            Slog.w(TAG, "Removing dangling preferred activity: "
4755                                    + pa.mPref.mComponent);
4756                            pir.removeFilter(pa);
4757                            changed = true;
4758                            continue;
4759                        }
4760                        for (int j=0; j<N; j++) {
4761                            final ResolveInfo ri = query.get(j);
4762                            if (!ri.activityInfo.applicationInfo.packageName
4763                                    .equals(ai.applicationInfo.packageName)) {
4764                                continue;
4765                            }
4766                            if (!ri.activityInfo.name.equals(ai.name)) {
4767                                continue;
4768                            }
4769
4770                            if (removeMatches) {
4771                                pir.removeFilter(pa);
4772                                changed = true;
4773                                if (DEBUG_PREFERRED) {
4774                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4775                                }
4776                                break;
4777                            }
4778
4779                            // Okay we found a previously set preferred or last chosen app.
4780                            // If the result set is different from when this
4781                            // was created, we need to clear it and re-ask the
4782                            // user their preference, if we're looking for an "always" type entry.
4783                            if (always && !pa.mPref.sameSet(query)) {
4784                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4785                                        + intent + " type " + resolvedType);
4786                                if (DEBUG_PREFERRED) {
4787                                    Slog.v(TAG, "Removing preferred activity since set changed "
4788                                            + pa.mPref.mComponent);
4789                                }
4790                                pir.removeFilter(pa);
4791                                // Re-add the filter as a "last chosen" entry (!always)
4792                                PreferredActivity lastChosen = new PreferredActivity(
4793                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4794                                pir.addFilter(lastChosen);
4795                                changed = true;
4796                                return null;
4797                            }
4798
4799                            // Yay! Either the set matched or we're looking for the last chosen
4800                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4801                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4802                            return ri;
4803                        }
4804                    }
4805                } finally {
4806                    if (changed) {
4807                        if (DEBUG_PREFERRED) {
4808                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4809                        }
4810                        scheduleWritePackageRestrictionsLocked(userId);
4811                    }
4812                }
4813            }
4814        }
4815        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4816        return null;
4817    }
4818
4819    /*
4820     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4821     */
4822    @Override
4823    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4824            int targetUserId) {
4825        mContext.enforceCallingOrSelfPermission(
4826                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4827        List<CrossProfileIntentFilter> matches =
4828                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4829        if (matches != null) {
4830            int size = matches.size();
4831            for (int i = 0; i < size; i++) {
4832                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4833            }
4834        }
4835        if (hasWebURI(intent)) {
4836            // cross-profile app linking works only towards the parent.
4837            final UserInfo parent = getProfileParent(sourceUserId);
4838            synchronized(mPackages) {
4839                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4840                        intent, resolvedType, 0, sourceUserId, parent.id);
4841                return xpDomainInfo != null;
4842            }
4843        }
4844        return false;
4845    }
4846
4847    private UserInfo getProfileParent(int userId) {
4848        final long identity = Binder.clearCallingIdentity();
4849        try {
4850            return sUserManager.getProfileParent(userId);
4851        } finally {
4852            Binder.restoreCallingIdentity(identity);
4853        }
4854    }
4855
4856    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4857            String resolvedType, int userId) {
4858        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4859        if (resolver != null) {
4860            return resolver.queryIntent(intent, resolvedType, false, userId);
4861        }
4862        return null;
4863    }
4864
4865    @Override
4866    public List<ResolveInfo> queryIntentActivities(Intent intent,
4867            String resolvedType, int flags, int userId) {
4868        if (!sUserManager.exists(userId)) return Collections.emptyList();
4869        flags = augmentFlagsForUser(flags, userId);
4870        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4871        ComponentName comp = intent.getComponent();
4872        if (comp == null) {
4873            if (intent.getSelector() != null) {
4874                intent = intent.getSelector();
4875                comp = intent.getComponent();
4876            }
4877        }
4878
4879        if (comp != null) {
4880            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4881            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4882            if (ai != null) {
4883                final ResolveInfo ri = new ResolveInfo();
4884                ri.activityInfo = ai;
4885                list.add(ri);
4886            }
4887            return list;
4888        }
4889
4890        // reader
4891        synchronized (mPackages) {
4892            final String pkgName = intent.getPackage();
4893            if (pkgName == null) {
4894                List<CrossProfileIntentFilter> matchingFilters =
4895                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4896                // Check for results that need to skip the current profile.
4897                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4898                        resolvedType, flags, userId);
4899                if (xpResolveInfo != null) {
4900                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4901                    result.add(xpResolveInfo);
4902                    return filterIfNotSystemUser(result, userId);
4903                }
4904
4905                // Check for results in the current profile.
4906                List<ResolveInfo> result = mActivities.queryIntent(
4907                        intent, resolvedType, flags, userId);
4908                result = filterIfNotSystemUser(result, userId);
4909
4910                // Check for cross profile results.
4911                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4912                xpResolveInfo = queryCrossProfileIntents(
4913                        matchingFilters, intent, resolvedType, flags, userId,
4914                        hasNonNegativePriorityResult);
4915                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4916                    boolean isVisibleToUser = filterIfNotSystemUser(
4917                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4918                    if (isVisibleToUser) {
4919                        result.add(xpResolveInfo);
4920                        Collections.sort(result, mResolvePrioritySorter);
4921                    }
4922                }
4923                if (hasWebURI(intent)) {
4924                    CrossProfileDomainInfo xpDomainInfo = null;
4925                    final UserInfo parent = getProfileParent(userId);
4926                    if (parent != null) {
4927                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4928                                flags, userId, parent.id);
4929                    }
4930                    if (xpDomainInfo != null) {
4931                        if (xpResolveInfo != null) {
4932                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4933                            // in the result.
4934                            result.remove(xpResolveInfo);
4935                        }
4936                        if (result.size() == 0) {
4937                            result.add(xpDomainInfo.resolveInfo);
4938                            return result;
4939                        }
4940                    } else if (result.size() <= 1) {
4941                        return result;
4942                    }
4943                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4944                            xpDomainInfo, userId);
4945                    Collections.sort(result, mResolvePrioritySorter);
4946                }
4947                return result;
4948            }
4949            final PackageParser.Package pkg = mPackages.get(pkgName);
4950            if (pkg != null) {
4951                return filterIfNotSystemUser(
4952                        mActivities.queryIntentForPackage(
4953                                intent, resolvedType, flags, pkg.activities, userId),
4954                        userId);
4955            }
4956            return new ArrayList<ResolveInfo>();
4957        }
4958    }
4959
4960    private static class CrossProfileDomainInfo {
4961        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4962        ResolveInfo resolveInfo;
4963        /* Best domain verification status of the activities found in the other profile */
4964        int bestDomainVerificationStatus;
4965    }
4966
4967    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4968            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4969        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4970                sourceUserId)) {
4971            return null;
4972        }
4973        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4974                resolvedType, flags, parentUserId);
4975
4976        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4977            return null;
4978        }
4979        CrossProfileDomainInfo result = null;
4980        int size = resultTargetUser.size();
4981        for (int i = 0; i < size; i++) {
4982            ResolveInfo riTargetUser = resultTargetUser.get(i);
4983            // Intent filter verification is only for filters that specify a host. So don't return
4984            // those that handle all web uris.
4985            if (riTargetUser.handleAllWebDataURI) {
4986                continue;
4987            }
4988            String packageName = riTargetUser.activityInfo.packageName;
4989            PackageSetting ps = mSettings.mPackages.get(packageName);
4990            if (ps == null) {
4991                continue;
4992            }
4993            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4994            int status = (int)(verificationState >> 32);
4995            if (result == null) {
4996                result = new CrossProfileDomainInfo();
4997                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4998                        sourceUserId, parentUserId);
4999                result.bestDomainVerificationStatus = status;
5000            } else {
5001                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5002                        result.bestDomainVerificationStatus);
5003            }
5004        }
5005        // Don't consider matches with status NEVER across profiles.
5006        if (result != null && result.bestDomainVerificationStatus
5007                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5008            return null;
5009        }
5010        return result;
5011    }
5012
5013    /**
5014     * Verification statuses are ordered from the worse to the best, except for
5015     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5016     */
5017    private int bestDomainVerificationStatus(int status1, int status2) {
5018        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5019            return status2;
5020        }
5021        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5022            return status1;
5023        }
5024        return (int) MathUtils.max(status1, status2);
5025    }
5026
5027    private boolean isUserEnabled(int userId) {
5028        long callingId = Binder.clearCallingIdentity();
5029        try {
5030            UserInfo userInfo = sUserManager.getUserInfo(userId);
5031            return userInfo != null && userInfo.isEnabled();
5032        } finally {
5033            Binder.restoreCallingIdentity(callingId);
5034        }
5035    }
5036
5037    /**
5038     * Filter out activities with systemUserOnly flag set, when current user is not System.
5039     *
5040     * @return filtered list
5041     */
5042    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5043        if (userId == UserHandle.USER_SYSTEM) {
5044            return resolveInfos;
5045        }
5046        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5047            ResolveInfo info = resolveInfos.get(i);
5048            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5049                resolveInfos.remove(i);
5050            }
5051        }
5052        return resolveInfos;
5053    }
5054
5055    /**
5056     * @param resolveInfos list of resolve infos in descending priority order
5057     * @return if the list contains a resolve info with non-negative priority
5058     */
5059    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5060        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5061    }
5062
5063    private static boolean hasWebURI(Intent intent) {
5064        if (intent.getData() == null) {
5065            return false;
5066        }
5067        final String scheme = intent.getScheme();
5068        if (TextUtils.isEmpty(scheme)) {
5069            return false;
5070        }
5071        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5072    }
5073
5074    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5075            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5076            int userId) {
5077        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5078
5079        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5080            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5081                    candidates.size());
5082        }
5083
5084        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5085        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5086        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5087        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5088        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5089        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5090
5091        synchronized (mPackages) {
5092            final int count = candidates.size();
5093            // First, try to use linked apps. Partition the candidates into four lists:
5094            // one for the final results, one for the "do not use ever", one for "undefined status"
5095            // and finally one for "browser app type".
5096            for (int n=0; n<count; n++) {
5097                ResolveInfo info = candidates.get(n);
5098                String packageName = info.activityInfo.packageName;
5099                PackageSetting ps = mSettings.mPackages.get(packageName);
5100                if (ps != null) {
5101                    // Add to the special match all list (Browser use case)
5102                    if (info.handleAllWebDataURI) {
5103                        matchAllList.add(info);
5104                        continue;
5105                    }
5106                    // Try to get the status from User settings first
5107                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5108                    int status = (int)(packedStatus >> 32);
5109                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5110                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5111                        if (DEBUG_DOMAIN_VERIFICATION) {
5112                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5113                                    + " : linkgen=" + linkGeneration);
5114                        }
5115                        // Use link-enabled generation as preferredOrder, i.e.
5116                        // prefer newly-enabled over earlier-enabled.
5117                        info.preferredOrder = linkGeneration;
5118                        alwaysList.add(info);
5119                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5120                        if (DEBUG_DOMAIN_VERIFICATION) {
5121                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5122                        }
5123                        neverList.add(info);
5124                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5125                        if (DEBUG_DOMAIN_VERIFICATION) {
5126                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5127                        }
5128                        alwaysAskList.add(info);
5129                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5130                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5131                        if (DEBUG_DOMAIN_VERIFICATION) {
5132                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5133                        }
5134                        undefinedList.add(info);
5135                    }
5136                }
5137            }
5138
5139            // We'll want to include browser possibilities in a few cases
5140            boolean includeBrowser = false;
5141
5142            // First try to add the "always" resolution(s) for the current user, if any
5143            if (alwaysList.size() > 0) {
5144                result.addAll(alwaysList);
5145            } else {
5146                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5147                result.addAll(undefinedList);
5148                // Maybe add one for the other profile.
5149                if (xpDomainInfo != null && (
5150                        xpDomainInfo.bestDomainVerificationStatus
5151                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5152                    result.add(xpDomainInfo.resolveInfo);
5153                }
5154                includeBrowser = true;
5155            }
5156
5157            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5158            // If there were 'always' entries their preferred order has been set, so we also
5159            // back that off to make the alternatives equivalent
5160            if (alwaysAskList.size() > 0) {
5161                for (ResolveInfo i : result) {
5162                    i.preferredOrder = 0;
5163                }
5164                result.addAll(alwaysAskList);
5165                includeBrowser = true;
5166            }
5167
5168            if (includeBrowser) {
5169                // Also add browsers (all of them or only the default one)
5170                if (DEBUG_DOMAIN_VERIFICATION) {
5171                    Slog.v(TAG, "   ...including browsers in candidate set");
5172                }
5173                if ((matchFlags & MATCH_ALL) != 0) {
5174                    result.addAll(matchAllList);
5175                } else {
5176                    // Browser/generic handling case.  If there's a default browser, go straight
5177                    // to that (but only if there is no other higher-priority match).
5178                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5179                    int maxMatchPrio = 0;
5180                    ResolveInfo defaultBrowserMatch = null;
5181                    final int numCandidates = matchAllList.size();
5182                    for (int n = 0; n < numCandidates; n++) {
5183                        ResolveInfo info = matchAllList.get(n);
5184                        // track the highest overall match priority...
5185                        if (info.priority > maxMatchPrio) {
5186                            maxMatchPrio = info.priority;
5187                        }
5188                        // ...and the highest-priority default browser match
5189                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5190                            if (defaultBrowserMatch == null
5191                                    || (defaultBrowserMatch.priority < info.priority)) {
5192                                if (debug) {
5193                                    Slog.v(TAG, "Considering default browser match " + info);
5194                                }
5195                                defaultBrowserMatch = info;
5196                            }
5197                        }
5198                    }
5199                    if (defaultBrowserMatch != null
5200                            && defaultBrowserMatch.priority >= maxMatchPrio
5201                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5202                    {
5203                        if (debug) {
5204                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5205                        }
5206                        result.add(defaultBrowserMatch);
5207                    } else {
5208                        result.addAll(matchAllList);
5209                    }
5210                }
5211
5212                // If there is nothing selected, add all candidates and remove the ones that the user
5213                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5214                if (result.size() == 0) {
5215                    result.addAll(candidates);
5216                    result.removeAll(neverList);
5217                }
5218            }
5219        }
5220        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5221            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5222                    result.size());
5223            for (ResolveInfo info : result) {
5224                Slog.v(TAG, "  + " + info.activityInfo);
5225            }
5226        }
5227        return result;
5228    }
5229
5230    // Returns a packed value as a long:
5231    //
5232    // high 'int'-sized word: link status: undefined/ask/never/always.
5233    // low 'int'-sized word: relative priority among 'always' results.
5234    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5235        long result = ps.getDomainVerificationStatusForUser(userId);
5236        // if none available, get the master status
5237        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5238            if (ps.getIntentFilterVerificationInfo() != null) {
5239                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5240            }
5241        }
5242        return result;
5243    }
5244
5245    private ResolveInfo querySkipCurrentProfileIntents(
5246            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5247            int flags, int sourceUserId) {
5248        if (matchingFilters != null) {
5249            int size = matchingFilters.size();
5250            for (int i = 0; i < size; i ++) {
5251                CrossProfileIntentFilter filter = matchingFilters.get(i);
5252                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5253                    // Checking if there are activities in the target user that can handle the
5254                    // intent.
5255                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5256                            resolvedType, flags, sourceUserId);
5257                    if (resolveInfo != null) {
5258                        return resolveInfo;
5259                    }
5260                }
5261            }
5262        }
5263        return null;
5264    }
5265
5266    // Return matching ResolveInfo in target user if any.
5267    private ResolveInfo queryCrossProfileIntents(
5268            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5269            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5270        if (matchingFilters != null) {
5271            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5272            // match the same intent. For performance reasons, it is better not to
5273            // run queryIntent twice for the same userId
5274            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5275            int size = matchingFilters.size();
5276            for (int i = 0; i < size; i++) {
5277                CrossProfileIntentFilter filter = matchingFilters.get(i);
5278                int targetUserId = filter.getTargetUserId();
5279                boolean skipCurrentProfile =
5280                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5281                boolean skipCurrentProfileIfNoMatchFound =
5282                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5283                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5284                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5285                    // Checking if there are activities in the target user that can handle the
5286                    // intent.
5287                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5288                            resolvedType, flags, sourceUserId);
5289                    if (resolveInfo != null) return resolveInfo;
5290                    alreadyTriedUserIds.put(targetUserId, true);
5291                }
5292            }
5293        }
5294        return null;
5295    }
5296
5297    /**
5298     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5299     * will forward the intent to the filter's target user.
5300     * Otherwise, returns null.
5301     */
5302    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5303            String resolvedType, int flags, int sourceUserId) {
5304        int targetUserId = filter.getTargetUserId();
5305        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5306                resolvedType, flags, targetUserId);
5307        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5308                && isUserEnabled(targetUserId)) {
5309            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5310        }
5311        return null;
5312    }
5313
5314    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5315            int sourceUserId, int targetUserId) {
5316        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5317        long ident = Binder.clearCallingIdentity();
5318        boolean targetIsProfile;
5319        try {
5320            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5321        } finally {
5322            Binder.restoreCallingIdentity(ident);
5323        }
5324        String className;
5325        if (targetIsProfile) {
5326            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5327        } else {
5328            className = FORWARD_INTENT_TO_PARENT;
5329        }
5330        ComponentName forwardingActivityComponentName = new ComponentName(
5331                mAndroidApplication.packageName, className);
5332        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5333                sourceUserId);
5334        if (!targetIsProfile) {
5335            forwardingActivityInfo.showUserIcon = targetUserId;
5336            forwardingResolveInfo.noResourceId = true;
5337        }
5338        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5339        forwardingResolveInfo.priority = 0;
5340        forwardingResolveInfo.preferredOrder = 0;
5341        forwardingResolveInfo.match = 0;
5342        forwardingResolveInfo.isDefault = true;
5343        forwardingResolveInfo.filter = filter;
5344        forwardingResolveInfo.targetUserId = targetUserId;
5345        return forwardingResolveInfo;
5346    }
5347
5348    @Override
5349    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5350            Intent[] specifics, String[] specificTypes, Intent intent,
5351            String resolvedType, int flags, int userId) {
5352        if (!sUserManager.exists(userId)) return Collections.emptyList();
5353        flags = augmentFlagsForUser(flags, userId);
5354        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5355                false, "query intent activity options");
5356        final String resultsAction = intent.getAction();
5357
5358        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5359                | PackageManager.GET_RESOLVED_FILTER, userId);
5360
5361        if (DEBUG_INTENT_MATCHING) {
5362            Log.v(TAG, "Query " + intent + ": " + results);
5363        }
5364
5365        int specificsPos = 0;
5366        int N;
5367
5368        // todo: note that the algorithm used here is O(N^2).  This
5369        // isn't a problem in our current environment, but if we start running
5370        // into situations where we have more than 5 or 10 matches then this
5371        // should probably be changed to something smarter...
5372
5373        // First we go through and resolve each of the specific items
5374        // that were supplied, taking care of removing any corresponding
5375        // duplicate items in the generic resolve list.
5376        if (specifics != null) {
5377            for (int i=0; i<specifics.length; i++) {
5378                final Intent sintent = specifics[i];
5379                if (sintent == null) {
5380                    continue;
5381                }
5382
5383                if (DEBUG_INTENT_MATCHING) {
5384                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5385                }
5386
5387                String action = sintent.getAction();
5388                if (resultsAction != null && resultsAction.equals(action)) {
5389                    // If this action was explicitly requested, then don't
5390                    // remove things that have it.
5391                    action = null;
5392                }
5393
5394                ResolveInfo ri = null;
5395                ActivityInfo ai = null;
5396
5397                ComponentName comp = sintent.getComponent();
5398                if (comp == null) {
5399                    ri = resolveIntent(
5400                        sintent,
5401                        specificTypes != null ? specificTypes[i] : null,
5402                            flags, userId);
5403                    if (ri == null) {
5404                        continue;
5405                    }
5406                    if (ri == mResolveInfo) {
5407                        // ACK!  Must do something better with this.
5408                    }
5409                    ai = ri.activityInfo;
5410                    comp = new ComponentName(ai.applicationInfo.packageName,
5411                            ai.name);
5412                } else {
5413                    ai = getActivityInfo(comp, flags, userId);
5414                    if (ai == null) {
5415                        continue;
5416                    }
5417                }
5418
5419                // Look for any generic query activities that are duplicates
5420                // of this specific one, and remove them from the results.
5421                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5422                N = results.size();
5423                int j;
5424                for (j=specificsPos; j<N; j++) {
5425                    ResolveInfo sri = results.get(j);
5426                    if ((sri.activityInfo.name.equals(comp.getClassName())
5427                            && sri.activityInfo.applicationInfo.packageName.equals(
5428                                    comp.getPackageName()))
5429                        || (action != null && sri.filter.matchAction(action))) {
5430                        results.remove(j);
5431                        if (DEBUG_INTENT_MATCHING) Log.v(
5432                            TAG, "Removing duplicate item from " + j
5433                            + " due to specific " + specificsPos);
5434                        if (ri == null) {
5435                            ri = sri;
5436                        }
5437                        j--;
5438                        N--;
5439                    }
5440                }
5441
5442                // Add this specific item to its proper place.
5443                if (ri == null) {
5444                    ri = new ResolveInfo();
5445                    ri.activityInfo = ai;
5446                }
5447                results.add(specificsPos, ri);
5448                ri.specificIndex = i;
5449                specificsPos++;
5450            }
5451        }
5452
5453        // Now we go through the remaining generic results and remove any
5454        // duplicate actions that are found here.
5455        N = results.size();
5456        for (int i=specificsPos; i<N-1; i++) {
5457            final ResolveInfo rii = results.get(i);
5458            if (rii.filter == null) {
5459                continue;
5460            }
5461
5462            // Iterate over all of the actions of this result's intent
5463            // filter...  typically this should be just one.
5464            final Iterator<String> it = rii.filter.actionsIterator();
5465            if (it == null) {
5466                continue;
5467            }
5468            while (it.hasNext()) {
5469                final String action = it.next();
5470                if (resultsAction != null && resultsAction.equals(action)) {
5471                    // If this action was explicitly requested, then don't
5472                    // remove things that have it.
5473                    continue;
5474                }
5475                for (int j=i+1; j<N; j++) {
5476                    final ResolveInfo rij = results.get(j);
5477                    if (rij.filter != null && rij.filter.hasAction(action)) {
5478                        results.remove(j);
5479                        if (DEBUG_INTENT_MATCHING) Log.v(
5480                            TAG, "Removing duplicate item from " + j
5481                            + " due to action " + action + " at " + i);
5482                        j--;
5483                        N--;
5484                    }
5485                }
5486            }
5487
5488            // If the caller didn't request filter information, drop it now
5489            // so we don't have to marshall/unmarshall it.
5490            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5491                rii.filter = null;
5492            }
5493        }
5494
5495        // Filter out the caller activity if so requested.
5496        if (caller != null) {
5497            N = results.size();
5498            for (int i=0; i<N; i++) {
5499                ActivityInfo ainfo = results.get(i).activityInfo;
5500                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5501                        && caller.getClassName().equals(ainfo.name)) {
5502                    results.remove(i);
5503                    break;
5504                }
5505            }
5506        }
5507
5508        // If the caller didn't request filter information,
5509        // drop them now so we don't have to
5510        // marshall/unmarshall it.
5511        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5512            N = results.size();
5513            for (int i=0; i<N; i++) {
5514                results.get(i).filter = null;
5515            }
5516        }
5517
5518        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5519        return results;
5520    }
5521
5522    @Override
5523    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5524            int userId) {
5525        if (!sUserManager.exists(userId)) return Collections.emptyList();
5526        flags = augmentFlagsForUser(flags, userId);
5527        ComponentName comp = intent.getComponent();
5528        if (comp == null) {
5529            if (intent.getSelector() != null) {
5530                intent = intent.getSelector();
5531                comp = intent.getComponent();
5532            }
5533        }
5534        if (comp != null) {
5535            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5536            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5537            if (ai != null) {
5538                ResolveInfo ri = new ResolveInfo();
5539                ri.activityInfo = ai;
5540                list.add(ri);
5541            }
5542            return list;
5543        }
5544
5545        // reader
5546        synchronized (mPackages) {
5547            String pkgName = intent.getPackage();
5548            if (pkgName == null) {
5549                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5550            }
5551            final PackageParser.Package pkg = mPackages.get(pkgName);
5552            if (pkg != null) {
5553                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5554                        userId);
5555            }
5556            return null;
5557        }
5558    }
5559
5560    @Override
5561    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5562        if (!sUserManager.exists(userId)) return null;
5563        flags = augmentFlagsForUser(flags, userId);
5564        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5565        if (query != null) {
5566            if (query.size() >= 1) {
5567                // If there is more than one service with the same priority,
5568                // just arbitrarily pick the first one.
5569                return query.get(0);
5570            }
5571        }
5572        return null;
5573    }
5574
5575    @Override
5576    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5577            int userId) {
5578        if (!sUserManager.exists(userId)) return Collections.emptyList();
5579        flags = augmentFlagsForUser(flags, userId);
5580        ComponentName comp = intent.getComponent();
5581        if (comp == null) {
5582            if (intent.getSelector() != null) {
5583                intent = intent.getSelector();
5584                comp = intent.getComponent();
5585            }
5586        }
5587        if (comp != null) {
5588            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5589            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5590            if (si != null) {
5591                final ResolveInfo ri = new ResolveInfo();
5592                ri.serviceInfo = si;
5593                list.add(ri);
5594            }
5595            return list;
5596        }
5597
5598        // reader
5599        synchronized (mPackages) {
5600            String pkgName = intent.getPackage();
5601            if (pkgName == null) {
5602                return mServices.queryIntent(intent, resolvedType, flags, userId);
5603            }
5604            final PackageParser.Package pkg = mPackages.get(pkgName);
5605            if (pkg != null) {
5606                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5607                        userId);
5608            }
5609            return null;
5610        }
5611    }
5612
5613    @Override
5614    public List<ResolveInfo> queryIntentContentProviders(
5615            Intent intent, String resolvedType, int flags, int userId) {
5616        if (!sUserManager.exists(userId)) return Collections.emptyList();
5617        flags = augmentFlagsForUser(flags, userId);
5618        ComponentName comp = intent.getComponent();
5619        if (comp == null) {
5620            if (intent.getSelector() != null) {
5621                intent = intent.getSelector();
5622                comp = intent.getComponent();
5623            }
5624        }
5625        if (comp != null) {
5626            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5627            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5628            if (pi != null) {
5629                final ResolveInfo ri = new ResolveInfo();
5630                ri.providerInfo = pi;
5631                list.add(ri);
5632            }
5633            return list;
5634        }
5635
5636        // reader
5637        synchronized (mPackages) {
5638            String pkgName = intent.getPackage();
5639            if (pkgName == null) {
5640                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5641            }
5642            final PackageParser.Package pkg = mPackages.get(pkgName);
5643            if (pkg != null) {
5644                return mProviders.queryIntentForPackage(
5645                        intent, resolvedType, flags, pkg.providers, userId);
5646            }
5647            return null;
5648        }
5649    }
5650
5651    @Override
5652    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5653        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5654
5655        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5656
5657        // writer
5658        synchronized (mPackages) {
5659            ArrayList<PackageInfo> list;
5660            if (listUninstalled) {
5661                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5662                for (PackageSetting ps : mSettings.mPackages.values()) {
5663                    PackageInfo pi;
5664                    if (ps.pkg != null) {
5665                        pi = generatePackageInfo(ps.pkg, flags, userId);
5666                    } else {
5667                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5668                    }
5669                    if (pi != null) {
5670                        list.add(pi);
5671                    }
5672                }
5673            } else {
5674                list = new ArrayList<PackageInfo>(mPackages.size());
5675                for (PackageParser.Package p : mPackages.values()) {
5676                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5677                    if (pi != null) {
5678                        list.add(pi);
5679                    }
5680                }
5681            }
5682
5683            return new ParceledListSlice<PackageInfo>(list);
5684        }
5685    }
5686
5687    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5688            String[] permissions, boolean[] tmp, int flags, int userId) {
5689        int numMatch = 0;
5690        final PermissionsState permissionsState = ps.getPermissionsState();
5691        for (int i=0; i<permissions.length; i++) {
5692            final String permission = permissions[i];
5693            if (permissionsState.hasPermission(permission, userId)) {
5694                tmp[i] = true;
5695                numMatch++;
5696            } else {
5697                tmp[i] = false;
5698            }
5699        }
5700        if (numMatch == 0) {
5701            return;
5702        }
5703        PackageInfo pi;
5704        if (ps.pkg != null) {
5705            pi = generatePackageInfo(ps.pkg, flags, userId);
5706        } else {
5707            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5708        }
5709        // The above might return null in cases of uninstalled apps or install-state
5710        // skew across users/profiles.
5711        if (pi != null) {
5712            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5713                if (numMatch == permissions.length) {
5714                    pi.requestedPermissions = permissions;
5715                } else {
5716                    pi.requestedPermissions = new String[numMatch];
5717                    numMatch = 0;
5718                    for (int i=0; i<permissions.length; i++) {
5719                        if (tmp[i]) {
5720                            pi.requestedPermissions[numMatch] = permissions[i];
5721                            numMatch++;
5722                        }
5723                    }
5724                }
5725            }
5726            list.add(pi);
5727        }
5728    }
5729
5730    @Override
5731    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5732            String[] permissions, int flags, int userId) {
5733        if (!sUserManager.exists(userId)) return null;
5734        flags = augmentFlagsForUser(flags, userId);
5735        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5736
5737        // writer
5738        synchronized (mPackages) {
5739            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5740            boolean[] tmpBools = new boolean[permissions.length];
5741            if (listUninstalled) {
5742                for (PackageSetting ps : mSettings.mPackages.values()) {
5743                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5744                }
5745            } else {
5746                for (PackageParser.Package pkg : mPackages.values()) {
5747                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5748                    if (ps != null) {
5749                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5750                                userId);
5751                    }
5752                }
5753            }
5754
5755            return new ParceledListSlice<PackageInfo>(list);
5756        }
5757    }
5758
5759    @Override
5760    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5761        if (!sUserManager.exists(userId)) return null;
5762        flags = augmentFlagsForUser(flags, userId);
5763        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5764
5765        // writer
5766        synchronized (mPackages) {
5767            ArrayList<ApplicationInfo> list;
5768            if (listUninstalled) {
5769                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5770                for (PackageSetting ps : mSettings.mPackages.values()) {
5771                    ApplicationInfo ai;
5772                    if (ps.pkg != null) {
5773                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5774                                ps.readUserState(userId), userId);
5775                    } else {
5776                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5777                    }
5778                    if (ai != null) {
5779                        list.add(ai);
5780                    }
5781                }
5782            } else {
5783                list = new ArrayList<ApplicationInfo>(mPackages.size());
5784                for (PackageParser.Package p : mPackages.values()) {
5785                    if (p.mExtras != null) {
5786                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5787                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5788                        if (ai != null) {
5789                            list.add(ai);
5790                        }
5791                    }
5792                }
5793            }
5794
5795            return new ParceledListSlice<ApplicationInfo>(list);
5796        }
5797    }
5798
5799    @Override
5800    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5801        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5802                "getEphemeralApplications");
5803        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5804                "getEphemeralApplications");
5805        synchronized (mPackages) {
5806            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5807                    .getEphemeralApplicationsLPw(userId);
5808            if (ephemeralApps != null) {
5809                return new ParceledListSlice<>(ephemeralApps);
5810            }
5811        }
5812        return null;
5813    }
5814
5815    @Override
5816    public boolean isEphemeralApplication(String packageName, int userId) {
5817        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5818                "isEphemeral");
5819        if (!isCallerSameApp(packageName)) {
5820            return false;
5821        }
5822        synchronized (mPackages) {
5823            PackageParser.Package pkg = mPackages.get(packageName);
5824            if (pkg != null) {
5825                return pkg.applicationInfo.isEphemeralApp();
5826            }
5827        }
5828        return false;
5829    }
5830
5831    @Override
5832    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5833        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5834                "getCookie");
5835        if (!isCallerSameApp(packageName)) {
5836            return null;
5837        }
5838        synchronized (mPackages) {
5839            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5840                    packageName, userId);
5841        }
5842    }
5843
5844    @Override
5845    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5846        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5847                "setCookie");
5848        if (!isCallerSameApp(packageName)) {
5849            return false;
5850        }
5851        synchronized (mPackages) {
5852            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5853                    packageName, cookie, userId);
5854        }
5855    }
5856
5857    @Override
5858    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5859        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5860                "getEphemeralApplicationIcon");
5861        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5862                "getEphemeralApplicationIcon");
5863        synchronized (mPackages) {
5864            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5865                    packageName, userId);
5866        }
5867    }
5868
5869    private boolean isCallerSameApp(String packageName) {
5870        PackageParser.Package pkg = mPackages.get(packageName);
5871        return pkg != null
5872                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5873    }
5874
5875    public List<ApplicationInfo> getPersistentApplications(int flags) {
5876        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5877
5878        // reader
5879        synchronized (mPackages) {
5880            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5881            final int userId = UserHandle.getCallingUserId();
5882            while (i.hasNext()) {
5883                final PackageParser.Package p = i.next();
5884                if (p.applicationInfo != null
5885                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5886                        && (!mSafeMode || isSystemApp(p))) {
5887                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5888                    if (ps != null) {
5889                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5890                                ps.readUserState(userId), userId);
5891                        if (ai != null) {
5892                            finalList.add(ai);
5893                        }
5894                    }
5895                }
5896            }
5897        }
5898
5899        return finalList;
5900    }
5901
5902    @Override
5903    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5904        if (!sUserManager.exists(userId)) return null;
5905        flags = augmentFlagsForUser(flags, userId);
5906        // reader
5907        synchronized (mPackages) {
5908            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5909            PackageSetting ps = provider != null
5910                    ? mSettings.mPackages.get(provider.owner.packageName)
5911                    : null;
5912            return ps != null
5913                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5914                    && (!mSafeMode || (provider.info.applicationInfo.flags
5915                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5916                    ? PackageParser.generateProviderInfo(provider, flags,
5917                            ps.readUserState(userId), userId)
5918                    : null;
5919        }
5920    }
5921
5922    /**
5923     * @deprecated
5924     */
5925    @Deprecated
5926    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5927        // reader
5928        synchronized (mPackages) {
5929            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5930                    .entrySet().iterator();
5931            final int userId = UserHandle.getCallingUserId();
5932            while (i.hasNext()) {
5933                Map.Entry<String, PackageParser.Provider> entry = i.next();
5934                PackageParser.Provider p = entry.getValue();
5935                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5936
5937                if (ps != null && p.syncable
5938                        && (!mSafeMode || (p.info.applicationInfo.flags
5939                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5940                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5941                            ps.readUserState(userId), userId);
5942                    if (info != null) {
5943                        outNames.add(entry.getKey());
5944                        outInfo.add(info);
5945                    }
5946                }
5947            }
5948        }
5949    }
5950
5951    @Override
5952    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5953            int uid, int flags) {
5954        final int userId = processName != null ? UserHandle.getUserId(uid)
5955                : UserHandle.getCallingUserId();
5956        if (!sUserManager.exists(userId)) return null;
5957        flags = augmentFlagsForUser(flags, userId);
5958
5959        ArrayList<ProviderInfo> finalList = null;
5960        // reader
5961        synchronized (mPackages) {
5962            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5963            while (i.hasNext()) {
5964                final PackageParser.Provider p = i.next();
5965                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5966                if (ps != null && p.info.authority != null
5967                        && (processName == null
5968                                || (p.info.processName.equals(processName)
5969                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5970                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5971                        && (!mSafeMode
5972                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5973                    if (finalList == null) {
5974                        finalList = new ArrayList<ProviderInfo>(3);
5975                    }
5976                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5977                            ps.readUserState(userId), userId);
5978                    if (info != null) {
5979                        finalList.add(info);
5980                    }
5981                }
5982            }
5983        }
5984
5985        if (finalList != null) {
5986            Collections.sort(finalList, mProviderInitOrderSorter);
5987            return new ParceledListSlice<ProviderInfo>(finalList);
5988        }
5989
5990        return null;
5991    }
5992
5993    @Override
5994    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5995            int flags) {
5996        // reader
5997        synchronized (mPackages) {
5998            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5999            return PackageParser.generateInstrumentationInfo(i, flags);
6000        }
6001    }
6002
6003    @Override
6004    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6005            int flags) {
6006        ArrayList<InstrumentationInfo> finalList =
6007            new ArrayList<InstrumentationInfo>();
6008
6009        // reader
6010        synchronized (mPackages) {
6011            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6012            while (i.hasNext()) {
6013                final PackageParser.Instrumentation p = i.next();
6014                if (targetPackage == null
6015                        || targetPackage.equals(p.info.targetPackage)) {
6016                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6017                            flags);
6018                    if (ii != null) {
6019                        finalList.add(ii);
6020                    }
6021                }
6022            }
6023        }
6024
6025        return finalList;
6026    }
6027
6028    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6029        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6030        if (overlays == null) {
6031            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6032            return;
6033        }
6034        for (PackageParser.Package opkg : overlays.values()) {
6035            // Not much to do if idmap fails: we already logged the error
6036            // and we certainly don't want to abort installation of pkg simply
6037            // because an overlay didn't fit properly. For these reasons,
6038            // ignore the return value of createIdmapForPackagePairLI.
6039            createIdmapForPackagePairLI(pkg, opkg);
6040        }
6041    }
6042
6043    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6044            PackageParser.Package opkg) {
6045        if (!opkg.mTrustedOverlay) {
6046            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6047                    opkg.baseCodePath + ": overlay not trusted");
6048            return false;
6049        }
6050        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6051        if (overlaySet == null) {
6052            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6053                    opkg.baseCodePath + " but target package has no known overlays");
6054            return false;
6055        }
6056        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6057        // TODO: generate idmap for split APKs
6058        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6059            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6060                    + opkg.baseCodePath);
6061            return false;
6062        }
6063        PackageParser.Package[] overlayArray =
6064            overlaySet.values().toArray(new PackageParser.Package[0]);
6065        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6066            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6067                return p1.mOverlayPriority - p2.mOverlayPriority;
6068            }
6069        };
6070        Arrays.sort(overlayArray, cmp);
6071
6072        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6073        int i = 0;
6074        for (PackageParser.Package p : overlayArray) {
6075            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6076        }
6077        return true;
6078    }
6079
6080    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6081        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6082        try {
6083            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6084        } finally {
6085            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6086        }
6087    }
6088
6089    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6090        final File[] files = dir.listFiles();
6091        if (ArrayUtils.isEmpty(files)) {
6092            Log.d(TAG, "No files in app dir " + dir);
6093            return;
6094        }
6095
6096        if (DEBUG_PACKAGE_SCANNING) {
6097            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6098                    + " flags=0x" + Integer.toHexString(parseFlags));
6099        }
6100
6101        for (File file : files) {
6102            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6103                    && !PackageInstallerService.isStageName(file.getName());
6104            if (!isPackage) {
6105                // Ignore entries which are not packages
6106                continue;
6107            }
6108            try {
6109                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6110                        scanFlags, currentTime, null);
6111            } catch (PackageManagerException e) {
6112                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6113
6114                // Delete invalid userdata apps
6115                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6116                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6117                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6118                    if (file.isDirectory()) {
6119                        mInstaller.rmPackageDir(file.getAbsolutePath());
6120                    } else {
6121                        file.delete();
6122                    }
6123                }
6124            }
6125        }
6126    }
6127
6128    private static File getSettingsProblemFile() {
6129        File dataDir = Environment.getDataDirectory();
6130        File systemDir = new File(dataDir, "system");
6131        File fname = new File(systemDir, "uiderrors.txt");
6132        return fname;
6133    }
6134
6135    static void reportSettingsProblem(int priority, String msg) {
6136        logCriticalInfo(priority, msg);
6137    }
6138
6139    static void logCriticalInfo(int priority, String msg) {
6140        Slog.println(priority, TAG, msg);
6141        EventLogTags.writePmCriticalInfo(msg);
6142        try {
6143            File fname = getSettingsProblemFile();
6144            FileOutputStream out = new FileOutputStream(fname, true);
6145            PrintWriter pw = new FastPrintWriter(out);
6146            SimpleDateFormat formatter = new SimpleDateFormat();
6147            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6148            pw.println(dateString + ": " + msg);
6149            pw.close();
6150            FileUtils.setPermissions(
6151                    fname.toString(),
6152                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6153                    -1, -1);
6154        } catch (java.io.IOException e) {
6155        }
6156    }
6157
6158    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6159            PackageParser.Package pkg, File srcFile, int parseFlags)
6160            throws PackageManagerException {
6161        if (ps != null
6162                && ps.codePath.equals(srcFile)
6163                && ps.timeStamp == srcFile.lastModified()
6164                && !isCompatSignatureUpdateNeeded(pkg)
6165                && !isRecoverSignatureUpdateNeeded(pkg)) {
6166            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6167            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6168            ArraySet<PublicKey> signingKs;
6169            synchronized (mPackages) {
6170                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6171            }
6172            if (ps.signatures.mSignatures != null
6173                    && ps.signatures.mSignatures.length != 0
6174                    && signingKs != null) {
6175                // Optimization: reuse the existing cached certificates
6176                // if the package appears to be unchanged.
6177                pkg.mSignatures = ps.signatures.mSignatures;
6178                pkg.mSigningKeys = signingKs;
6179                return;
6180            }
6181
6182            Slog.w(TAG, "PackageSetting for " + ps.name
6183                    + " is missing signatures.  Collecting certs again to recover them.");
6184        } else {
6185            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6186        }
6187
6188        try {
6189            pp.collectCertificates(pkg, parseFlags);
6190            pp.collectManifestDigest(pkg);
6191        } catch (PackageParserException e) {
6192            throw PackageManagerException.from(e);
6193        }
6194    }
6195
6196    /**
6197     *  Traces a package scan.
6198     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6199     */
6200    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6201            long currentTime, UserHandle user) throws PackageManagerException {
6202        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6203        try {
6204            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6205        } finally {
6206            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6207        }
6208    }
6209
6210    /**
6211     *  Scans a package and returns the newly parsed package.
6212     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6213     */
6214    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6215            long currentTime, UserHandle user) throws PackageManagerException {
6216        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6217        parseFlags |= mDefParseFlags;
6218        PackageParser pp = new PackageParser();
6219        pp.setSeparateProcesses(mSeparateProcesses);
6220        pp.setOnlyCoreApps(mOnlyCore);
6221        pp.setDisplayMetrics(mMetrics);
6222
6223        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6224            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6225        }
6226
6227        final PackageParser.Package pkg;
6228        try {
6229            pkg = pp.parsePackage(scanFile, parseFlags);
6230        } catch (PackageParserException e) {
6231            throw PackageManagerException.from(e);
6232        }
6233
6234        PackageSetting ps = null;
6235        PackageSetting updatedPkg;
6236        // reader
6237        synchronized (mPackages) {
6238            // Look to see if we already know about this package.
6239            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6240            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6241                // This package has been renamed to its original name.  Let's
6242                // use that.
6243                ps = mSettings.peekPackageLPr(oldName);
6244            }
6245            // If there was no original package, see one for the real package name.
6246            if (ps == null) {
6247                ps = mSettings.peekPackageLPr(pkg.packageName);
6248            }
6249            // Check to see if this package could be hiding/updating a system
6250            // package.  Must look for it either under the original or real
6251            // package name depending on our state.
6252            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6253            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6254        }
6255        boolean updatedPkgBetter = false;
6256        // First check if this is a system package that may involve an update
6257        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6258            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6259            // it needs to drop FLAG_PRIVILEGED.
6260            if (locationIsPrivileged(scanFile)) {
6261                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6262            } else {
6263                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6264            }
6265
6266            if (ps != null && !ps.codePath.equals(scanFile)) {
6267                // The path has changed from what was last scanned...  check the
6268                // version of the new path against what we have stored to determine
6269                // what to do.
6270                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6271                if (pkg.mVersionCode <= ps.versionCode) {
6272                    // The system package has been updated and the code path does not match
6273                    // Ignore entry. Skip it.
6274                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6275                            + " ignored: updated version " + ps.versionCode
6276                            + " better than this " + pkg.mVersionCode);
6277                    if (!updatedPkg.codePath.equals(scanFile)) {
6278                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6279                                + ps.name + " changing from " + updatedPkg.codePathString
6280                                + " to " + scanFile);
6281                        updatedPkg.codePath = scanFile;
6282                        updatedPkg.codePathString = scanFile.toString();
6283                        updatedPkg.resourcePath = scanFile;
6284                        updatedPkg.resourcePathString = scanFile.toString();
6285                    }
6286                    updatedPkg.pkg = pkg;
6287                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6288                            "Package " + ps.name + " at " + scanFile
6289                                    + " ignored: updated version " + ps.versionCode
6290                                    + " better than this " + pkg.mVersionCode);
6291                } else {
6292                    // The current app on the system partition is better than
6293                    // what we have updated to on the data partition; switch
6294                    // back to the system partition version.
6295                    // At this point, its safely assumed that package installation for
6296                    // apps in system partition will go through. If not there won't be a working
6297                    // version of the app
6298                    // writer
6299                    synchronized (mPackages) {
6300                        // Just remove the loaded entries from package lists.
6301                        mPackages.remove(ps.name);
6302                    }
6303
6304                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6305                            + " reverting from " + ps.codePathString
6306                            + ": new version " + pkg.mVersionCode
6307                            + " better than installed " + ps.versionCode);
6308
6309                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6310                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6311                    synchronized (mInstallLock) {
6312                        args.cleanUpResourcesLI();
6313                    }
6314                    synchronized (mPackages) {
6315                        mSettings.enableSystemPackageLPw(ps.name);
6316                    }
6317                    updatedPkgBetter = true;
6318                }
6319            }
6320        }
6321
6322        if (updatedPkg != null) {
6323            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6324            // initially
6325            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6326
6327            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6328            // flag set initially
6329            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6330                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6331            }
6332        }
6333
6334        // Verify certificates against what was last scanned
6335        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6336
6337        /*
6338         * A new system app appeared, but we already had a non-system one of the
6339         * same name installed earlier.
6340         */
6341        boolean shouldHideSystemApp = false;
6342        if (updatedPkg == null && ps != null
6343                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6344            /*
6345             * Check to make sure the signatures match first. If they don't,
6346             * wipe the installed application and its data.
6347             */
6348            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6349                    != PackageManager.SIGNATURE_MATCH) {
6350                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6351                        + " signatures don't match existing userdata copy; removing");
6352                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6353                ps = null;
6354            } else {
6355                /*
6356                 * If the newly-added system app is an older version than the
6357                 * already installed version, hide it. It will be scanned later
6358                 * and re-added like an update.
6359                 */
6360                if (pkg.mVersionCode <= ps.versionCode) {
6361                    shouldHideSystemApp = true;
6362                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6363                            + " but new version " + pkg.mVersionCode + " better than installed "
6364                            + ps.versionCode + "; hiding system");
6365                } else {
6366                    /*
6367                     * The newly found system app is a newer version that the
6368                     * one previously installed. Simply remove the
6369                     * already-installed application and replace it with our own
6370                     * while keeping the application data.
6371                     */
6372                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6373                            + " reverting from " + ps.codePathString + ": new version "
6374                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6375                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6376                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6377                    synchronized (mInstallLock) {
6378                        args.cleanUpResourcesLI();
6379                    }
6380                }
6381            }
6382        }
6383
6384        // The apk is forward locked (not public) if its code and resources
6385        // are kept in different files. (except for app in either system or
6386        // vendor path).
6387        // TODO grab this value from PackageSettings
6388        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6389            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6390                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6391            }
6392        }
6393
6394        // TODO: extend to support forward-locked splits
6395        String resourcePath = null;
6396        String baseResourcePath = null;
6397        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6398            if (ps != null && ps.resourcePathString != null) {
6399                resourcePath = ps.resourcePathString;
6400                baseResourcePath = ps.resourcePathString;
6401            } else {
6402                // Should not happen at all. Just log an error.
6403                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6404            }
6405        } else {
6406            resourcePath = pkg.codePath;
6407            baseResourcePath = pkg.baseCodePath;
6408        }
6409
6410        // Set application objects path explicitly.
6411        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6412        pkg.applicationInfo.setCodePath(pkg.codePath);
6413        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6414        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6415        pkg.applicationInfo.setResourcePath(resourcePath);
6416        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6417        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6418
6419        // Note that we invoke the following method only if we are about to unpack an application
6420        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6421                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6422
6423        /*
6424         * If the system app should be overridden by a previously installed
6425         * data, hide the system app now and let the /data/app scan pick it up
6426         * again.
6427         */
6428        if (shouldHideSystemApp) {
6429            synchronized (mPackages) {
6430                mSettings.disableSystemPackageLPw(pkg.packageName);
6431            }
6432        }
6433
6434        return scannedPkg;
6435    }
6436
6437    private static String fixProcessName(String defProcessName,
6438            String processName, int uid) {
6439        if (processName == null) {
6440            return defProcessName;
6441        }
6442        return processName;
6443    }
6444
6445    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6446            throws PackageManagerException {
6447        if (pkgSetting.signatures.mSignatures != null) {
6448            // Already existing package. Make sure signatures match
6449            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6450                    == PackageManager.SIGNATURE_MATCH;
6451            if (!match) {
6452                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6453                        == PackageManager.SIGNATURE_MATCH;
6454            }
6455            if (!match) {
6456                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6457                        == PackageManager.SIGNATURE_MATCH;
6458            }
6459            if (!match) {
6460                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6461                        + pkg.packageName + " signatures do not match the "
6462                        + "previously installed version; ignoring!");
6463            }
6464        }
6465
6466        // Check for shared user signatures
6467        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6468            // Already existing package. Make sure signatures match
6469            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6470                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6471            if (!match) {
6472                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6473                        == PackageManager.SIGNATURE_MATCH;
6474            }
6475            if (!match) {
6476                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6477                        == PackageManager.SIGNATURE_MATCH;
6478            }
6479            if (!match) {
6480                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6481                        "Package " + pkg.packageName
6482                        + " has no signatures that match those in shared user "
6483                        + pkgSetting.sharedUser.name + "; ignoring!");
6484            }
6485        }
6486    }
6487
6488    /**
6489     * Enforces that only the system UID or root's UID can call a method exposed
6490     * via Binder.
6491     *
6492     * @param message used as message if SecurityException is thrown
6493     * @throws SecurityException if the caller is not system or root
6494     */
6495    private static final void enforceSystemOrRoot(String message) {
6496        final int uid = Binder.getCallingUid();
6497        if (uid != Process.SYSTEM_UID && uid != 0) {
6498            throw new SecurityException(message);
6499        }
6500    }
6501
6502    @Override
6503    public void performFstrimIfNeeded() {
6504        enforceSystemOrRoot("Only the system can request fstrim");
6505
6506        // Before everything else, see whether we need to fstrim.
6507        try {
6508            IMountService ms = PackageHelper.getMountService();
6509            if (ms != null) {
6510                final boolean isUpgrade = isUpgrade();
6511                boolean doTrim = isUpgrade;
6512                if (doTrim) {
6513                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6514                } else {
6515                    final long interval = android.provider.Settings.Global.getLong(
6516                            mContext.getContentResolver(),
6517                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6518                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6519                    if (interval > 0) {
6520                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6521                        if (timeSinceLast > interval) {
6522                            doTrim = true;
6523                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6524                                    + "; running immediately");
6525                        }
6526                    }
6527                }
6528                if (doTrim) {
6529                    if (!isFirstBoot()) {
6530                        try {
6531                            ActivityManagerNative.getDefault().showBootMessage(
6532                                    mContext.getResources().getString(
6533                                            R.string.android_upgrading_fstrim), true);
6534                        } catch (RemoteException e) {
6535                        }
6536                    }
6537                    ms.runMaintenance();
6538                }
6539            } else {
6540                Slog.e(TAG, "Mount service unavailable!");
6541            }
6542        } catch (RemoteException e) {
6543            // Can't happen; MountService is local
6544        }
6545    }
6546
6547    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6548        List<ResolveInfo> ris = null;
6549        try {
6550            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6551                    intent, null, 0, userId);
6552        } catch (RemoteException e) {
6553        }
6554        ArraySet<String> pkgNames = new ArraySet<String>();
6555        if (ris != null) {
6556            for (ResolveInfo ri : ris) {
6557                pkgNames.add(ri.activityInfo.packageName);
6558            }
6559        }
6560        return pkgNames;
6561    }
6562
6563    @Override
6564    public void notifyPackageUse(String packageName) {
6565        synchronized (mPackages) {
6566            PackageParser.Package p = mPackages.get(packageName);
6567            if (p == null) {
6568                return;
6569            }
6570            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6571        }
6572    }
6573
6574    @Override
6575    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6576        return performDexOptTraced(packageName, instructionSet);
6577    }
6578
6579    public boolean performDexOpt(String packageName, String instructionSet) {
6580        return performDexOptTraced(packageName, instructionSet);
6581    }
6582
6583    private boolean performDexOptTraced(String packageName, String instructionSet) {
6584        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6585        try {
6586            return performDexOptInternal(packageName, instructionSet);
6587        } finally {
6588            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6589        }
6590    }
6591
6592    private boolean performDexOptInternal(String packageName, String instructionSet) {
6593        PackageParser.Package p;
6594        final String targetInstructionSet;
6595        synchronized (mPackages) {
6596            p = mPackages.get(packageName);
6597            if (p == null) {
6598                return false;
6599            }
6600            mPackageUsage.write(false);
6601
6602            targetInstructionSet = instructionSet != null ? instructionSet :
6603                    getPrimaryInstructionSet(p.applicationInfo);
6604            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6605                return false;
6606            }
6607        }
6608        long callingId = Binder.clearCallingIdentity();
6609        try {
6610            synchronized (mInstallLock) {
6611                final String[] instructionSets = new String[] { targetInstructionSet };
6612                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6613                        true /* inclDependencies */);
6614                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6615            }
6616        } finally {
6617            Binder.restoreCallingIdentity(callingId);
6618        }
6619    }
6620
6621    public ArraySet<String> getPackagesThatNeedDexOpt() {
6622        ArraySet<String> pkgs = null;
6623        synchronized (mPackages) {
6624            for (PackageParser.Package p : mPackages.values()) {
6625                if (DEBUG_DEXOPT) {
6626                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6627                }
6628                if (!p.mDexOptPerformed.isEmpty()) {
6629                    continue;
6630                }
6631                if (pkgs == null) {
6632                    pkgs = new ArraySet<String>();
6633                }
6634                pkgs.add(p.packageName);
6635            }
6636        }
6637        return pkgs;
6638    }
6639
6640    public void shutdown() {
6641        mPackageUsage.write(true);
6642    }
6643
6644    @Override
6645    public void forceDexOpt(String packageName) {
6646        enforceSystemOrRoot("forceDexOpt");
6647
6648        PackageParser.Package pkg;
6649        synchronized (mPackages) {
6650            pkg = mPackages.get(packageName);
6651            if (pkg == null) {
6652                throw new IllegalArgumentException("Missing package: " + packageName);
6653            }
6654        }
6655
6656        synchronized (mInstallLock) {
6657            final String[] instructionSets = new String[] {
6658                    getPrimaryInstructionSet(pkg.applicationInfo) };
6659
6660            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6661
6662            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6663                    true /* inclDependencies */);
6664
6665            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6666            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6667                throw new IllegalStateException("Failed to dexopt: " + res);
6668            }
6669        }
6670    }
6671
6672    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6673        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6674            Slog.w(TAG, "Unable to update from " + oldPkg.name
6675                    + " to " + newPkg.packageName
6676                    + ": old package not in system partition");
6677            return false;
6678        } else if (mPackages.get(oldPkg.name) != null) {
6679            Slog.w(TAG, "Unable to update from " + oldPkg.name
6680                    + " to " + newPkg.packageName
6681                    + ": old package still exists");
6682            return false;
6683        }
6684        return true;
6685    }
6686
6687    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6688            throws PackageManagerException {
6689        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6690        if (res != 0) {
6691            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6692                    "Failed to install " + packageName + ": " + res);
6693        }
6694
6695        final int[] users = sUserManager.getUserIds();
6696        for (int user : users) {
6697            if (user != 0) {
6698                res = mInstaller.createUserData(volumeUuid, packageName,
6699                        UserHandle.getUid(user, uid), user, seinfo);
6700                if (res != 0) {
6701                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6702                            "Failed to createUserData " + packageName + ": " + res);
6703                }
6704            }
6705        }
6706    }
6707
6708    private int removeDataDirsLI(String volumeUuid, String packageName) {
6709        int[] users = sUserManager.getUserIds();
6710        int res = 0;
6711        for (int user : users) {
6712            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6713            if (resInner < 0) {
6714                res = resInner;
6715            }
6716        }
6717
6718        return res;
6719    }
6720
6721    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6722        int[] users = sUserManager.getUserIds();
6723        int res = 0;
6724        for (int user : users) {
6725            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6726            if (resInner < 0) {
6727                res = resInner;
6728            }
6729        }
6730        return res;
6731    }
6732
6733    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6734            PackageParser.Package changingLib) {
6735        if (file.path != null) {
6736            usesLibraryFiles.add(file.path);
6737            return;
6738        }
6739        PackageParser.Package p = mPackages.get(file.apk);
6740        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6741            // If we are doing this while in the middle of updating a library apk,
6742            // then we need to make sure to use that new apk for determining the
6743            // dependencies here.  (We haven't yet finished committing the new apk
6744            // to the package manager state.)
6745            if (p == null || p.packageName.equals(changingLib.packageName)) {
6746                p = changingLib;
6747            }
6748        }
6749        if (p != null) {
6750            usesLibraryFiles.addAll(p.getAllCodePaths());
6751        }
6752    }
6753
6754    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6755            PackageParser.Package changingLib) throws PackageManagerException {
6756        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6757            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6758            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6759            for (int i=0; i<N; i++) {
6760                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6761                if (file == null) {
6762                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6763                            "Package " + pkg.packageName + " requires unavailable shared library "
6764                            + pkg.usesLibraries.get(i) + "; failing!");
6765                }
6766                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6767            }
6768            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6769            for (int i=0; i<N; i++) {
6770                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6771                if (file == null) {
6772                    Slog.w(TAG, "Package " + pkg.packageName
6773                            + " desires unavailable shared library "
6774                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6775                } else {
6776                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6777                }
6778            }
6779            N = usesLibraryFiles.size();
6780            if (N > 0) {
6781                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6782            } else {
6783                pkg.usesLibraryFiles = null;
6784            }
6785        }
6786    }
6787
6788    private static boolean hasString(List<String> list, List<String> which) {
6789        if (list == null) {
6790            return false;
6791        }
6792        for (int i=list.size()-1; i>=0; i--) {
6793            for (int j=which.size()-1; j>=0; j--) {
6794                if (which.get(j).equals(list.get(i))) {
6795                    return true;
6796                }
6797            }
6798        }
6799        return false;
6800    }
6801
6802    private void updateAllSharedLibrariesLPw() {
6803        for (PackageParser.Package pkg : mPackages.values()) {
6804            try {
6805                updateSharedLibrariesLPw(pkg, null);
6806            } catch (PackageManagerException e) {
6807                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6808            }
6809        }
6810    }
6811
6812    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6813            PackageParser.Package changingPkg) {
6814        ArrayList<PackageParser.Package> res = null;
6815        for (PackageParser.Package pkg : mPackages.values()) {
6816            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6817                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6818                if (res == null) {
6819                    res = new ArrayList<PackageParser.Package>();
6820                }
6821                res.add(pkg);
6822                try {
6823                    updateSharedLibrariesLPw(pkg, changingPkg);
6824                } catch (PackageManagerException e) {
6825                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6826                }
6827            }
6828        }
6829        return res;
6830    }
6831
6832    /**
6833     * Derive the value of the {@code cpuAbiOverride} based on the provided
6834     * value and an optional stored value from the package settings.
6835     */
6836    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6837        String cpuAbiOverride = null;
6838
6839        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6840            cpuAbiOverride = null;
6841        } else if (abiOverride != null) {
6842            cpuAbiOverride = abiOverride;
6843        } else if (settings != null) {
6844            cpuAbiOverride = settings.cpuAbiOverrideString;
6845        }
6846
6847        return cpuAbiOverride;
6848    }
6849
6850    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6851            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6852        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6853        try {
6854            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6855        } finally {
6856            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6857        }
6858    }
6859
6860    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6861            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6862        boolean success = false;
6863        try {
6864            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6865                    currentTime, user);
6866            success = true;
6867            return res;
6868        } finally {
6869            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6870                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6871            }
6872        }
6873    }
6874
6875    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6876            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6877        final File scanFile = new File(pkg.codePath);
6878        if (pkg.applicationInfo.getCodePath() == null ||
6879                pkg.applicationInfo.getResourcePath() == null) {
6880            // Bail out. The resource and code paths haven't been set.
6881            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6882                    "Code and resource paths haven't been set correctly");
6883        }
6884
6885        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6886            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6887        } else {
6888            // Only allow system apps to be flagged as core apps.
6889            pkg.coreApp = false;
6890        }
6891
6892        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6893            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6894        }
6895
6896        if (mCustomResolverComponentName != null &&
6897                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6898            setUpCustomResolverActivity(pkg);
6899        }
6900
6901        if (pkg.packageName.equals("android")) {
6902            synchronized (mPackages) {
6903                if (mAndroidApplication != null) {
6904                    Slog.w(TAG, "*************************************************");
6905                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6906                    Slog.w(TAG, " file=" + scanFile);
6907                    Slog.w(TAG, "*************************************************");
6908                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6909                            "Core android package being redefined.  Skipping.");
6910                }
6911
6912                // Set up information for our fall-back user intent resolution activity.
6913                mPlatformPackage = pkg;
6914                pkg.mVersionCode = mSdkVersion;
6915                mAndroidApplication = pkg.applicationInfo;
6916
6917                if (!mResolverReplaced) {
6918                    mResolveActivity.applicationInfo = mAndroidApplication;
6919                    mResolveActivity.name = ResolverActivity.class.getName();
6920                    mResolveActivity.packageName = mAndroidApplication.packageName;
6921                    mResolveActivity.processName = "system:ui";
6922                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6923                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6924                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6925                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6926                    mResolveActivity.exported = true;
6927                    mResolveActivity.enabled = true;
6928                    mResolveInfo.activityInfo = mResolveActivity;
6929                    mResolveInfo.priority = 0;
6930                    mResolveInfo.preferredOrder = 0;
6931                    mResolveInfo.match = 0;
6932                    mResolveComponentName = new ComponentName(
6933                            mAndroidApplication.packageName, mResolveActivity.name);
6934                }
6935            }
6936        }
6937
6938        if (DEBUG_PACKAGE_SCANNING) {
6939            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6940                Log.d(TAG, "Scanning package " + pkg.packageName);
6941        }
6942
6943        if (mPackages.containsKey(pkg.packageName)
6944                || mSharedLibraries.containsKey(pkg.packageName)) {
6945            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6946                    "Application package " + pkg.packageName
6947                    + " already installed.  Skipping duplicate.");
6948        }
6949
6950        // If we're only installing presumed-existing packages, require that the
6951        // scanned APK is both already known and at the path previously established
6952        // for it.  Previously unknown packages we pick up normally, but if we have an
6953        // a priori expectation about this package's install presence, enforce it.
6954        // With a singular exception for new system packages. When an OTA contains
6955        // a new system package, we allow the codepath to change from a system location
6956        // to the user-installed location. If we don't allow this change, any newer,
6957        // user-installed version of the application will be ignored.
6958        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6959            if (mExpectingBetter.containsKey(pkg.packageName)) {
6960                logCriticalInfo(Log.WARN,
6961                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6962            } else {
6963                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6964                if (known != null) {
6965                    if (DEBUG_PACKAGE_SCANNING) {
6966                        Log.d(TAG, "Examining " + pkg.codePath
6967                                + " and requiring known paths " + known.codePathString
6968                                + " & " + known.resourcePathString);
6969                    }
6970                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6971                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6972                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6973                                "Application package " + pkg.packageName
6974                                + " found at " + pkg.applicationInfo.getCodePath()
6975                                + " but expected at " + known.codePathString + "; ignoring.");
6976                    }
6977                }
6978            }
6979        }
6980
6981        // Initialize package source and resource directories
6982        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6983        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6984
6985        SharedUserSetting suid = null;
6986        PackageSetting pkgSetting = null;
6987
6988        if (!isSystemApp(pkg)) {
6989            // Only system apps can use these features.
6990            pkg.mOriginalPackages = null;
6991            pkg.mRealPackage = null;
6992            pkg.mAdoptPermissions = null;
6993        }
6994
6995        // writer
6996        synchronized (mPackages) {
6997            if (pkg.mSharedUserId != null) {
6998                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6999                if (suid == null) {
7000                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7001                            "Creating application package " + pkg.packageName
7002                            + " for shared user failed");
7003                }
7004                if (DEBUG_PACKAGE_SCANNING) {
7005                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7006                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7007                                + "): packages=" + suid.packages);
7008                }
7009            }
7010
7011            // Check if we are renaming from an original package name.
7012            PackageSetting origPackage = null;
7013            String realName = null;
7014            if (pkg.mOriginalPackages != null) {
7015                // This package may need to be renamed to a previously
7016                // installed name.  Let's check on that...
7017                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7018                if (pkg.mOriginalPackages.contains(renamed)) {
7019                    // This package had originally been installed as the
7020                    // original name, and we have already taken care of
7021                    // transitioning to the new one.  Just update the new
7022                    // one to continue using the old name.
7023                    realName = pkg.mRealPackage;
7024                    if (!pkg.packageName.equals(renamed)) {
7025                        // Callers into this function may have already taken
7026                        // care of renaming the package; only do it here if
7027                        // it is not already done.
7028                        pkg.setPackageName(renamed);
7029                    }
7030
7031                } else {
7032                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7033                        if ((origPackage = mSettings.peekPackageLPr(
7034                                pkg.mOriginalPackages.get(i))) != null) {
7035                            // We do have the package already installed under its
7036                            // original name...  should we use it?
7037                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7038                                // New package is not compatible with original.
7039                                origPackage = null;
7040                                continue;
7041                            } else if (origPackage.sharedUser != null) {
7042                                // Make sure uid is compatible between packages.
7043                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7044                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7045                                            + " to " + pkg.packageName + ": old uid "
7046                                            + origPackage.sharedUser.name
7047                                            + " differs from " + pkg.mSharedUserId);
7048                                    origPackage = null;
7049                                    continue;
7050                                }
7051                            } else {
7052                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7053                                        + pkg.packageName + " to old name " + origPackage.name);
7054                            }
7055                            break;
7056                        }
7057                    }
7058                }
7059            }
7060
7061            if (mTransferedPackages.contains(pkg.packageName)) {
7062                Slog.w(TAG, "Package " + pkg.packageName
7063                        + " was transferred to another, but its .apk remains");
7064            }
7065
7066            // Just create the setting, don't add it yet. For already existing packages
7067            // the PkgSetting exists already and doesn't have to be created.
7068            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7069                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7070                    pkg.applicationInfo.primaryCpuAbi,
7071                    pkg.applicationInfo.secondaryCpuAbi,
7072                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7073                    user, false);
7074            if (pkgSetting == null) {
7075                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7076                        "Creating application package " + pkg.packageName + " failed");
7077            }
7078
7079            if (pkgSetting.origPackage != null) {
7080                // If we are first transitioning from an original package,
7081                // fix up the new package's name now.  We need to do this after
7082                // looking up the package under its new name, so getPackageLP
7083                // can take care of fiddling things correctly.
7084                pkg.setPackageName(origPackage.name);
7085
7086                // File a report about this.
7087                String msg = "New package " + pkgSetting.realName
7088                        + " renamed to replace old package " + pkgSetting.name;
7089                reportSettingsProblem(Log.WARN, msg);
7090
7091                // Make a note of it.
7092                mTransferedPackages.add(origPackage.name);
7093
7094                // No longer need to retain this.
7095                pkgSetting.origPackage = null;
7096            }
7097
7098            if (realName != null) {
7099                // Make a note of it.
7100                mTransferedPackages.add(pkg.packageName);
7101            }
7102
7103            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7104                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7105            }
7106
7107            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7108                // Check all shared libraries and map to their actual file path.
7109                // We only do this here for apps not on a system dir, because those
7110                // are the only ones that can fail an install due to this.  We
7111                // will take care of the system apps by updating all of their
7112                // library paths after the scan is done.
7113                updateSharedLibrariesLPw(pkg, null);
7114            }
7115
7116            if (mFoundPolicyFile) {
7117                SELinuxMMAC.assignSeinfoValue(pkg);
7118            }
7119
7120            pkg.applicationInfo.uid = pkgSetting.appId;
7121            pkg.mExtras = pkgSetting;
7122            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7123                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7124                    // We just determined the app is signed correctly, so bring
7125                    // over the latest parsed certs.
7126                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7127                } else {
7128                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7129                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7130                                "Package " + pkg.packageName + " upgrade keys do not match the "
7131                                + "previously installed version");
7132                    } else {
7133                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7134                        String msg = "System package " + pkg.packageName
7135                            + " signature changed; retaining data.";
7136                        reportSettingsProblem(Log.WARN, msg);
7137                    }
7138                }
7139            } else {
7140                try {
7141                    verifySignaturesLP(pkgSetting, pkg);
7142                    // We just determined the app is signed correctly, so bring
7143                    // over the latest parsed certs.
7144                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7145                } catch (PackageManagerException e) {
7146                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7147                        throw e;
7148                    }
7149                    // The signature has changed, but this package is in the system
7150                    // image...  let's recover!
7151                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7152                    // However...  if this package is part of a shared user, but it
7153                    // doesn't match the signature of the shared user, let's fail.
7154                    // What this means is that you can't change the signatures
7155                    // associated with an overall shared user, which doesn't seem all
7156                    // that unreasonable.
7157                    if (pkgSetting.sharedUser != null) {
7158                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7159                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7160                            throw new PackageManagerException(
7161                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7162                                            "Signature mismatch for shared user : "
7163                                            + pkgSetting.sharedUser);
7164                        }
7165                    }
7166                    // File a report about this.
7167                    String msg = "System package " + pkg.packageName
7168                        + " signature changed; retaining data.";
7169                    reportSettingsProblem(Log.WARN, msg);
7170                }
7171            }
7172            // Verify that this new package doesn't have any content providers
7173            // that conflict with existing packages.  Only do this if the
7174            // package isn't already installed, since we don't want to break
7175            // things that are installed.
7176            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7177                final int N = pkg.providers.size();
7178                int i;
7179                for (i=0; i<N; i++) {
7180                    PackageParser.Provider p = pkg.providers.get(i);
7181                    if (p.info.authority != null) {
7182                        String names[] = p.info.authority.split(";");
7183                        for (int j = 0; j < names.length; j++) {
7184                            if (mProvidersByAuthority.containsKey(names[j])) {
7185                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7186                                final String otherPackageName =
7187                                        ((other != null && other.getComponentName() != null) ?
7188                                                other.getComponentName().getPackageName() : "?");
7189                                throw new PackageManagerException(
7190                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7191                                                "Can't install because provider name " + names[j]
7192                                                + " (in package " + pkg.applicationInfo.packageName
7193                                                + ") is already used by " + otherPackageName);
7194                            }
7195                        }
7196                    }
7197                }
7198            }
7199
7200            if (pkg.mAdoptPermissions != null) {
7201                // This package wants to adopt ownership of permissions from
7202                // another package.
7203                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7204                    final String origName = pkg.mAdoptPermissions.get(i);
7205                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7206                    if (orig != null) {
7207                        if (verifyPackageUpdateLPr(orig, pkg)) {
7208                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7209                                    + pkg.packageName);
7210                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7211                        }
7212                    }
7213                }
7214            }
7215        }
7216
7217        final String pkgName = pkg.packageName;
7218
7219        final long scanFileTime = scanFile.lastModified();
7220        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7221        pkg.applicationInfo.processName = fixProcessName(
7222                pkg.applicationInfo.packageName,
7223                pkg.applicationInfo.processName,
7224                pkg.applicationInfo.uid);
7225
7226        if (pkg != mPlatformPackage) {
7227            // This is a normal package, need to make its data directory.
7228            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7229                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7230
7231            boolean uidError = false;
7232            if (dataPath.exists()) {
7233                int currentUid = 0;
7234                try {
7235                    StructStat stat = Os.stat(dataPath.getPath());
7236                    currentUid = stat.st_uid;
7237                } catch (ErrnoException e) {
7238                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7239                }
7240
7241                // If we have mismatched owners for the data path, we have a problem.
7242                if (currentUid != pkg.applicationInfo.uid) {
7243                    boolean recovered = false;
7244                    if (currentUid == 0) {
7245                        // The directory somehow became owned by root.  Wow.
7246                        // This is probably because the system was stopped while
7247                        // installd was in the middle of messing with its libs
7248                        // directory.  Ask installd to fix that.
7249                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7250                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7251                        if (ret >= 0) {
7252                            recovered = true;
7253                            String msg = "Package " + pkg.packageName
7254                                    + " unexpectedly changed to uid 0; recovered to " +
7255                                    + pkg.applicationInfo.uid;
7256                            reportSettingsProblem(Log.WARN, msg);
7257                        }
7258                    }
7259                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7260                            || (scanFlags&SCAN_BOOTING) != 0)) {
7261                        // If this is a system app, we can at least delete its
7262                        // current data so the application will still work.
7263                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7264                        if (ret >= 0) {
7265                            // TODO: Kill the processes first
7266                            // Old data gone!
7267                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7268                                    ? "System package " : "Third party package ";
7269                            String msg = prefix + pkg.packageName
7270                                    + " has changed from uid: "
7271                                    + currentUid + " to "
7272                                    + pkg.applicationInfo.uid + "; old data erased";
7273                            reportSettingsProblem(Log.WARN, msg);
7274                            recovered = true;
7275                        }
7276                        if (!recovered) {
7277                            mHasSystemUidErrors = true;
7278                        }
7279                    } else if (!recovered) {
7280                        // If we allow this install to proceed, we will be broken.
7281                        // Abort, abort!
7282                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7283                                "scanPackageLI");
7284                    }
7285                    if (!recovered) {
7286                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7287                            + pkg.applicationInfo.uid + "/fs_"
7288                            + currentUid;
7289                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7290                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7291                        String msg = "Package " + pkg.packageName
7292                                + " has mismatched uid: "
7293                                + currentUid + " on disk, "
7294                                + pkg.applicationInfo.uid + " in settings";
7295                        // writer
7296                        synchronized (mPackages) {
7297                            mSettings.mReadMessages.append(msg);
7298                            mSettings.mReadMessages.append('\n');
7299                            uidError = true;
7300                            if (!pkgSetting.uidError) {
7301                                reportSettingsProblem(Log.ERROR, msg);
7302                            }
7303                        }
7304                    }
7305                }
7306
7307                // Ensure that directories are prepared
7308                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7309                        pkg.applicationInfo.seinfo);
7310
7311                if (mShouldRestoreconData) {
7312                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7313                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7314                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7315                }
7316            } else {
7317                if (DEBUG_PACKAGE_SCANNING) {
7318                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7319                        Log.v(TAG, "Want this data dir: " + dataPath);
7320                }
7321                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7322                        pkg.applicationInfo.seinfo);
7323            }
7324
7325            // Get all of our default paths setup
7326            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7327
7328            pkgSetting.uidError = uidError;
7329        }
7330
7331        final String path = scanFile.getPath();
7332        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7333
7334        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7335            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7336
7337            // Some system apps still use directory structure for native libraries
7338            // in which case we might end up not detecting abi solely based on apk
7339            // structure. Try to detect abi based on directory structure.
7340            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7341                    pkg.applicationInfo.primaryCpuAbi == null) {
7342                setBundledAppAbisAndRoots(pkg, pkgSetting);
7343                setNativeLibraryPaths(pkg);
7344            }
7345
7346        } else {
7347            if ((scanFlags & SCAN_MOVE) != 0) {
7348                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7349                // but we already have this packages package info in the PackageSetting. We just
7350                // use that and derive the native library path based on the new codepath.
7351                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7352                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7353            }
7354
7355            // Set native library paths again. For moves, the path will be updated based on the
7356            // ABIs we've determined above. For non-moves, the path will be updated based on the
7357            // ABIs we determined during compilation, but the path will depend on the final
7358            // package path (after the rename away from the stage path).
7359            setNativeLibraryPaths(pkg);
7360        }
7361
7362        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7363        final int[] userIds = sUserManager.getUserIds();
7364        synchronized (mInstallLock) {
7365            // Make sure all user data directories are ready to roll; we're okay
7366            // if they already exist
7367            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7368                for (int userId : userIds) {
7369                    if (userId != UserHandle.USER_SYSTEM) {
7370                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7371                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7372                                pkg.applicationInfo.seinfo);
7373                    }
7374                }
7375            }
7376
7377            // Create a native library symlink only if we have native libraries
7378            // and if the native libraries are 32 bit libraries. We do not provide
7379            // this symlink for 64 bit libraries.
7380            if (pkg.applicationInfo.primaryCpuAbi != null &&
7381                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7382                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7383                try {
7384                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7385                    for (int userId : userIds) {
7386                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7387                                nativeLibPath, userId) < 0) {
7388                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7389                                    "Failed linking native library dir (user=" + userId + ")");
7390                        }
7391                    }
7392                } finally {
7393                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7394                }
7395            }
7396        }
7397
7398        // This is a special case for the "system" package, where the ABI is
7399        // dictated by the zygote configuration (and init.rc). We should keep track
7400        // of this ABI so that we can deal with "normal" applications that run under
7401        // the same UID correctly.
7402        if (mPlatformPackage == pkg) {
7403            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7404                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7405        }
7406
7407        // If there's a mismatch between the abi-override in the package setting
7408        // and the abiOverride specified for the install. Warn about this because we
7409        // would've already compiled the app without taking the package setting into
7410        // account.
7411        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7412            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7413                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7414                        " for package: " + pkg.packageName);
7415            }
7416        }
7417
7418        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7419        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7420        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7421
7422        // Copy the derived override back to the parsed package, so that we can
7423        // update the package settings accordingly.
7424        pkg.cpuAbiOverride = cpuAbiOverride;
7425
7426        if (DEBUG_ABI_SELECTION) {
7427            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7428                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7429                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7430        }
7431
7432        // Push the derived path down into PackageSettings so we know what to
7433        // clean up at uninstall time.
7434        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7435
7436        if (DEBUG_ABI_SELECTION) {
7437            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7438                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7439                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7440        }
7441
7442        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7443            // We don't do this here during boot because we can do it all
7444            // at once after scanning all existing packages.
7445            //
7446            // We also do this *before* we perform dexopt on this package, so that
7447            // we can avoid redundant dexopts, and also to make sure we've got the
7448            // code and package path correct.
7449            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7450                    pkg, true /* boot complete */);
7451        }
7452
7453        if (mFactoryTest && pkg.requestedPermissions.contains(
7454                android.Manifest.permission.FACTORY_TEST)) {
7455            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7456        }
7457
7458        ArrayList<PackageParser.Package> clientLibPkgs = null;
7459
7460        // writer
7461        synchronized (mPackages) {
7462            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7463                // Only system apps can add new shared libraries.
7464                if (pkg.libraryNames != null) {
7465                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7466                        String name = pkg.libraryNames.get(i);
7467                        boolean allowed = false;
7468                        if (pkg.isUpdatedSystemApp()) {
7469                            // New library entries can only be added through the
7470                            // system image.  This is important to get rid of a lot
7471                            // of nasty edge cases: for example if we allowed a non-
7472                            // system update of the app to add a library, then uninstalling
7473                            // the update would make the library go away, and assumptions
7474                            // we made such as through app install filtering would now
7475                            // have allowed apps on the device which aren't compatible
7476                            // with it.  Better to just have the restriction here, be
7477                            // conservative, and create many fewer cases that can negatively
7478                            // impact the user experience.
7479                            final PackageSetting sysPs = mSettings
7480                                    .getDisabledSystemPkgLPr(pkg.packageName);
7481                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7482                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7483                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7484                                        allowed = true;
7485                                        break;
7486                                    }
7487                                }
7488                            }
7489                        } else {
7490                            allowed = true;
7491                        }
7492                        if (allowed) {
7493                            if (!mSharedLibraries.containsKey(name)) {
7494                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7495                            } else if (!name.equals(pkg.packageName)) {
7496                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7497                                        + name + " already exists; skipping");
7498                            }
7499                        } else {
7500                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7501                                    + name + " that is not declared on system image; skipping");
7502                        }
7503                    }
7504                    if ((scanFlags & SCAN_BOOTING) == 0) {
7505                        // If we are not booting, we need to update any applications
7506                        // that are clients of our shared library.  If we are booting,
7507                        // this will all be done once the scan is complete.
7508                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7509                    }
7510                }
7511            }
7512        }
7513
7514        // Request the ActivityManager to kill the process(only for existing packages)
7515        // so that we do not end up in a confused state while the user is still using the older
7516        // version of the application while the new one gets installed.
7517        if ((scanFlags & SCAN_REPLACING) != 0) {
7518            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7519
7520            killApplication(pkg.applicationInfo.packageName,
7521                        pkg.applicationInfo.uid, "replace pkg");
7522
7523            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7524        }
7525
7526        // Also need to kill any apps that are dependent on the library.
7527        if (clientLibPkgs != null) {
7528            for (int i=0; i<clientLibPkgs.size(); i++) {
7529                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7530                killApplication(clientPkg.applicationInfo.packageName,
7531                        clientPkg.applicationInfo.uid, "update lib");
7532            }
7533        }
7534
7535        // Make sure we're not adding any bogus keyset info
7536        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7537        ksms.assertScannedPackageValid(pkg);
7538
7539        // writer
7540        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7541
7542        boolean createIdmapFailed = false;
7543        synchronized (mPackages) {
7544            // We don't expect installation to fail beyond this point
7545
7546            // Add the new setting to mSettings
7547            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7548            // Add the new setting to mPackages
7549            mPackages.put(pkg.applicationInfo.packageName, pkg);
7550            // Make sure we don't accidentally delete its data.
7551            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7552            while (iter.hasNext()) {
7553                PackageCleanItem item = iter.next();
7554                if (pkgName.equals(item.packageName)) {
7555                    iter.remove();
7556                }
7557            }
7558
7559            // Take care of first install / last update times.
7560            if (currentTime != 0) {
7561                if (pkgSetting.firstInstallTime == 0) {
7562                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7563                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7564                    pkgSetting.lastUpdateTime = currentTime;
7565                }
7566            } else if (pkgSetting.firstInstallTime == 0) {
7567                // We need *something*.  Take time time stamp of the file.
7568                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7569            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7570                if (scanFileTime != pkgSetting.timeStamp) {
7571                    // A package on the system image has changed; consider this
7572                    // to be an update.
7573                    pkgSetting.lastUpdateTime = scanFileTime;
7574                }
7575            }
7576
7577            // Add the package's KeySets to the global KeySetManagerService
7578            ksms.addScannedPackageLPw(pkg);
7579
7580            int N = pkg.providers.size();
7581            StringBuilder r = null;
7582            int i;
7583            for (i=0; i<N; i++) {
7584                PackageParser.Provider p = pkg.providers.get(i);
7585                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7586                        p.info.processName, pkg.applicationInfo.uid);
7587                mProviders.addProvider(p);
7588                p.syncable = p.info.isSyncable;
7589                if (p.info.authority != null) {
7590                    String names[] = p.info.authority.split(";");
7591                    p.info.authority = null;
7592                    for (int j = 0; j < names.length; j++) {
7593                        if (j == 1 && p.syncable) {
7594                            // We only want the first authority for a provider to possibly be
7595                            // syncable, so if we already added this provider using a different
7596                            // authority clear the syncable flag. We copy the provider before
7597                            // changing it because the mProviders object contains a reference
7598                            // to a provider that we don't want to change.
7599                            // Only do this for the second authority since the resulting provider
7600                            // object can be the same for all future authorities for this provider.
7601                            p = new PackageParser.Provider(p);
7602                            p.syncable = false;
7603                        }
7604                        if (!mProvidersByAuthority.containsKey(names[j])) {
7605                            mProvidersByAuthority.put(names[j], p);
7606                            if (p.info.authority == null) {
7607                                p.info.authority = names[j];
7608                            } else {
7609                                p.info.authority = p.info.authority + ";" + names[j];
7610                            }
7611                            if (DEBUG_PACKAGE_SCANNING) {
7612                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7613                                    Log.d(TAG, "Registered content provider: " + names[j]
7614                                            + ", className = " + p.info.name + ", isSyncable = "
7615                                            + p.info.isSyncable);
7616                            }
7617                        } else {
7618                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7619                            Slog.w(TAG, "Skipping provider name " + names[j] +
7620                                    " (in package " + pkg.applicationInfo.packageName +
7621                                    "): name already used by "
7622                                    + ((other != null && other.getComponentName() != null)
7623                                            ? other.getComponentName().getPackageName() : "?"));
7624                        }
7625                    }
7626                }
7627                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7628                    if (r == null) {
7629                        r = new StringBuilder(256);
7630                    } else {
7631                        r.append(' ');
7632                    }
7633                    r.append(p.info.name);
7634                }
7635            }
7636            if (r != null) {
7637                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7638            }
7639
7640            N = pkg.services.size();
7641            r = null;
7642            for (i=0; i<N; i++) {
7643                PackageParser.Service s = pkg.services.get(i);
7644                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7645                        s.info.processName, pkg.applicationInfo.uid);
7646                mServices.addService(s);
7647                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7648                    if (r == null) {
7649                        r = new StringBuilder(256);
7650                    } else {
7651                        r.append(' ');
7652                    }
7653                    r.append(s.info.name);
7654                }
7655            }
7656            if (r != null) {
7657                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7658            }
7659
7660            N = pkg.receivers.size();
7661            r = null;
7662            for (i=0; i<N; i++) {
7663                PackageParser.Activity a = pkg.receivers.get(i);
7664                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7665                        a.info.processName, pkg.applicationInfo.uid);
7666                mReceivers.addActivity(a, "receiver");
7667                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7668                    if (r == null) {
7669                        r = new StringBuilder(256);
7670                    } else {
7671                        r.append(' ');
7672                    }
7673                    r.append(a.info.name);
7674                }
7675            }
7676            if (r != null) {
7677                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7678            }
7679
7680            N = pkg.activities.size();
7681            r = null;
7682            for (i=0; i<N; i++) {
7683                PackageParser.Activity a = pkg.activities.get(i);
7684                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7685                        a.info.processName, pkg.applicationInfo.uid);
7686                mActivities.addActivity(a, "activity");
7687                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7688                    if (r == null) {
7689                        r = new StringBuilder(256);
7690                    } else {
7691                        r.append(' ');
7692                    }
7693                    r.append(a.info.name);
7694                }
7695            }
7696            if (r != null) {
7697                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7698            }
7699
7700            N = pkg.permissionGroups.size();
7701            r = null;
7702            for (i=0; i<N; i++) {
7703                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7704                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7705                if (cur == null) {
7706                    mPermissionGroups.put(pg.info.name, pg);
7707                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7708                        if (r == null) {
7709                            r = new StringBuilder(256);
7710                        } else {
7711                            r.append(' ');
7712                        }
7713                        r.append(pg.info.name);
7714                    }
7715                } else {
7716                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7717                            + pg.info.packageName + " ignored: original from "
7718                            + cur.info.packageName);
7719                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7720                        if (r == null) {
7721                            r = new StringBuilder(256);
7722                        } else {
7723                            r.append(' ');
7724                        }
7725                        r.append("DUP:");
7726                        r.append(pg.info.name);
7727                    }
7728                }
7729            }
7730            if (r != null) {
7731                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7732            }
7733
7734            N = pkg.permissions.size();
7735            r = null;
7736            for (i=0; i<N; i++) {
7737                PackageParser.Permission p = pkg.permissions.get(i);
7738
7739                // Assume by default that we did not install this permission into the system.
7740                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7741
7742                // Now that permission groups have a special meaning, we ignore permission
7743                // groups for legacy apps to prevent unexpected behavior. In particular,
7744                // permissions for one app being granted to someone just becuase they happen
7745                // to be in a group defined by another app (before this had no implications).
7746                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7747                    p.group = mPermissionGroups.get(p.info.group);
7748                    // Warn for a permission in an unknown group.
7749                    if (p.info.group != null && p.group == null) {
7750                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7751                                + p.info.packageName + " in an unknown group " + p.info.group);
7752                    }
7753                }
7754
7755                ArrayMap<String, BasePermission> permissionMap =
7756                        p.tree ? mSettings.mPermissionTrees
7757                                : mSettings.mPermissions;
7758                BasePermission bp = permissionMap.get(p.info.name);
7759
7760                // Allow system apps to redefine non-system permissions
7761                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7762                    final boolean currentOwnerIsSystem = (bp.perm != null
7763                            && isSystemApp(bp.perm.owner));
7764                    if (isSystemApp(p.owner)) {
7765                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7766                            // It's a built-in permission and no owner, take ownership now
7767                            bp.packageSetting = pkgSetting;
7768                            bp.perm = p;
7769                            bp.uid = pkg.applicationInfo.uid;
7770                            bp.sourcePackage = p.info.packageName;
7771                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7772                        } else if (!currentOwnerIsSystem) {
7773                            String msg = "New decl " + p.owner + " of permission  "
7774                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7775                            reportSettingsProblem(Log.WARN, msg);
7776                            bp = null;
7777                        }
7778                    }
7779                }
7780
7781                if (bp == null) {
7782                    bp = new BasePermission(p.info.name, p.info.packageName,
7783                            BasePermission.TYPE_NORMAL);
7784                    permissionMap.put(p.info.name, bp);
7785                }
7786
7787                if (bp.perm == null) {
7788                    if (bp.sourcePackage == null
7789                            || bp.sourcePackage.equals(p.info.packageName)) {
7790                        BasePermission tree = findPermissionTreeLP(p.info.name);
7791                        if (tree == null
7792                                || tree.sourcePackage.equals(p.info.packageName)) {
7793                            bp.packageSetting = pkgSetting;
7794                            bp.perm = p;
7795                            bp.uid = pkg.applicationInfo.uid;
7796                            bp.sourcePackage = p.info.packageName;
7797                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7798                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7799                                if (r == null) {
7800                                    r = new StringBuilder(256);
7801                                } else {
7802                                    r.append(' ');
7803                                }
7804                                r.append(p.info.name);
7805                            }
7806                        } else {
7807                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7808                                    + p.info.packageName + " ignored: base tree "
7809                                    + tree.name + " is from package "
7810                                    + tree.sourcePackage);
7811                        }
7812                    } else {
7813                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7814                                + p.info.packageName + " ignored: original from "
7815                                + bp.sourcePackage);
7816                    }
7817                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7818                    if (r == null) {
7819                        r = new StringBuilder(256);
7820                    } else {
7821                        r.append(' ');
7822                    }
7823                    r.append("DUP:");
7824                    r.append(p.info.name);
7825                }
7826                if (bp.perm == p) {
7827                    bp.protectionLevel = p.info.protectionLevel;
7828                }
7829            }
7830
7831            if (r != null) {
7832                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7833            }
7834
7835            N = pkg.instrumentation.size();
7836            r = null;
7837            for (i=0; i<N; i++) {
7838                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7839                a.info.packageName = pkg.applicationInfo.packageName;
7840                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7841                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7842                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7843                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7844                a.info.dataDir = pkg.applicationInfo.dataDir;
7845                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7846                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7847
7848                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7849                // need other information about the application, like the ABI and what not ?
7850                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7851                mInstrumentation.put(a.getComponentName(), a);
7852                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7853                    if (r == null) {
7854                        r = new StringBuilder(256);
7855                    } else {
7856                        r.append(' ');
7857                    }
7858                    r.append(a.info.name);
7859                }
7860            }
7861            if (r != null) {
7862                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7863            }
7864
7865            if (pkg.protectedBroadcasts != null) {
7866                N = pkg.protectedBroadcasts.size();
7867                for (i=0; i<N; i++) {
7868                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7869                }
7870            }
7871
7872            pkgSetting.setTimeStamp(scanFileTime);
7873
7874            // Create idmap files for pairs of (packages, overlay packages).
7875            // Note: "android", ie framework-res.apk, is handled by native layers.
7876            if (pkg.mOverlayTarget != null) {
7877                // This is an overlay package.
7878                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7879                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7880                        mOverlays.put(pkg.mOverlayTarget,
7881                                new ArrayMap<String, PackageParser.Package>());
7882                    }
7883                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7884                    map.put(pkg.packageName, pkg);
7885                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7886                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7887                        createIdmapFailed = true;
7888                    }
7889                }
7890            } else if (mOverlays.containsKey(pkg.packageName) &&
7891                    !pkg.packageName.equals("android")) {
7892                // This is a regular package, with one or more known overlay packages.
7893                createIdmapsForPackageLI(pkg);
7894            }
7895        }
7896
7897        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7898
7899        if (createIdmapFailed) {
7900            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7901                    "scanPackageLI failed to createIdmap");
7902        }
7903        return pkg;
7904    }
7905
7906    /**
7907     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7908     * is derived purely on the basis of the contents of {@code scanFile} and
7909     * {@code cpuAbiOverride}.
7910     *
7911     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7912     */
7913    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7914                                 String cpuAbiOverride, boolean extractLibs)
7915            throws PackageManagerException {
7916        // TODO: We can probably be smarter about this stuff. For installed apps,
7917        // we can calculate this information at install time once and for all. For
7918        // system apps, we can probably assume that this information doesn't change
7919        // after the first boot scan. As things stand, we do lots of unnecessary work.
7920
7921        // Give ourselves some initial paths; we'll come back for another
7922        // pass once we've determined ABI below.
7923        setNativeLibraryPaths(pkg);
7924
7925        // We would never need to extract libs for forward-locked and external packages,
7926        // since the container service will do it for us. We shouldn't attempt to
7927        // extract libs from system app when it was not updated.
7928        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7929                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7930            extractLibs = false;
7931        }
7932
7933        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7934        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7935
7936        NativeLibraryHelper.Handle handle = null;
7937        try {
7938            handle = NativeLibraryHelper.Handle.create(pkg);
7939            // TODO(multiArch): This can be null for apps that didn't go through the
7940            // usual installation process. We can calculate it again, like we
7941            // do during install time.
7942            //
7943            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7944            // unnecessary.
7945            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7946
7947            // Null out the abis so that they can be recalculated.
7948            pkg.applicationInfo.primaryCpuAbi = null;
7949            pkg.applicationInfo.secondaryCpuAbi = null;
7950            if (isMultiArch(pkg.applicationInfo)) {
7951                // Warn if we've set an abiOverride for multi-lib packages..
7952                // By definition, we need to copy both 32 and 64 bit libraries for
7953                // such packages.
7954                if (pkg.cpuAbiOverride != null
7955                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7956                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7957                }
7958
7959                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7960                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7961                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7962                    if (extractLibs) {
7963                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7964                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7965                                useIsaSpecificSubdirs);
7966                    } else {
7967                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7968                    }
7969                }
7970
7971                maybeThrowExceptionForMultiArchCopy(
7972                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7973
7974                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7975                    if (extractLibs) {
7976                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7977                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7978                                useIsaSpecificSubdirs);
7979                    } else {
7980                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7981                    }
7982                }
7983
7984                maybeThrowExceptionForMultiArchCopy(
7985                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7986
7987                if (abi64 >= 0) {
7988                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7989                }
7990
7991                if (abi32 >= 0) {
7992                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7993                    if (abi64 >= 0) {
7994                        pkg.applicationInfo.secondaryCpuAbi = abi;
7995                    } else {
7996                        pkg.applicationInfo.primaryCpuAbi = abi;
7997                    }
7998                }
7999            } else {
8000                String[] abiList = (cpuAbiOverride != null) ?
8001                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8002
8003                // Enable gross and lame hacks for apps that are built with old
8004                // SDK tools. We must scan their APKs for renderscript bitcode and
8005                // not launch them if it's present. Don't bother checking on devices
8006                // that don't have 64 bit support.
8007                boolean needsRenderScriptOverride = false;
8008                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8009                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8010                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8011                    needsRenderScriptOverride = true;
8012                }
8013
8014                final int copyRet;
8015                if (extractLibs) {
8016                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8017                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8018                } else {
8019                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8020                }
8021
8022                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8023                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8024                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8025                }
8026
8027                if (copyRet >= 0) {
8028                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8029                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8030                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8031                } else if (needsRenderScriptOverride) {
8032                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8033                }
8034            }
8035        } catch (IOException ioe) {
8036            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8037        } finally {
8038            IoUtils.closeQuietly(handle);
8039        }
8040
8041        // Now that we've calculated the ABIs and determined if it's an internal app,
8042        // we will go ahead and populate the nativeLibraryPath.
8043        setNativeLibraryPaths(pkg);
8044    }
8045
8046    /**
8047     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8048     * i.e, so that all packages can be run inside a single process if required.
8049     *
8050     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8051     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8052     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8053     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8054     * updating a package that belongs to a shared user.
8055     *
8056     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8057     * adds unnecessary complexity.
8058     */
8059    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8060            PackageParser.Package scannedPackage, boolean bootComplete) {
8061        String requiredInstructionSet = null;
8062        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8063            requiredInstructionSet = VMRuntime.getInstructionSet(
8064                     scannedPackage.applicationInfo.primaryCpuAbi);
8065        }
8066
8067        PackageSetting requirer = null;
8068        for (PackageSetting ps : packagesForUser) {
8069            // If packagesForUser contains scannedPackage, we skip it. This will happen
8070            // when scannedPackage is an update of an existing package. Without this check,
8071            // we will never be able to change the ABI of any package belonging to a shared
8072            // user, even if it's compatible with other packages.
8073            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8074                if (ps.primaryCpuAbiString == null) {
8075                    continue;
8076                }
8077
8078                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8079                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8080                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8081                    // this but there's not much we can do.
8082                    String errorMessage = "Instruction set mismatch, "
8083                            + ((requirer == null) ? "[caller]" : requirer)
8084                            + " requires " + requiredInstructionSet + " whereas " + ps
8085                            + " requires " + instructionSet;
8086                    Slog.w(TAG, errorMessage);
8087                }
8088
8089                if (requiredInstructionSet == null) {
8090                    requiredInstructionSet = instructionSet;
8091                    requirer = ps;
8092                }
8093            }
8094        }
8095
8096        if (requiredInstructionSet != null) {
8097            String adjustedAbi;
8098            if (requirer != null) {
8099                // requirer != null implies that either scannedPackage was null or that scannedPackage
8100                // did not require an ABI, in which case we have to adjust scannedPackage to match
8101                // the ABI of the set (which is the same as requirer's ABI)
8102                adjustedAbi = requirer.primaryCpuAbiString;
8103                if (scannedPackage != null) {
8104                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8105                }
8106            } else {
8107                // requirer == null implies that we're updating all ABIs in the set to
8108                // match scannedPackage.
8109                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8110            }
8111
8112            for (PackageSetting ps : packagesForUser) {
8113                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8114                    if (ps.primaryCpuAbiString != null) {
8115                        continue;
8116                    }
8117
8118                    ps.primaryCpuAbiString = adjustedAbi;
8119                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8120                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8121                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8122                        mInstaller.rmdex(ps.codePathString,
8123                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8124                    }
8125                }
8126            }
8127        }
8128    }
8129
8130    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8131        synchronized (mPackages) {
8132            mResolverReplaced = true;
8133            // Set up information for custom user intent resolution activity.
8134            mResolveActivity.applicationInfo = pkg.applicationInfo;
8135            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8136            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8137            mResolveActivity.processName = pkg.applicationInfo.packageName;
8138            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8139            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8140                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8141            mResolveActivity.theme = 0;
8142            mResolveActivity.exported = true;
8143            mResolveActivity.enabled = true;
8144            mResolveInfo.activityInfo = mResolveActivity;
8145            mResolveInfo.priority = 0;
8146            mResolveInfo.preferredOrder = 0;
8147            mResolveInfo.match = 0;
8148            mResolveComponentName = mCustomResolverComponentName;
8149            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8150                    mResolveComponentName);
8151        }
8152    }
8153
8154    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8155        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8156
8157        // Set up information for ephemeral installer activity
8158        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8159        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8160        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8161        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8162        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8163        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8164                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8165        mEphemeralInstallerActivity.theme = 0;
8166        mEphemeralInstallerActivity.exported = true;
8167        mEphemeralInstallerActivity.enabled = true;
8168        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8169        mEphemeralInstallerInfo.priority = 0;
8170        mEphemeralInstallerInfo.preferredOrder = 0;
8171        mEphemeralInstallerInfo.match = 0;
8172
8173        if (DEBUG_EPHEMERAL) {
8174            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8175        }
8176    }
8177
8178    private static String calculateBundledApkRoot(final String codePathString) {
8179        final File codePath = new File(codePathString);
8180        final File codeRoot;
8181        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8182            codeRoot = Environment.getRootDirectory();
8183        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8184            codeRoot = Environment.getOemDirectory();
8185        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8186            codeRoot = Environment.getVendorDirectory();
8187        } else {
8188            // Unrecognized code path; take its top real segment as the apk root:
8189            // e.g. /something/app/blah.apk => /something
8190            try {
8191                File f = codePath.getCanonicalFile();
8192                File parent = f.getParentFile();    // non-null because codePath is a file
8193                File tmp;
8194                while ((tmp = parent.getParentFile()) != null) {
8195                    f = parent;
8196                    parent = tmp;
8197                }
8198                codeRoot = f;
8199                Slog.w(TAG, "Unrecognized code path "
8200                        + codePath + " - using " + codeRoot);
8201            } catch (IOException e) {
8202                // Can't canonicalize the code path -- shenanigans?
8203                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8204                return Environment.getRootDirectory().getPath();
8205            }
8206        }
8207        return codeRoot.getPath();
8208    }
8209
8210    /**
8211     * Derive and set the location of native libraries for the given package,
8212     * which varies depending on where and how the package was installed.
8213     */
8214    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8215        final ApplicationInfo info = pkg.applicationInfo;
8216        final String codePath = pkg.codePath;
8217        final File codeFile = new File(codePath);
8218        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8219        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8220
8221        info.nativeLibraryRootDir = null;
8222        info.nativeLibraryRootRequiresIsa = false;
8223        info.nativeLibraryDir = null;
8224        info.secondaryNativeLibraryDir = null;
8225
8226        if (isApkFile(codeFile)) {
8227            // Monolithic install
8228            if (bundledApp) {
8229                // If "/system/lib64/apkname" exists, assume that is the per-package
8230                // native library directory to use; otherwise use "/system/lib/apkname".
8231                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8232                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8233                        getPrimaryInstructionSet(info));
8234
8235                // This is a bundled system app so choose the path based on the ABI.
8236                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8237                // is just the default path.
8238                final String apkName = deriveCodePathName(codePath);
8239                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8240                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8241                        apkName).getAbsolutePath();
8242
8243                if (info.secondaryCpuAbi != null) {
8244                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8245                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8246                            secondaryLibDir, apkName).getAbsolutePath();
8247                }
8248            } else if (asecApp) {
8249                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8250                        .getAbsolutePath();
8251            } else {
8252                final String apkName = deriveCodePathName(codePath);
8253                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8254                        .getAbsolutePath();
8255            }
8256
8257            info.nativeLibraryRootRequiresIsa = false;
8258            info.nativeLibraryDir = info.nativeLibraryRootDir;
8259        } else {
8260            // Cluster install
8261            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8262            info.nativeLibraryRootRequiresIsa = true;
8263
8264            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8265                    getPrimaryInstructionSet(info)).getAbsolutePath();
8266
8267            if (info.secondaryCpuAbi != null) {
8268                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8269                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8270            }
8271        }
8272    }
8273
8274    /**
8275     * Calculate the abis and roots for a bundled app. These can uniquely
8276     * be determined from the contents of the system partition, i.e whether
8277     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8278     * of this information, and instead assume that the system was built
8279     * sensibly.
8280     */
8281    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8282                                           PackageSetting pkgSetting) {
8283        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8284
8285        // If "/system/lib64/apkname" exists, assume that is the per-package
8286        // native library directory to use; otherwise use "/system/lib/apkname".
8287        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8288        setBundledAppAbi(pkg, apkRoot, apkName);
8289        // pkgSetting might be null during rescan following uninstall of updates
8290        // to a bundled app, so accommodate that possibility.  The settings in
8291        // that case will be established later from the parsed package.
8292        //
8293        // If the settings aren't null, sync them up with what we've just derived.
8294        // note that apkRoot isn't stored in the package settings.
8295        if (pkgSetting != null) {
8296            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8297            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8298        }
8299    }
8300
8301    /**
8302     * Deduces the ABI of a bundled app and sets the relevant fields on the
8303     * parsed pkg object.
8304     *
8305     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8306     *        under which system libraries are installed.
8307     * @param apkName the name of the installed package.
8308     */
8309    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8310        final File codeFile = new File(pkg.codePath);
8311
8312        final boolean has64BitLibs;
8313        final boolean has32BitLibs;
8314        if (isApkFile(codeFile)) {
8315            // Monolithic install
8316            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8317            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8318        } else {
8319            // Cluster install
8320            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8321            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8322                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8323                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8324                has64BitLibs = (new File(rootDir, isa)).exists();
8325            } else {
8326                has64BitLibs = false;
8327            }
8328            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8329                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8330                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8331                has32BitLibs = (new File(rootDir, isa)).exists();
8332            } else {
8333                has32BitLibs = false;
8334            }
8335        }
8336
8337        if (has64BitLibs && !has32BitLibs) {
8338            // The package has 64 bit libs, but not 32 bit libs. Its primary
8339            // ABI should be 64 bit. We can safely assume here that the bundled
8340            // native libraries correspond to the most preferred ABI in the list.
8341
8342            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8343            pkg.applicationInfo.secondaryCpuAbi = null;
8344        } else if (has32BitLibs && !has64BitLibs) {
8345            // The package has 32 bit libs but not 64 bit libs. Its primary
8346            // ABI should be 32 bit.
8347
8348            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8349            pkg.applicationInfo.secondaryCpuAbi = null;
8350        } else if (has32BitLibs && has64BitLibs) {
8351            // The application has both 64 and 32 bit bundled libraries. We check
8352            // here that the app declares multiArch support, and warn if it doesn't.
8353            //
8354            // We will be lenient here and record both ABIs. The primary will be the
8355            // ABI that's higher on the list, i.e, a device that's configured to prefer
8356            // 64 bit apps will see a 64 bit primary ABI,
8357
8358            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8359                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8360            }
8361
8362            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8363                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8364                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8365            } else {
8366                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8367                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8368            }
8369        } else {
8370            pkg.applicationInfo.primaryCpuAbi = null;
8371            pkg.applicationInfo.secondaryCpuAbi = null;
8372        }
8373    }
8374
8375    private void killApplication(String pkgName, int appId, String reason) {
8376        // Request the ActivityManager to kill the process(only for existing packages)
8377        // so that we do not end up in a confused state while the user is still using the older
8378        // version of the application while the new one gets installed.
8379        IActivityManager am = ActivityManagerNative.getDefault();
8380        if (am != null) {
8381            try {
8382                am.killApplicationWithAppId(pkgName, appId, reason);
8383            } catch (RemoteException e) {
8384            }
8385        }
8386    }
8387
8388    void removePackageLI(PackageSetting ps, boolean chatty) {
8389        if (DEBUG_INSTALL) {
8390            if (chatty)
8391                Log.d(TAG, "Removing package " + ps.name);
8392        }
8393
8394        // writer
8395        synchronized (mPackages) {
8396            mPackages.remove(ps.name);
8397            final PackageParser.Package pkg = ps.pkg;
8398            if (pkg != null) {
8399                cleanPackageDataStructuresLILPw(pkg, chatty);
8400            }
8401        }
8402    }
8403
8404    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8405        if (DEBUG_INSTALL) {
8406            if (chatty)
8407                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8408        }
8409
8410        // writer
8411        synchronized (mPackages) {
8412            mPackages.remove(pkg.applicationInfo.packageName);
8413            cleanPackageDataStructuresLILPw(pkg, chatty);
8414        }
8415    }
8416
8417    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8418        int N = pkg.providers.size();
8419        StringBuilder r = null;
8420        int i;
8421        for (i=0; i<N; i++) {
8422            PackageParser.Provider p = pkg.providers.get(i);
8423            mProviders.removeProvider(p);
8424            if (p.info.authority == null) {
8425
8426                /* There was another ContentProvider with this authority when
8427                 * this app was installed so this authority is null,
8428                 * Ignore it as we don't have to unregister the provider.
8429                 */
8430                continue;
8431            }
8432            String names[] = p.info.authority.split(";");
8433            for (int j = 0; j < names.length; j++) {
8434                if (mProvidersByAuthority.get(names[j]) == p) {
8435                    mProvidersByAuthority.remove(names[j]);
8436                    if (DEBUG_REMOVE) {
8437                        if (chatty)
8438                            Log.d(TAG, "Unregistered content provider: " + names[j]
8439                                    + ", className = " + p.info.name + ", isSyncable = "
8440                                    + p.info.isSyncable);
8441                    }
8442                }
8443            }
8444            if (DEBUG_REMOVE && chatty) {
8445                if (r == null) {
8446                    r = new StringBuilder(256);
8447                } else {
8448                    r.append(' ');
8449                }
8450                r.append(p.info.name);
8451            }
8452        }
8453        if (r != null) {
8454            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8455        }
8456
8457        N = pkg.services.size();
8458        r = null;
8459        for (i=0; i<N; i++) {
8460            PackageParser.Service s = pkg.services.get(i);
8461            mServices.removeService(s);
8462            if (chatty) {
8463                if (r == null) {
8464                    r = new StringBuilder(256);
8465                } else {
8466                    r.append(' ');
8467                }
8468                r.append(s.info.name);
8469            }
8470        }
8471        if (r != null) {
8472            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8473        }
8474
8475        N = pkg.receivers.size();
8476        r = null;
8477        for (i=0; i<N; i++) {
8478            PackageParser.Activity a = pkg.receivers.get(i);
8479            mReceivers.removeActivity(a, "receiver");
8480            if (DEBUG_REMOVE && chatty) {
8481                if (r == null) {
8482                    r = new StringBuilder(256);
8483                } else {
8484                    r.append(' ');
8485                }
8486                r.append(a.info.name);
8487            }
8488        }
8489        if (r != null) {
8490            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8491        }
8492
8493        N = pkg.activities.size();
8494        r = null;
8495        for (i=0; i<N; i++) {
8496            PackageParser.Activity a = pkg.activities.get(i);
8497            mActivities.removeActivity(a, "activity");
8498            if (DEBUG_REMOVE && chatty) {
8499                if (r == null) {
8500                    r = new StringBuilder(256);
8501                } else {
8502                    r.append(' ');
8503                }
8504                r.append(a.info.name);
8505            }
8506        }
8507        if (r != null) {
8508            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8509        }
8510
8511        N = pkg.permissions.size();
8512        r = null;
8513        for (i=0; i<N; i++) {
8514            PackageParser.Permission p = pkg.permissions.get(i);
8515            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8516            if (bp == null) {
8517                bp = mSettings.mPermissionTrees.get(p.info.name);
8518            }
8519            if (bp != null && bp.perm == p) {
8520                bp.perm = null;
8521                if (DEBUG_REMOVE && chatty) {
8522                    if (r == null) {
8523                        r = new StringBuilder(256);
8524                    } else {
8525                        r.append(' ');
8526                    }
8527                    r.append(p.info.name);
8528                }
8529            }
8530            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8531                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8532                if (appOpPkgs != null) {
8533                    appOpPkgs.remove(pkg.packageName);
8534                }
8535            }
8536        }
8537        if (r != null) {
8538            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8539        }
8540
8541        N = pkg.requestedPermissions.size();
8542        r = null;
8543        for (i=0; i<N; i++) {
8544            String perm = pkg.requestedPermissions.get(i);
8545            BasePermission bp = mSettings.mPermissions.get(perm);
8546            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8547                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8548                if (appOpPkgs != null) {
8549                    appOpPkgs.remove(pkg.packageName);
8550                    if (appOpPkgs.isEmpty()) {
8551                        mAppOpPermissionPackages.remove(perm);
8552                    }
8553                }
8554            }
8555        }
8556        if (r != null) {
8557            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8558        }
8559
8560        N = pkg.instrumentation.size();
8561        r = null;
8562        for (i=0; i<N; i++) {
8563            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8564            mInstrumentation.remove(a.getComponentName());
8565            if (DEBUG_REMOVE && chatty) {
8566                if (r == null) {
8567                    r = new StringBuilder(256);
8568                } else {
8569                    r.append(' ');
8570                }
8571                r.append(a.info.name);
8572            }
8573        }
8574        if (r != null) {
8575            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8576        }
8577
8578        r = null;
8579        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8580            // Only system apps can hold shared libraries.
8581            if (pkg.libraryNames != null) {
8582                for (i=0; i<pkg.libraryNames.size(); i++) {
8583                    String name = pkg.libraryNames.get(i);
8584                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8585                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8586                        mSharedLibraries.remove(name);
8587                        if (DEBUG_REMOVE && chatty) {
8588                            if (r == null) {
8589                                r = new StringBuilder(256);
8590                            } else {
8591                                r.append(' ');
8592                            }
8593                            r.append(name);
8594                        }
8595                    }
8596                }
8597            }
8598        }
8599        if (r != null) {
8600            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8601        }
8602    }
8603
8604    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8605        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8606            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8607                return true;
8608            }
8609        }
8610        return false;
8611    }
8612
8613    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8614    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8615    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8616
8617    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8618            int flags) {
8619        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8620        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8621    }
8622
8623    private void updatePermissionsLPw(String changingPkg,
8624            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8625        // Make sure there are no dangling permission trees.
8626        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8627        while (it.hasNext()) {
8628            final BasePermission bp = it.next();
8629            if (bp.packageSetting == null) {
8630                // We may not yet have parsed the package, so just see if
8631                // we still know about its settings.
8632                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8633            }
8634            if (bp.packageSetting == null) {
8635                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8636                        + " from package " + bp.sourcePackage);
8637                it.remove();
8638            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8639                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8640                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8641                            + " from package " + bp.sourcePackage);
8642                    flags |= UPDATE_PERMISSIONS_ALL;
8643                    it.remove();
8644                }
8645            }
8646        }
8647
8648        // Make sure all dynamic permissions have been assigned to a package,
8649        // and make sure there are no dangling permissions.
8650        it = mSettings.mPermissions.values().iterator();
8651        while (it.hasNext()) {
8652            final BasePermission bp = it.next();
8653            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8654                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8655                        + bp.name + " pkg=" + bp.sourcePackage
8656                        + " info=" + bp.pendingInfo);
8657                if (bp.packageSetting == null && bp.pendingInfo != null) {
8658                    final BasePermission tree = findPermissionTreeLP(bp.name);
8659                    if (tree != null && tree.perm != null) {
8660                        bp.packageSetting = tree.packageSetting;
8661                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8662                                new PermissionInfo(bp.pendingInfo));
8663                        bp.perm.info.packageName = tree.perm.info.packageName;
8664                        bp.perm.info.name = bp.name;
8665                        bp.uid = tree.uid;
8666                    }
8667                }
8668            }
8669            if (bp.packageSetting == null) {
8670                // We may not yet have parsed the package, so just see if
8671                // we still know about its settings.
8672                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8673            }
8674            if (bp.packageSetting == null) {
8675                Slog.w(TAG, "Removing dangling permission: " + bp.name
8676                        + " from package " + bp.sourcePackage);
8677                it.remove();
8678            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8679                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8680                    Slog.i(TAG, "Removing old permission: " + bp.name
8681                            + " from package " + bp.sourcePackage);
8682                    flags |= UPDATE_PERMISSIONS_ALL;
8683                    it.remove();
8684                }
8685            }
8686        }
8687
8688        // Now update the permissions for all packages, in particular
8689        // replace the granted permissions of the system packages.
8690        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8691            for (PackageParser.Package pkg : mPackages.values()) {
8692                if (pkg != pkgInfo) {
8693                    // Only replace for packages on requested volume
8694                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8695                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8696                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8697                    grantPermissionsLPw(pkg, replace, changingPkg);
8698                }
8699            }
8700        }
8701
8702        if (pkgInfo != null) {
8703            // Only replace for packages on requested volume
8704            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8705            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8706                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8707            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8708        }
8709    }
8710
8711    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8712            String packageOfInterest) {
8713        // IMPORTANT: There are two types of permissions: install and runtime.
8714        // Install time permissions are granted when the app is installed to
8715        // all device users and users added in the future. Runtime permissions
8716        // are granted at runtime explicitly to specific users. Normal and signature
8717        // protected permissions are install time permissions. Dangerous permissions
8718        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8719        // otherwise they are runtime permissions. This function does not manage
8720        // runtime permissions except for the case an app targeting Lollipop MR1
8721        // being upgraded to target a newer SDK, in which case dangerous permissions
8722        // are transformed from install time to runtime ones.
8723
8724        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8725        if (ps == null) {
8726            return;
8727        }
8728
8729        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8730
8731        PermissionsState permissionsState = ps.getPermissionsState();
8732        PermissionsState origPermissions = permissionsState;
8733
8734        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8735
8736        boolean runtimePermissionsRevoked = false;
8737        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8738
8739        boolean changedInstallPermission = false;
8740
8741        if (replace) {
8742            ps.installPermissionsFixed = false;
8743            if (!ps.isSharedUser()) {
8744                origPermissions = new PermissionsState(permissionsState);
8745                permissionsState.reset();
8746            } else {
8747                // We need to know only about runtime permission changes since the
8748                // calling code always writes the install permissions state but
8749                // the runtime ones are written only if changed. The only cases of
8750                // changed runtime permissions here are promotion of an install to
8751                // runtime and revocation of a runtime from a shared user.
8752                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8753                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8754                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8755                    runtimePermissionsRevoked = true;
8756                }
8757            }
8758        }
8759
8760        permissionsState.setGlobalGids(mGlobalGids);
8761
8762        final int N = pkg.requestedPermissions.size();
8763        for (int i=0; i<N; i++) {
8764            final String name = pkg.requestedPermissions.get(i);
8765            final BasePermission bp = mSettings.mPermissions.get(name);
8766
8767            if (DEBUG_INSTALL) {
8768                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8769            }
8770
8771            if (bp == null || bp.packageSetting == null) {
8772                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8773                    Slog.w(TAG, "Unknown permission " + name
8774                            + " in package " + pkg.packageName);
8775                }
8776                continue;
8777            }
8778
8779            final String perm = bp.name;
8780            boolean allowedSig = false;
8781            int grant = GRANT_DENIED;
8782
8783            // Keep track of app op permissions.
8784            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8785                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8786                if (pkgs == null) {
8787                    pkgs = new ArraySet<>();
8788                    mAppOpPermissionPackages.put(bp.name, pkgs);
8789                }
8790                pkgs.add(pkg.packageName);
8791            }
8792
8793            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8794            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8795                    >= Build.VERSION_CODES.M;
8796            switch (level) {
8797                case PermissionInfo.PROTECTION_NORMAL: {
8798                    // For all apps normal permissions are install time ones.
8799                    grant = GRANT_INSTALL;
8800                } break;
8801
8802                case PermissionInfo.PROTECTION_DANGEROUS: {
8803                    // If a permission review is required for legacy apps we represent
8804                    // their permissions as always granted runtime ones since we need
8805                    // to keep the review required permission flag per user while an
8806                    // install permission's state is shared across all users.
8807                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8808                        // For legacy apps dangerous permissions are install time ones.
8809                        grant = GRANT_INSTALL;
8810                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8811                        // For legacy apps that became modern, install becomes runtime.
8812                        grant = GRANT_UPGRADE;
8813                    } else if (mPromoteSystemApps
8814                            && isSystemApp(ps)
8815                            && mExistingSystemPackages.contains(ps.name)) {
8816                        // For legacy system apps, install becomes runtime.
8817                        // We cannot check hasInstallPermission() for system apps since those
8818                        // permissions were granted implicitly and not persisted pre-M.
8819                        grant = GRANT_UPGRADE;
8820                    } else {
8821                        // For modern apps keep runtime permissions unchanged.
8822                        grant = GRANT_RUNTIME;
8823                    }
8824                } break;
8825
8826                case PermissionInfo.PROTECTION_SIGNATURE: {
8827                    // For all apps signature permissions are install time ones.
8828                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8829                    if (allowedSig) {
8830                        grant = GRANT_INSTALL;
8831                    }
8832                } break;
8833            }
8834
8835            if (DEBUG_INSTALL) {
8836                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8837            }
8838
8839            if (grant != GRANT_DENIED) {
8840                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8841                    // If this is an existing, non-system package, then
8842                    // we can't add any new permissions to it.
8843                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8844                        // Except...  if this is a permission that was added
8845                        // to the platform (note: need to only do this when
8846                        // updating the platform).
8847                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8848                            grant = GRANT_DENIED;
8849                        }
8850                    }
8851                }
8852
8853                switch (grant) {
8854                    case GRANT_INSTALL: {
8855                        // Revoke this as runtime permission to handle the case of
8856                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8857                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8858                            if (origPermissions.getRuntimePermissionState(
8859                                    bp.name, userId) != null) {
8860                                // Revoke the runtime permission and clear the flags.
8861                                origPermissions.revokeRuntimePermission(bp, userId);
8862                                origPermissions.updatePermissionFlags(bp, userId,
8863                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8864                                // If we revoked a permission permission, we have to write.
8865                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8866                                        changedRuntimePermissionUserIds, userId);
8867                            }
8868                        }
8869                        // Grant an install permission.
8870                        if (permissionsState.grantInstallPermission(bp) !=
8871                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8872                            changedInstallPermission = true;
8873                        }
8874                    } break;
8875
8876                    case GRANT_RUNTIME: {
8877                        // Grant previously granted runtime permissions.
8878                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8879                            PermissionState permissionState = origPermissions
8880                                    .getRuntimePermissionState(bp.name, userId);
8881                            int flags = permissionState != null
8882                                    ? permissionState.getFlags() : 0;
8883                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8884                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8885                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8886                                    // If we cannot put the permission as it was, we have to write.
8887                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8888                                            changedRuntimePermissionUserIds, userId);
8889                                }
8890                                // If the app supports runtime permissions no need for a review.
8891                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8892                                        && appSupportsRuntimePermissions
8893                                        && (flags & PackageManager
8894                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8895                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8896                                    // Since we changed the flags, we have to write.
8897                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8898                                            changedRuntimePermissionUserIds, userId);
8899                                }
8900                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8901                                    && !appSupportsRuntimePermissions) {
8902                                // For legacy apps that need a permission review, every new
8903                                // runtime permission is granted but it is pending a review.
8904                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8905                                    permissionsState.grantRuntimePermission(bp, userId);
8906                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8907                                    // We changed the permission and flags, hence have to write.
8908                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8909                                            changedRuntimePermissionUserIds, userId);
8910                                }
8911                            }
8912                            // Propagate the permission flags.
8913                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8914                        }
8915                    } break;
8916
8917                    case GRANT_UPGRADE: {
8918                        // Grant runtime permissions for a previously held install permission.
8919                        PermissionState permissionState = origPermissions
8920                                .getInstallPermissionState(bp.name);
8921                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8922
8923                        if (origPermissions.revokeInstallPermission(bp)
8924                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8925                            // We will be transferring the permission flags, so clear them.
8926                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8927                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8928                            changedInstallPermission = true;
8929                        }
8930
8931                        // If the permission is not to be promoted to runtime we ignore it and
8932                        // also its other flags as they are not applicable to install permissions.
8933                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8934                            for (int userId : currentUserIds) {
8935                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8936                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8937                                    // Transfer the permission flags.
8938                                    permissionsState.updatePermissionFlags(bp, userId,
8939                                            flags, flags);
8940                                    // If we granted the permission, we have to write.
8941                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8942                                            changedRuntimePermissionUserIds, userId);
8943                                }
8944                            }
8945                        }
8946                    } break;
8947
8948                    default: {
8949                        if (packageOfInterest == null
8950                                || packageOfInterest.equals(pkg.packageName)) {
8951                            Slog.w(TAG, "Not granting permission " + perm
8952                                    + " to package " + pkg.packageName
8953                                    + " because it was previously installed without");
8954                        }
8955                    } break;
8956                }
8957            } else {
8958                if (permissionsState.revokeInstallPermission(bp) !=
8959                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8960                    // Also drop the permission flags.
8961                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8962                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8963                    changedInstallPermission = true;
8964                    Slog.i(TAG, "Un-granting permission " + perm
8965                            + " from package " + pkg.packageName
8966                            + " (protectionLevel=" + bp.protectionLevel
8967                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8968                            + ")");
8969                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8970                    // Don't print warning for app op permissions, since it is fine for them
8971                    // not to be granted, there is a UI for the user to decide.
8972                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8973                        Slog.w(TAG, "Not granting permission " + perm
8974                                + " to package " + pkg.packageName
8975                                + " (protectionLevel=" + bp.protectionLevel
8976                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8977                                + ")");
8978                    }
8979                }
8980            }
8981        }
8982
8983        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8984                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8985            // This is the first that we have heard about this package, so the
8986            // permissions we have now selected are fixed until explicitly
8987            // changed.
8988            ps.installPermissionsFixed = true;
8989        }
8990
8991        // Persist the runtime permissions state for users with changes. If permissions
8992        // were revoked because no app in the shared user declares them we have to
8993        // write synchronously to avoid losing runtime permissions state.
8994        for (int userId : changedRuntimePermissionUserIds) {
8995            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8996        }
8997
8998        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8999    }
9000
9001    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9002        boolean allowed = false;
9003        final int NP = PackageParser.NEW_PERMISSIONS.length;
9004        for (int ip=0; ip<NP; ip++) {
9005            final PackageParser.NewPermissionInfo npi
9006                    = PackageParser.NEW_PERMISSIONS[ip];
9007            if (npi.name.equals(perm)
9008                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9009                allowed = true;
9010                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9011                        + pkg.packageName);
9012                break;
9013            }
9014        }
9015        return allowed;
9016    }
9017
9018    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9019            BasePermission bp, PermissionsState origPermissions) {
9020        boolean allowed;
9021        allowed = (compareSignatures(
9022                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9023                        == PackageManager.SIGNATURE_MATCH)
9024                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9025                        == PackageManager.SIGNATURE_MATCH);
9026        if (!allowed && (bp.protectionLevel
9027                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9028            if (isSystemApp(pkg)) {
9029                // For updated system applications, a system permission
9030                // is granted only if it had been defined by the original application.
9031                if (pkg.isUpdatedSystemApp()) {
9032                    final PackageSetting sysPs = mSettings
9033                            .getDisabledSystemPkgLPr(pkg.packageName);
9034                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9035                        // If the original was granted this permission, we take
9036                        // that grant decision as read and propagate it to the
9037                        // update.
9038                        if (sysPs.isPrivileged()) {
9039                            allowed = true;
9040                        }
9041                    } else {
9042                        // The system apk may have been updated with an older
9043                        // version of the one on the data partition, but which
9044                        // granted a new system permission that it didn't have
9045                        // before.  In this case we do want to allow the app to
9046                        // now get the new permission if the ancestral apk is
9047                        // privileged to get it.
9048                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9049                            for (int j=0;
9050                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9051                                if (perm.equals(
9052                                        sysPs.pkg.requestedPermissions.get(j))) {
9053                                    allowed = true;
9054                                    break;
9055                                }
9056                            }
9057                        }
9058                    }
9059                } else {
9060                    allowed = isPrivilegedApp(pkg);
9061                }
9062            }
9063        }
9064        if (!allowed) {
9065            if (!allowed && (bp.protectionLevel
9066                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9067                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9068                // If this was a previously normal/dangerous permission that got moved
9069                // to a system permission as part of the runtime permission redesign, then
9070                // we still want to blindly grant it to old apps.
9071                allowed = true;
9072            }
9073            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9074                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9075                // If this permission is to be granted to the system installer and
9076                // this app is an installer, then it gets the permission.
9077                allowed = true;
9078            }
9079            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9080                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9081                // If this permission is to be granted to the system verifier and
9082                // this app is a verifier, then it gets the permission.
9083                allowed = true;
9084            }
9085            if (!allowed && (bp.protectionLevel
9086                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9087                    && isSystemApp(pkg)) {
9088                // Any pre-installed system app is allowed to get this permission.
9089                allowed = true;
9090            }
9091            if (!allowed && (bp.protectionLevel
9092                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9093                // For development permissions, a development permission
9094                // is granted only if it was already granted.
9095                allowed = origPermissions.hasInstallPermission(perm);
9096            }
9097        }
9098        return allowed;
9099    }
9100
9101    final class ActivityIntentResolver
9102            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9103        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9104                boolean defaultOnly, int userId) {
9105            if (!sUserManager.exists(userId)) return null;
9106            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9107            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9108        }
9109
9110        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9111                int userId) {
9112            if (!sUserManager.exists(userId)) return null;
9113            mFlags = flags;
9114            return super.queryIntent(intent, resolvedType,
9115                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9116        }
9117
9118        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9119                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9120            if (!sUserManager.exists(userId)) return null;
9121            if (packageActivities == null) {
9122                return null;
9123            }
9124            mFlags = flags;
9125            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9126            final int N = packageActivities.size();
9127            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9128                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9129
9130            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9131            for (int i = 0; i < N; ++i) {
9132                intentFilters = packageActivities.get(i).intents;
9133                if (intentFilters != null && intentFilters.size() > 0) {
9134                    PackageParser.ActivityIntentInfo[] array =
9135                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9136                    intentFilters.toArray(array);
9137                    listCut.add(array);
9138                }
9139            }
9140            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9141        }
9142
9143        public final void addActivity(PackageParser.Activity a, String type) {
9144            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9145            mActivities.put(a.getComponentName(), a);
9146            if (DEBUG_SHOW_INFO)
9147                Log.v(
9148                TAG, "  " + type + " " +
9149                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9150            if (DEBUG_SHOW_INFO)
9151                Log.v(TAG, "    Class=" + a.info.name);
9152            final int NI = a.intents.size();
9153            for (int j=0; j<NI; j++) {
9154                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9155                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9156                    intent.setPriority(0);
9157                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9158                            + a.className + " with priority > 0, forcing to 0");
9159                }
9160                if (DEBUG_SHOW_INFO) {
9161                    Log.v(TAG, "    IntentFilter:");
9162                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9163                }
9164                if (!intent.debugCheck()) {
9165                    Log.w(TAG, "==> For Activity " + a.info.name);
9166                }
9167                addFilter(intent);
9168            }
9169        }
9170
9171        public final void removeActivity(PackageParser.Activity a, String type) {
9172            mActivities.remove(a.getComponentName());
9173            if (DEBUG_SHOW_INFO) {
9174                Log.v(TAG, "  " + type + " "
9175                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9176                                : a.info.name) + ":");
9177                Log.v(TAG, "    Class=" + a.info.name);
9178            }
9179            final int NI = a.intents.size();
9180            for (int j=0; j<NI; j++) {
9181                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9182                if (DEBUG_SHOW_INFO) {
9183                    Log.v(TAG, "    IntentFilter:");
9184                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9185                }
9186                removeFilter(intent);
9187            }
9188        }
9189
9190        @Override
9191        protected boolean allowFilterResult(
9192                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9193            ActivityInfo filterAi = filter.activity.info;
9194            for (int i=dest.size()-1; i>=0; i--) {
9195                ActivityInfo destAi = dest.get(i).activityInfo;
9196                if (destAi.name == filterAi.name
9197                        && destAi.packageName == filterAi.packageName) {
9198                    return false;
9199                }
9200            }
9201            return true;
9202        }
9203
9204        @Override
9205        protected ActivityIntentInfo[] newArray(int size) {
9206            return new ActivityIntentInfo[size];
9207        }
9208
9209        @Override
9210        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9211            if (!sUserManager.exists(userId)) return true;
9212            PackageParser.Package p = filter.activity.owner;
9213            if (p != null) {
9214                PackageSetting ps = (PackageSetting)p.mExtras;
9215                if (ps != null) {
9216                    // System apps are never considered stopped for purposes of
9217                    // filtering, because there may be no way for the user to
9218                    // actually re-launch them.
9219                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9220                            && ps.getStopped(userId);
9221                }
9222            }
9223            return false;
9224        }
9225
9226        @Override
9227        protected boolean isPackageForFilter(String packageName,
9228                PackageParser.ActivityIntentInfo info) {
9229            return packageName.equals(info.activity.owner.packageName);
9230        }
9231
9232        @Override
9233        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9234                int match, int userId) {
9235            if (!sUserManager.exists(userId)) return null;
9236            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9237                return null;
9238            }
9239            final PackageParser.Activity activity = info.activity;
9240            if (mSafeMode && (activity.info.applicationInfo.flags
9241                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9242                return null;
9243            }
9244            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9245            if (ps == null) {
9246                return null;
9247            }
9248            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9249                    ps.readUserState(userId), userId);
9250            if (ai == null) {
9251                return null;
9252            }
9253            final ResolveInfo res = new ResolveInfo();
9254            res.activityInfo = ai;
9255            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9256                res.filter = info;
9257            }
9258            if (info != null) {
9259                res.handleAllWebDataURI = info.handleAllWebDataURI();
9260            }
9261            res.priority = info.getPriority();
9262            res.preferredOrder = activity.owner.mPreferredOrder;
9263            //System.out.println("Result: " + res.activityInfo.className +
9264            //                   " = " + res.priority);
9265            res.match = match;
9266            res.isDefault = info.hasDefault;
9267            res.labelRes = info.labelRes;
9268            res.nonLocalizedLabel = info.nonLocalizedLabel;
9269            if (userNeedsBadging(userId)) {
9270                res.noResourceId = true;
9271            } else {
9272                res.icon = info.icon;
9273            }
9274            res.iconResourceId = info.icon;
9275            res.system = res.activityInfo.applicationInfo.isSystemApp();
9276            return res;
9277        }
9278
9279        @Override
9280        protected void sortResults(List<ResolveInfo> results) {
9281            Collections.sort(results, mResolvePrioritySorter);
9282        }
9283
9284        @Override
9285        protected void dumpFilter(PrintWriter out, String prefix,
9286                PackageParser.ActivityIntentInfo filter) {
9287            out.print(prefix); out.print(
9288                    Integer.toHexString(System.identityHashCode(filter.activity)));
9289                    out.print(' ');
9290                    filter.activity.printComponentShortName(out);
9291                    out.print(" filter ");
9292                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9293        }
9294
9295        @Override
9296        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9297            return filter.activity;
9298        }
9299
9300        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9301            PackageParser.Activity activity = (PackageParser.Activity)label;
9302            out.print(prefix); out.print(
9303                    Integer.toHexString(System.identityHashCode(activity)));
9304                    out.print(' ');
9305                    activity.printComponentShortName(out);
9306            if (count > 1) {
9307                out.print(" ("); out.print(count); out.print(" filters)");
9308            }
9309            out.println();
9310        }
9311
9312//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9313//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9314//            final List<ResolveInfo> retList = Lists.newArrayList();
9315//            while (i.hasNext()) {
9316//                final ResolveInfo resolveInfo = i.next();
9317//                if (isEnabledLP(resolveInfo.activityInfo)) {
9318//                    retList.add(resolveInfo);
9319//                }
9320//            }
9321//            return retList;
9322//        }
9323
9324        // Keys are String (activity class name), values are Activity.
9325        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9326                = new ArrayMap<ComponentName, PackageParser.Activity>();
9327        private int mFlags;
9328    }
9329
9330    private final class ServiceIntentResolver
9331            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9332        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9333                boolean defaultOnly, int userId) {
9334            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9335            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9336        }
9337
9338        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9339                int userId) {
9340            if (!sUserManager.exists(userId)) return null;
9341            mFlags = flags;
9342            return super.queryIntent(intent, resolvedType,
9343                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9344        }
9345
9346        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9347                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9348            if (!sUserManager.exists(userId)) return null;
9349            if (packageServices == null) {
9350                return null;
9351            }
9352            mFlags = flags;
9353            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9354            final int N = packageServices.size();
9355            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9356                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9357
9358            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9359            for (int i = 0; i < N; ++i) {
9360                intentFilters = packageServices.get(i).intents;
9361                if (intentFilters != null && intentFilters.size() > 0) {
9362                    PackageParser.ServiceIntentInfo[] array =
9363                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9364                    intentFilters.toArray(array);
9365                    listCut.add(array);
9366                }
9367            }
9368            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9369        }
9370
9371        public final void addService(PackageParser.Service s) {
9372            mServices.put(s.getComponentName(), s);
9373            if (DEBUG_SHOW_INFO) {
9374                Log.v(TAG, "  "
9375                        + (s.info.nonLocalizedLabel != null
9376                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9377                Log.v(TAG, "    Class=" + s.info.name);
9378            }
9379            final int NI = s.intents.size();
9380            int j;
9381            for (j=0; j<NI; j++) {
9382                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9383                if (DEBUG_SHOW_INFO) {
9384                    Log.v(TAG, "    IntentFilter:");
9385                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9386                }
9387                if (!intent.debugCheck()) {
9388                    Log.w(TAG, "==> For Service " + s.info.name);
9389                }
9390                addFilter(intent);
9391            }
9392        }
9393
9394        public final void removeService(PackageParser.Service s) {
9395            mServices.remove(s.getComponentName());
9396            if (DEBUG_SHOW_INFO) {
9397                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9398                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9399                Log.v(TAG, "    Class=" + s.info.name);
9400            }
9401            final int NI = s.intents.size();
9402            int j;
9403            for (j=0; j<NI; j++) {
9404                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9405                if (DEBUG_SHOW_INFO) {
9406                    Log.v(TAG, "    IntentFilter:");
9407                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9408                }
9409                removeFilter(intent);
9410            }
9411        }
9412
9413        @Override
9414        protected boolean allowFilterResult(
9415                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9416            ServiceInfo filterSi = filter.service.info;
9417            for (int i=dest.size()-1; i>=0; i--) {
9418                ServiceInfo destAi = dest.get(i).serviceInfo;
9419                if (destAi.name == filterSi.name
9420                        && destAi.packageName == filterSi.packageName) {
9421                    return false;
9422                }
9423            }
9424            return true;
9425        }
9426
9427        @Override
9428        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9429            return new PackageParser.ServiceIntentInfo[size];
9430        }
9431
9432        @Override
9433        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9434            if (!sUserManager.exists(userId)) return true;
9435            PackageParser.Package p = filter.service.owner;
9436            if (p != null) {
9437                PackageSetting ps = (PackageSetting)p.mExtras;
9438                if (ps != null) {
9439                    // System apps are never considered stopped for purposes of
9440                    // filtering, because there may be no way for the user to
9441                    // actually re-launch them.
9442                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9443                            && ps.getStopped(userId);
9444                }
9445            }
9446            return false;
9447        }
9448
9449        @Override
9450        protected boolean isPackageForFilter(String packageName,
9451                PackageParser.ServiceIntentInfo info) {
9452            return packageName.equals(info.service.owner.packageName);
9453        }
9454
9455        @Override
9456        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9457                int match, int userId) {
9458            if (!sUserManager.exists(userId)) return null;
9459            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9460            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9461                return null;
9462            }
9463            final PackageParser.Service service = info.service;
9464            if (mSafeMode && (service.info.applicationInfo.flags
9465                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9466                return null;
9467            }
9468            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9469            if (ps == null) {
9470                return null;
9471            }
9472            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9473                    ps.readUserState(userId), userId);
9474            if (si == null) {
9475                return null;
9476            }
9477            final ResolveInfo res = new ResolveInfo();
9478            res.serviceInfo = si;
9479            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9480                res.filter = filter;
9481            }
9482            res.priority = info.getPriority();
9483            res.preferredOrder = service.owner.mPreferredOrder;
9484            res.match = match;
9485            res.isDefault = info.hasDefault;
9486            res.labelRes = info.labelRes;
9487            res.nonLocalizedLabel = info.nonLocalizedLabel;
9488            res.icon = info.icon;
9489            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9490            return res;
9491        }
9492
9493        @Override
9494        protected void sortResults(List<ResolveInfo> results) {
9495            Collections.sort(results, mResolvePrioritySorter);
9496        }
9497
9498        @Override
9499        protected void dumpFilter(PrintWriter out, String prefix,
9500                PackageParser.ServiceIntentInfo filter) {
9501            out.print(prefix); out.print(
9502                    Integer.toHexString(System.identityHashCode(filter.service)));
9503                    out.print(' ');
9504                    filter.service.printComponentShortName(out);
9505                    out.print(" filter ");
9506                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9507        }
9508
9509        @Override
9510        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9511            return filter.service;
9512        }
9513
9514        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9515            PackageParser.Service service = (PackageParser.Service)label;
9516            out.print(prefix); out.print(
9517                    Integer.toHexString(System.identityHashCode(service)));
9518                    out.print(' ');
9519                    service.printComponentShortName(out);
9520            if (count > 1) {
9521                out.print(" ("); out.print(count); out.print(" filters)");
9522            }
9523            out.println();
9524        }
9525
9526//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9527//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9528//            final List<ResolveInfo> retList = Lists.newArrayList();
9529//            while (i.hasNext()) {
9530//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9531//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9532//                    retList.add(resolveInfo);
9533//                }
9534//            }
9535//            return retList;
9536//        }
9537
9538        // Keys are String (activity class name), values are Activity.
9539        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9540                = new ArrayMap<ComponentName, PackageParser.Service>();
9541        private int mFlags;
9542    };
9543
9544    private final class ProviderIntentResolver
9545            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9546        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9547                boolean defaultOnly, int userId) {
9548            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9549            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9550        }
9551
9552        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9553                int userId) {
9554            if (!sUserManager.exists(userId))
9555                return null;
9556            mFlags = flags;
9557            return super.queryIntent(intent, resolvedType,
9558                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9559        }
9560
9561        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9562                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9563            if (!sUserManager.exists(userId))
9564                return null;
9565            if (packageProviders == null) {
9566                return null;
9567            }
9568            mFlags = flags;
9569            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9570            final int N = packageProviders.size();
9571            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9572                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9573
9574            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9575            for (int i = 0; i < N; ++i) {
9576                intentFilters = packageProviders.get(i).intents;
9577                if (intentFilters != null && intentFilters.size() > 0) {
9578                    PackageParser.ProviderIntentInfo[] array =
9579                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9580                    intentFilters.toArray(array);
9581                    listCut.add(array);
9582                }
9583            }
9584            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9585        }
9586
9587        public final void addProvider(PackageParser.Provider p) {
9588            if (mProviders.containsKey(p.getComponentName())) {
9589                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9590                return;
9591            }
9592
9593            mProviders.put(p.getComponentName(), p);
9594            if (DEBUG_SHOW_INFO) {
9595                Log.v(TAG, "  "
9596                        + (p.info.nonLocalizedLabel != null
9597                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9598                Log.v(TAG, "    Class=" + p.info.name);
9599            }
9600            final int NI = p.intents.size();
9601            int j;
9602            for (j = 0; j < NI; j++) {
9603                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9604                if (DEBUG_SHOW_INFO) {
9605                    Log.v(TAG, "    IntentFilter:");
9606                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9607                }
9608                if (!intent.debugCheck()) {
9609                    Log.w(TAG, "==> For Provider " + p.info.name);
9610                }
9611                addFilter(intent);
9612            }
9613        }
9614
9615        public final void removeProvider(PackageParser.Provider p) {
9616            mProviders.remove(p.getComponentName());
9617            if (DEBUG_SHOW_INFO) {
9618                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9619                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9620                Log.v(TAG, "    Class=" + p.info.name);
9621            }
9622            final int NI = p.intents.size();
9623            int j;
9624            for (j = 0; j < NI; j++) {
9625                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9626                if (DEBUG_SHOW_INFO) {
9627                    Log.v(TAG, "    IntentFilter:");
9628                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9629                }
9630                removeFilter(intent);
9631            }
9632        }
9633
9634        @Override
9635        protected boolean allowFilterResult(
9636                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9637            ProviderInfo filterPi = filter.provider.info;
9638            for (int i = dest.size() - 1; i >= 0; i--) {
9639                ProviderInfo destPi = dest.get(i).providerInfo;
9640                if (destPi.name == filterPi.name
9641                        && destPi.packageName == filterPi.packageName) {
9642                    return false;
9643                }
9644            }
9645            return true;
9646        }
9647
9648        @Override
9649        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9650            return new PackageParser.ProviderIntentInfo[size];
9651        }
9652
9653        @Override
9654        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9655            if (!sUserManager.exists(userId))
9656                return true;
9657            PackageParser.Package p = filter.provider.owner;
9658            if (p != null) {
9659                PackageSetting ps = (PackageSetting) p.mExtras;
9660                if (ps != null) {
9661                    // System apps are never considered stopped for purposes of
9662                    // filtering, because there may be no way for the user to
9663                    // actually re-launch them.
9664                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9665                            && ps.getStopped(userId);
9666                }
9667            }
9668            return false;
9669        }
9670
9671        @Override
9672        protected boolean isPackageForFilter(String packageName,
9673                PackageParser.ProviderIntentInfo info) {
9674            return packageName.equals(info.provider.owner.packageName);
9675        }
9676
9677        @Override
9678        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9679                int match, int userId) {
9680            if (!sUserManager.exists(userId))
9681                return null;
9682            final PackageParser.ProviderIntentInfo info = filter;
9683            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9684                return null;
9685            }
9686            final PackageParser.Provider provider = info.provider;
9687            if (mSafeMode && (provider.info.applicationInfo.flags
9688                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9689                return null;
9690            }
9691            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9692            if (ps == null) {
9693                return null;
9694            }
9695            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9696                    ps.readUserState(userId), userId);
9697            if (pi == null) {
9698                return null;
9699            }
9700            final ResolveInfo res = new ResolveInfo();
9701            res.providerInfo = pi;
9702            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9703                res.filter = filter;
9704            }
9705            res.priority = info.getPriority();
9706            res.preferredOrder = provider.owner.mPreferredOrder;
9707            res.match = match;
9708            res.isDefault = info.hasDefault;
9709            res.labelRes = info.labelRes;
9710            res.nonLocalizedLabel = info.nonLocalizedLabel;
9711            res.icon = info.icon;
9712            res.system = res.providerInfo.applicationInfo.isSystemApp();
9713            return res;
9714        }
9715
9716        @Override
9717        protected void sortResults(List<ResolveInfo> results) {
9718            Collections.sort(results, mResolvePrioritySorter);
9719        }
9720
9721        @Override
9722        protected void dumpFilter(PrintWriter out, String prefix,
9723                PackageParser.ProviderIntentInfo filter) {
9724            out.print(prefix);
9725            out.print(
9726                    Integer.toHexString(System.identityHashCode(filter.provider)));
9727            out.print(' ');
9728            filter.provider.printComponentShortName(out);
9729            out.print(" filter ");
9730            out.println(Integer.toHexString(System.identityHashCode(filter)));
9731        }
9732
9733        @Override
9734        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9735            return filter.provider;
9736        }
9737
9738        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9739            PackageParser.Provider provider = (PackageParser.Provider)label;
9740            out.print(prefix); out.print(
9741                    Integer.toHexString(System.identityHashCode(provider)));
9742                    out.print(' ');
9743                    provider.printComponentShortName(out);
9744            if (count > 1) {
9745                out.print(" ("); out.print(count); out.print(" filters)");
9746            }
9747            out.println();
9748        }
9749
9750        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9751                = new ArrayMap<ComponentName, PackageParser.Provider>();
9752        private int mFlags;
9753    }
9754
9755    private static final class EphemeralIntentResolver
9756            extends IntentResolver<IntentFilter, ResolveInfo> {
9757        @Override
9758        protected IntentFilter[] newArray(int size) {
9759            return new IntentFilter[size];
9760        }
9761
9762        @Override
9763        protected boolean isPackageForFilter(String packageName, IntentFilter info) {
9764            return true;
9765        }
9766
9767        @Override
9768        protected ResolveInfo newResult(IntentFilter info, int match, int userId) {
9769            if (!sUserManager.exists(userId)) return null;
9770            final ResolveInfo res = new ResolveInfo();
9771            res.filter = info;
9772            return res;
9773        }
9774    }
9775
9776    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9777            new Comparator<ResolveInfo>() {
9778        public int compare(ResolveInfo r1, ResolveInfo r2) {
9779            int v1 = r1.priority;
9780            int v2 = r2.priority;
9781            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9782            if (v1 != v2) {
9783                return (v1 > v2) ? -1 : 1;
9784            }
9785            v1 = r1.preferredOrder;
9786            v2 = r2.preferredOrder;
9787            if (v1 != v2) {
9788                return (v1 > v2) ? -1 : 1;
9789            }
9790            if (r1.isDefault != r2.isDefault) {
9791                return r1.isDefault ? -1 : 1;
9792            }
9793            v1 = r1.match;
9794            v2 = r2.match;
9795            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9796            if (v1 != v2) {
9797                return (v1 > v2) ? -1 : 1;
9798            }
9799            if (r1.system != r2.system) {
9800                return r1.system ? -1 : 1;
9801            }
9802            if (r1.activityInfo != null) {
9803                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9804            }
9805            if (r1.serviceInfo != null) {
9806                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9807            }
9808            if (r1.providerInfo != null) {
9809                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9810            }
9811            return 0;
9812        }
9813    };
9814
9815    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9816            new Comparator<ProviderInfo>() {
9817        public int compare(ProviderInfo p1, ProviderInfo p2) {
9818            final int v1 = p1.initOrder;
9819            final int v2 = p2.initOrder;
9820            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9821        }
9822    };
9823
9824    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9825            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9826            final int[] userIds) {
9827        mHandler.post(new Runnable() {
9828            @Override
9829            public void run() {
9830                try {
9831                    final IActivityManager am = ActivityManagerNative.getDefault();
9832                    if (am == null) return;
9833                    final int[] resolvedUserIds;
9834                    if (userIds == null) {
9835                        resolvedUserIds = am.getRunningUserIds();
9836                    } else {
9837                        resolvedUserIds = userIds;
9838                    }
9839                    for (int id : resolvedUserIds) {
9840                        final Intent intent = new Intent(action,
9841                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9842                        if (extras != null) {
9843                            intent.putExtras(extras);
9844                        }
9845                        if (targetPkg != null) {
9846                            intent.setPackage(targetPkg);
9847                        }
9848                        // Modify the UID when posting to other users
9849                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9850                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9851                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9852                            intent.putExtra(Intent.EXTRA_UID, uid);
9853                        }
9854                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9855                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9856                        if (DEBUG_BROADCASTS) {
9857                            RuntimeException here = new RuntimeException("here");
9858                            here.fillInStackTrace();
9859                            Slog.d(TAG, "Sending to user " + id + ": "
9860                                    + intent.toShortString(false, true, false, false)
9861                                    + " " + intent.getExtras(), here);
9862                        }
9863                        am.broadcastIntent(null, intent, null, finishedReceiver,
9864                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9865                                null, finishedReceiver != null, false, id);
9866                    }
9867                } catch (RemoteException ex) {
9868                }
9869            }
9870        });
9871    }
9872
9873    /**
9874     * Check if the external storage media is available. This is true if there
9875     * is a mounted external storage medium or if the external storage is
9876     * emulated.
9877     */
9878    private boolean isExternalMediaAvailable() {
9879        return mMediaMounted || Environment.isExternalStorageEmulated();
9880    }
9881
9882    @Override
9883    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9884        // writer
9885        synchronized (mPackages) {
9886            if (!isExternalMediaAvailable()) {
9887                // If the external storage is no longer mounted at this point,
9888                // the caller may not have been able to delete all of this
9889                // packages files and can not delete any more.  Bail.
9890                return null;
9891            }
9892            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9893            if (lastPackage != null) {
9894                pkgs.remove(lastPackage);
9895            }
9896            if (pkgs.size() > 0) {
9897                return pkgs.get(0);
9898            }
9899        }
9900        return null;
9901    }
9902
9903    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9904        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9905                userId, andCode ? 1 : 0, packageName);
9906        if (mSystemReady) {
9907            msg.sendToTarget();
9908        } else {
9909            if (mPostSystemReadyMessages == null) {
9910                mPostSystemReadyMessages = new ArrayList<>();
9911            }
9912            mPostSystemReadyMessages.add(msg);
9913        }
9914    }
9915
9916    void startCleaningPackages() {
9917        // reader
9918        synchronized (mPackages) {
9919            if (!isExternalMediaAvailable()) {
9920                return;
9921            }
9922            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9923                return;
9924            }
9925        }
9926        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9927        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9928        IActivityManager am = ActivityManagerNative.getDefault();
9929        if (am != null) {
9930            try {
9931                am.startService(null, intent, null, mContext.getOpPackageName(),
9932                        UserHandle.USER_SYSTEM);
9933            } catch (RemoteException e) {
9934            }
9935        }
9936    }
9937
9938    @Override
9939    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9940            int installFlags, String installerPackageName, VerificationParams verificationParams,
9941            String packageAbiOverride) {
9942        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9943                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9944    }
9945
9946    @Override
9947    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9948            int installFlags, String installerPackageName, VerificationParams verificationParams,
9949            String packageAbiOverride, int userId) {
9950        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9951
9952        final int callingUid = Binder.getCallingUid();
9953        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9954
9955        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9956            try {
9957                if (observer != null) {
9958                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9959                }
9960            } catch (RemoteException re) {
9961            }
9962            return;
9963        }
9964
9965        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9966            installFlags |= PackageManager.INSTALL_FROM_ADB;
9967
9968        } else {
9969            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9970            // about installerPackageName.
9971
9972            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9973            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9974        }
9975
9976        UserHandle user;
9977        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9978            user = UserHandle.ALL;
9979        } else {
9980            user = new UserHandle(userId);
9981        }
9982
9983        // Only system components can circumvent runtime permissions when installing.
9984        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9985                && mContext.checkCallingOrSelfPermission(Manifest.permission
9986                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9987            throw new SecurityException("You need the "
9988                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9989                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9990        }
9991
9992        verificationParams.setInstallerUid(callingUid);
9993
9994        final File originFile = new File(originPath);
9995        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9996
9997        final Message msg = mHandler.obtainMessage(INIT_COPY);
9998        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9999                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10000        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10001        msg.obj = params;
10002
10003        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10004                System.identityHashCode(msg.obj));
10005        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10006                System.identityHashCode(msg.obj));
10007
10008        mHandler.sendMessage(msg);
10009    }
10010
10011    void installStage(String packageName, File stagedDir, String stagedCid,
10012            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10013            String installerPackageName, int installerUid, UserHandle user) {
10014        if (DEBUG_EPHEMERAL) {
10015            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10016                Slog.d(TAG, "Ephemeral install of " + packageName);
10017            }
10018        }
10019        final VerificationParams verifParams = new VerificationParams(
10020                null, sessionParams.originatingUri, sessionParams.referrerUri,
10021                sessionParams.originatingUid, null);
10022        verifParams.setInstallerUid(installerUid);
10023
10024        final OriginInfo origin;
10025        if (stagedDir != null) {
10026            origin = OriginInfo.fromStagedFile(stagedDir);
10027        } else {
10028            origin = OriginInfo.fromStagedContainer(stagedCid);
10029        }
10030
10031        final Message msg = mHandler.obtainMessage(INIT_COPY);
10032        final InstallParams params = new InstallParams(origin, null, observer,
10033                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10034                verifParams, user, sessionParams.abiOverride,
10035                sessionParams.grantedRuntimePermissions);
10036        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10037        msg.obj = params;
10038
10039        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10040                System.identityHashCode(msg.obj));
10041        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10042                System.identityHashCode(msg.obj));
10043
10044        mHandler.sendMessage(msg);
10045    }
10046
10047    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10048        Bundle extras = new Bundle(1);
10049        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10050
10051        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10052                packageName, extras, 0, null, null, new int[] {userId});
10053        try {
10054            IActivityManager am = ActivityManagerNative.getDefault();
10055            final boolean isSystem =
10056                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10057            if (isSystem && am.isUserRunning(userId, 0)) {
10058                // The just-installed/enabled app is bundled on the system, so presumed
10059                // to be able to run automatically without needing an explicit launch.
10060                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10061                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10062                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10063                        .setPackage(packageName);
10064                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10065                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10066            }
10067        } catch (RemoteException e) {
10068            // shouldn't happen
10069            Slog.w(TAG, "Unable to bootstrap installed package", e);
10070        }
10071    }
10072
10073    @Override
10074    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10075            int userId) {
10076        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10077        PackageSetting pkgSetting;
10078        final int uid = Binder.getCallingUid();
10079        enforceCrossUserPermission(uid, userId, true, true,
10080                "setApplicationHiddenSetting for user " + userId);
10081
10082        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10083            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10084            return false;
10085        }
10086
10087        long callingId = Binder.clearCallingIdentity();
10088        try {
10089            boolean sendAdded = false;
10090            boolean sendRemoved = false;
10091            // writer
10092            synchronized (mPackages) {
10093                pkgSetting = mSettings.mPackages.get(packageName);
10094                if (pkgSetting == null) {
10095                    return false;
10096                }
10097                if (pkgSetting.getHidden(userId) != hidden) {
10098                    pkgSetting.setHidden(hidden, userId);
10099                    mSettings.writePackageRestrictionsLPr(userId);
10100                    if (hidden) {
10101                        sendRemoved = true;
10102                    } else {
10103                        sendAdded = true;
10104                    }
10105                }
10106            }
10107            if (sendAdded) {
10108                sendPackageAddedForUser(packageName, pkgSetting, userId);
10109                return true;
10110            }
10111            if (sendRemoved) {
10112                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10113                        "hiding pkg");
10114                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10115                return true;
10116            }
10117        } finally {
10118            Binder.restoreCallingIdentity(callingId);
10119        }
10120        return false;
10121    }
10122
10123    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10124            int userId) {
10125        final PackageRemovedInfo info = new PackageRemovedInfo();
10126        info.removedPackage = packageName;
10127        info.removedUsers = new int[] {userId};
10128        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10129        info.sendBroadcast(false, false, false);
10130    }
10131
10132    /**
10133     * Returns true if application is not found or there was an error. Otherwise it returns
10134     * the hidden state of the package for the given user.
10135     */
10136    @Override
10137    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10138        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10139        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10140                false, "getApplicationHidden for user " + userId);
10141        PackageSetting pkgSetting;
10142        long callingId = Binder.clearCallingIdentity();
10143        try {
10144            // writer
10145            synchronized (mPackages) {
10146                pkgSetting = mSettings.mPackages.get(packageName);
10147                if (pkgSetting == null) {
10148                    return true;
10149                }
10150                return pkgSetting.getHidden(userId);
10151            }
10152        } finally {
10153            Binder.restoreCallingIdentity(callingId);
10154        }
10155    }
10156
10157    /**
10158     * @hide
10159     */
10160    @Override
10161    public int installExistingPackageAsUser(String packageName, int userId) {
10162        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10163                null);
10164        PackageSetting pkgSetting;
10165        final int uid = Binder.getCallingUid();
10166        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10167                + userId);
10168        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10169            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10170        }
10171
10172        long callingId = Binder.clearCallingIdentity();
10173        try {
10174            boolean sendAdded = false;
10175
10176            // writer
10177            synchronized (mPackages) {
10178                pkgSetting = mSettings.mPackages.get(packageName);
10179                if (pkgSetting == null) {
10180                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10181                }
10182                if (!pkgSetting.getInstalled(userId)) {
10183                    pkgSetting.setInstalled(true, userId);
10184                    pkgSetting.setHidden(false, userId);
10185                    mSettings.writePackageRestrictionsLPr(userId);
10186                    sendAdded = true;
10187                }
10188            }
10189
10190            if (sendAdded) {
10191                sendPackageAddedForUser(packageName, pkgSetting, userId);
10192            }
10193        } finally {
10194            Binder.restoreCallingIdentity(callingId);
10195        }
10196
10197        return PackageManager.INSTALL_SUCCEEDED;
10198    }
10199
10200    boolean isUserRestricted(int userId, String restrictionKey) {
10201        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10202        if (restrictions.getBoolean(restrictionKey, false)) {
10203            Log.w(TAG, "User is restricted: " + restrictionKey);
10204            return true;
10205        }
10206        return false;
10207    }
10208
10209    @Override
10210    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10211        mContext.enforceCallingOrSelfPermission(
10212                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10213                "Only package verification agents can verify applications");
10214
10215        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10216        final PackageVerificationResponse response = new PackageVerificationResponse(
10217                verificationCode, Binder.getCallingUid());
10218        msg.arg1 = id;
10219        msg.obj = response;
10220        mHandler.sendMessage(msg);
10221    }
10222
10223    @Override
10224    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10225            long millisecondsToDelay) {
10226        mContext.enforceCallingOrSelfPermission(
10227                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10228                "Only package verification agents can extend verification timeouts");
10229
10230        final PackageVerificationState state = mPendingVerification.get(id);
10231        final PackageVerificationResponse response = new PackageVerificationResponse(
10232                verificationCodeAtTimeout, Binder.getCallingUid());
10233
10234        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10235            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10236        }
10237        if (millisecondsToDelay < 0) {
10238            millisecondsToDelay = 0;
10239        }
10240        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10241                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10242            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10243        }
10244
10245        if ((state != null) && !state.timeoutExtended()) {
10246            state.extendTimeout();
10247
10248            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10249            msg.arg1 = id;
10250            msg.obj = response;
10251            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10252        }
10253    }
10254
10255    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10256            int verificationCode, UserHandle user) {
10257        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10258        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10259        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10260        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10261        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10262
10263        mContext.sendBroadcastAsUser(intent, user,
10264                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10265    }
10266
10267    private ComponentName matchComponentForVerifier(String packageName,
10268            List<ResolveInfo> receivers) {
10269        ActivityInfo targetReceiver = null;
10270
10271        final int NR = receivers.size();
10272        for (int i = 0; i < NR; i++) {
10273            final ResolveInfo info = receivers.get(i);
10274            if (info.activityInfo == null) {
10275                continue;
10276            }
10277
10278            if (packageName.equals(info.activityInfo.packageName)) {
10279                targetReceiver = info.activityInfo;
10280                break;
10281            }
10282        }
10283
10284        if (targetReceiver == null) {
10285            return null;
10286        }
10287
10288        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10289    }
10290
10291    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10292            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10293        if (pkgInfo.verifiers.length == 0) {
10294            return null;
10295        }
10296
10297        final int N = pkgInfo.verifiers.length;
10298        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10299        for (int i = 0; i < N; i++) {
10300            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10301
10302            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10303                    receivers);
10304            if (comp == null) {
10305                continue;
10306            }
10307
10308            final int verifierUid = getUidForVerifier(verifierInfo);
10309            if (verifierUid == -1) {
10310                continue;
10311            }
10312
10313            if (DEBUG_VERIFY) {
10314                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10315                        + " with the correct signature");
10316            }
10317            sufficientVerifiers.add(comp);
10318            verificationState.addSufficientVerifier(verifierUid);
10319        }
10320
10321        return sufficientVerifiers;
10322    }
10323
10324    private int getUidForVerifier(VerifierInfo verifierInfo) {
10325        synchronized (mPackages) {
10326            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10327            if (pkg == null) {
10328                return -1;
10329            } else if (pkg.mSignatures.length != 1) {
10330                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10331                        + " has more than one signature; ignoring");
10332                return -1;
10333            }
10334
10335            /*
10336             * If the public key of the package's signature does not match
10337             * our expected public key, then this is a different package and
10338             * we should skip.
10339             */
10340
10341            final byte[] expectedPublicKey;
10342            try {
10343                final Signature verifierSig = pkg.mSignatures[0];
10344                final PublicKey publicKey = verifierSig.getPublicKey();
10345                expectedPublicKey = publicKey.getEncoded();
10346            } catch (CertificateException e) {
10347                return -1;
10348            }
10349
10350            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10351
10352            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10353                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10354                        + " does not have the expected public key; ignoring");
10355                return -1;
10356            }
10357
10358            return pkg.applicationInfo.uid;
10359        }
10360    }
10361
10362    @Override
10363    public void finishPackageInstall(int token) {
10364        enforceSystemOrRoot("Only the system is allowed to finish installs");
10365
10366        if (DEBUG_INSTALL) {
10367            Slog.v(TAG, "BM finishing package install for " + token);
10368        }
10369        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10370
10371        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10372        mHandler.sendMessage(msg);
10373    }
10374
10375    /**
10376     * Get the verification agent timeout.
10377     *
10378     * @return verification timeout in milliseconds
10379     */
10380    private long getVerificationTimeout() {
10381        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10382                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10383                DEFAULT_VERIFICATION_TIMEOUT);
10384    }
10385
10386    /**
10387     * Get the default verification agent response code.
10388     *
10389     * @return default verification response code
10390     */
10391    private int getDefaultVerificationResponse() {
10392        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10393                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10394                DEFAULT_VERIFICATION_RESPONSE);
10395    }
10396
10397    /**
10398     * Check whether or not package verification has been enabled.
10399     *
10400     * @return true if verification should be performed
10401     */
10402    private boolean isVerificationEnabled(int userId, int installFlags) {
10403        if (!DEFAULT_VERIFY_ENABLE) {
10404            return false;
10405        }
10406        // TODO: fix b/25118622; don't bypass verification
10407        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10408            return false;
10409        }
10410        // Ephemeral apps don't get the full verification treatment
10411        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10412            if (DEBUG_EPHEMERAL) {
10413                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10414            }
10415            return false;
10416        }
10417
10418        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10419
10420        // Check if installing from ADB
10421        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10422            // Do not run verification in a test harness environment
10423            if (ActivityManager.isRunningInTestHarness()) {
10424                return false;
10425            }
10426            if (ensureVerifyAppsEnabled) {
10427                return true;
10428            }
10429            // Check if the developer does not want package verification for ADB installs
10430            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10431                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10432                return false;
10433            }
10434        }
10435
10436        if (ensureVerifyAppsEnabled) {
10437            return true;
10438        }
10439
10440        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10441                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10442    }
10443
10444    @Override
10445    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10446            throws RemoteException {
10447        mContext.enforceCallingOrSelfPermission(
10448                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10449                "Only intentfilter verification agents can verify applications");
10450
10451        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10452        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10453                Binder.getCallingUid(), verificationCode, failedDomains);
10454        msg.arg1 = id;
10455        msg.obj = response;
10456        mHandler.sendMessage(msg);
10457    }
10458
10459    @Override
10460    public int getIntentVerificationStatus(String packageName, int userId) {
10461        synchronized (mPackages) {
10462            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10463        }
10464    }
10465
10466    @Override
10467    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10468        mContext.enforceCallingOrSelfPermission(
10469                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10470
10471        boolean result = false;
10472        synchronized (mPackages) {
10473            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10474        }
10475        if (result) {
10476            scheduleWritePackageRestrictionsLocked(userId);
10477        }
10478        return result;
10479    }
10480
10481    @Override
10482    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10483        synchronized (mPackages) {
10484            return mSettings.getIntentFilterVerificationsLPr(packageName);
10485        }
10486    }
10487
10488    @Override
10489    public List<IntentFilter> getAllIntentFilters(String packageName) {
10490        if (TextUtils.isEmpty(packageName)) {
10491            return Collections.<IntentFilter>emptyList();
10492        }
10493        synchronized (mPackages) {
10494            PackageParser.Package pkg = mPackages.get(packageName);
10495            if (pkg == null || pkg.activities == null) {
10496                return Collections.<IntentFilter>emptyList();
10497            }
10498            final int count = pkg.activities.size();
10499            ArrayList<IntentFilter> result = new ArrayList<>();
10500            for (int n=0; n<count; n++) {
10501                PackageParser.Activity activity = pkg.activities.get(n);
10502                if (activity.intents != null || activity.intents.size() > 0) {
10503                    result.addAll(activity.intents);
10504                }
10505            }
10506            return result;
10507        }
10508    }
10509
10510    @Override
10511    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10512        mContext.enforceCallingOrSelfPermission(
10513                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10514
10515        synchronized (mPackages) {
10516            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10517            if (packageName != null) {
10518                result |= updateIntentVerificationStatus(packageName,
10519                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10520                        userId);
10521                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10522                        packageName, userId);
10523            }
10524            return result;
10525        }
10526    }
10527
10528    @Override
10529    public String getDefaultBrowserPackageName(int userId) {
10530        synchronized (mPackages) {
10531            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10532        }
10533    }
10534
10535    /**
10536     * Get the "allow unknown sources" setting.
10537     *
10538     * @return the current "allow unknown sources" setting
10539     */
10540    private int getUnknownSourcesSettings() {
10541        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10542                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10543                -1);
10544    }
10545
10546    @Override
10547    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10548        final int uid = Binder.getCallingUid();
10549        // writer
10550        synchronized (mPackages) {
10551            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10552            if (targetPackageSetting == null) {
10553                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10554            }
10555
10556            PackageSetting installerPackageSetting;
10557            if (installerPackageName != null) {
10558                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10559                if (installerPackageSetting == null) {
10560                    throw new IllegalArgumentException("Unknown installer package: "
10561                            + installerPackageName);
10562                }
10563            } else {
10564                installerPackageSetting = null;
10565            }
10566
10567            Signature[] callerSignature;
10568            Object obj = mSettings.getUserIdLPr(uid);
10569            if (obj != null) {
10570                if (obj instanceof SharedUserSetting) {
10571                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10572                } else if (obj instanceof PackageSetting) {
10573                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10574                } else {
10575                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10576                }
10577            } else {
10578                throw new SecurityException("Unknown calling uid " + uid);
10579            }
10580
10581            // Verify: can't set installerPackageName to a package that is
10582            // not signed with the same cert as the caller.
10583            if (installerPackageSetting != null) {
10584                if (compareSignatures(callerSignature,
10585                        installerPackageSetting.signatures.mSignatures)
10586                        != PackageManager.SIGNATURE_MATCH) {
10587                    throw new SecurityException(
10588                            "Caller does not have same cert as new installer package "
10589                            + installerPackageName);
10590                }
10591            }
10592
10593            // Verify: if target already has an installer package, it must
10594            // be signed with the same cert as the caller.
10595            if (targetPackageSetting.installerPackageName != null) {
10596                PackageSetting setting = mSettings.mPackages.get(
10597                        targetPackageSetting.installerPackageName);
10598                // If the currently set package isn't valid, then it's always
10599                // okay to change it.
10600                if (setting != null) {
10601                    if (compareSignatures(callerSignature,
10602                            setting.signatures.mSignatures)
10603                            != PackageManager.SIGNATURE_MATCH) {
10604                        throw new SecurityException(
10605                                "Caller does not have same cert as old installer package "
10606                                + targetPackageSetting.installerPackageName);
10607                    }
10608                }
10609            }
10610
10611            // Okay!
10612            targetPackageSetting.installerPackageName = installerPackageName;
10613            scheduleWriteSettingsLocked();
10614        }
10615    }
10616
10617    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10618        // Queue up an async operation since the package installation may take a little while.
10619        mHandler.post(new Runnable() {
10620            public void run() {
10621                mHandler.removeCallbacks(this);
10622                 // Result object to be returned
10623                PackageInstalledInfo res = new PackageInstalledInfo();
10624                res.returnCode = currentStatus;
10625                res.uid = -1;
10626                res.pkg = null;
10627                res.removedInfo = new PackageRemovedInfo();
10628                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10629                    args.doPreInstall(res.returnCode);
10630                    synchronized (mInstallLock) {
10631                        installPackageTracedLI(args, res);
10632                    }
10633                    args.doPostInstall(res.returnCode, res.uid);
10634                }
10635
10636                // A restore should be performed at this point if (a) the install
10637                // succeeded, (b) the operation is not an update, and (c) the new
10638                // package has not opted out of backup participation.
10639                final boolean update = res.removedInfo.removedPackage != null;
10640                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10641                boolean doRestore = !update
10642                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10643
10644                // Set up the post-install work request bookkeeping.  This will be used
10645                // and cleaned up by the post-install event handling regardless of whether
10646                // there's a restore pass performed.  Token values are >= 1.
10647                int token;
10648                if (mNextInstallToken < 0) mNextInstallToken = 1;
10649                token = mNextInstallToken++;
10650
10651                PostInstallData data = new PostInstallData(args, res);
10652                mRunningInstalls.put(token, data);
10653                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10654
10655                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10656                    // Pass responsibility to the Backup Manager.  It will perform a
10657                    // restore if appropriate, then pass responsibility back to the
10658                    // Package Manager to run the post-install observer callbacks
10659                    // and broadcasts.
10660                    IBackupManager bm = IBackupManager.Stub.asInterface(
10661                            ServiceManager.getService(Context.BACKUP_SERVICE));
10662                    if (bm != null) {
10663                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10664                                + " to BM for possible restore");
10665                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10666                        try {
10667                            // TODO: http://b/22388012
10668                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10669                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10670                            } else {
10671                                doRestore = false;
10672                            }
10673                        } catch (RemoteException e) {
10674                            // can't happen; the backup manager is local
10675                        } catch (Exception e) {
10676                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10677                            doRestore = false;
10678                        }
10679                    } else {
10680                        Slog.e(TAG, "Backup Manager not found!");
10681                        doRestore = false;
10682                    }
10683                }
10684
10685                if (!doRestore) {
10686                    // No restore possible, or the Backup Manager was mysteriously not
10687                    // available -- just fire the post-install work request directly.
10688                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10689
10690                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10691
10692                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10693                    mHandler.sendMessage(msg);
10694                }
10695            }
10696        });
10697    }
10698
10699    private abstract class HandlerParams {
10700        private static final int MAX_RETRIES = 4;
10701
10702        /**
10703         * Number of times startCopy() has been attempted and had a non-fatal
10704         * error.
10705         */
10706        private int mRetries = 0;
10707
10708        /** User handle for the user requesting the information or installation. */
10709        private final UserHandle mUser;
10710        String traceMethod;
10711        int traceCookie;
10712
10713        HandlerParams(UserHandle user) {
10714            mUser = user;
10715        }
10716
10717        UserHandle getUser() {
10718            return mUser;
10719        }
10720
10721        HandlerParams setTraceMethod(String traceMethod) {
10722            this.traceMethod = traceMethod;
10723            return this;
10724        }
10725
10726        HandlerParams setTraceCookie(int traceCookie) {
10727            this.traceCookie = traceCookie;
10728            return this;
10729        }
10730
10731        final boolean startCopy() {
10732            boolean res;
10733            try {
10734                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10735
10736                if (++mRetries > MAX_RETRIES) {
10737                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10738                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10739                    handleServiceError();
10740                    return false;
10741                } else {
10742                    handleStartCopy();
10743                    res = true;
10744                }
10745            } catch (RemoteException e) {
10746                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10747                mHandler.sendEmptyMessage(MCS_RECONNECT);
10748                res = false;
10749            }
10750            handleReturnCode();
10751            return res;
10752        }
10753
10754        final void serviceError() {
10755            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10756            handleServiceError();
10757            handleReturnCode();
10758        }
10759
10760        abstract void handleStartCopy() throws RemoteException;
10761        abstract void handleServiceError();
10762        abstract void handleReturnCode();
10763    }
10764
10765    class MeasureParams extends HandlerParams {
10766        private final PackageStats mStats;
10767        private boolean mSuccess;
10768
10769        private final IPackageStatsObserver mObserver;
10770
10771        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10772            super(new UserHandle(stats.userHandle));
10773            mObserver = observer;
10774            mStats = stats;
10775        }
10776
10777        @Override
10778        public String toString() {
10779            return "MeasureParams{"
10780                + Integer.toHexString(System.identityHashCode(this))
10781                + " " + mStats.packageName + "}";
10782        }
10783
10784        @Override
10785        void handleStartCopy() throws RemoteException {
10786            synchronized (mInstallLock) {
10787                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10788            }
10789
10790            if (mSuccess) {
10791                final boolean mounted;
10792                if (Environment.isExternalStorageEmulated()) {
10793                    mounted = true;
10794                } else {
10795                    final String status = Environment.getExternalStorageState();
10796                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10797                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10798                }
10799
10800                if (mounted) {
10801                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10802
10803                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10804                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10805
10806                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10807                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10808
10809                    // Always subtract cache size, since it's a subdirectory
10810                    mStats.externalDataSize -= mStats.externalCacheSize;
10811
10812                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10813                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10814
10815                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10816                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10817                }
10818            }
10819        }
10820
10821        @Override
10822        void handleReturnCode() {
10823            if (mObserver != null) {
10824                try {
10825                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10826                } catch (RemoteException e) {
10827                    Slog.i(TAG, "Observer no longer exists.");
10828                }
10829            }
10830        }
10831
10832        @Override
10833        void handleServiceError() {
10834            Slog.e(TAG, "Could not measure application " + mStats.packageName
10835                            + " external storage");
10836        }
10837    }
10838
10839    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10840            throws RemoteException {
10841        long result = 0;
10842        for (File path : paths) {
10843            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10844        }
10845        return result;
10846    }
10847
10848    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10849        for (File path : paths) {
10850            try {
10851                mcs.clearDirectory(path.getAbsolutePath());
10852            } catch (RemoteException e) {
10853            }
10854        }
10855    }
10856
10857    static class OriginInfo {
10858        /**
10859         * Location where install is coming from, before it has been
10860         * copied/renamed into place. This could be a single monolithic APK
10861         * file, or a cluster directory. This location may be untrusted.
10862         */
10863        final File file;
10864        final String cid;
10865
10866        /**
10867         * Flag indicating that {@link #file} or {@link #cid} has already been
10868         * staged, meaning downstream users don't need to defensively copy the
10869         * contents.
10870         */
10871        final boolean staged;
10872
10873        /**
10874         * Flag indicating that {@link #file} or {@link #cid} is an already
10875         * installed app that is being moved.
10876         */
10877        final boolean existing;
10878
10879        final String resolvedPath;
10880        final File resolvedFile;
10881
10882        static OriginInfo fromNothing() {
10883            return new OriginInfo(null, null, false, false);
10884        }
10885
10886        static OriginInfo fromUntrustedFile(File file) {
10887            return new OriginInfo(file, null, false, false);
10888        }
10889
10890        static OriginInfo fromExistingFile(File file) {
10891            return new OriginInfo(file, null, false, true);
10892        }
10893
10894        static OriginInfo fromStagedFile(File file) {
10895            return new OriginInfo(file, null, true, false);
10896        }
10897
10898        static OriginInfo fromStagedContainer(String cid) {
10899            return new OriginInfo(null, cid, true, false);
10900        }
10901
10902        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10903            this.file = file;
10904            this.cid = cid;
10905            this.staged = staged;
10906            this.existing = existing;
10907
10908            if (cid != null) {
10909                resolvedPath = PackageHelper.getSdDir(cid);
10910                resolvedFile = new File(resolvedPath);
10911            } else if (file != null) {
10912                resolvedPath = file.getAbsolutePath();
10913                resolvedFile = file;
10914            } else {
10915                resolvedPath = null;
10916                resolvedFile = null;
10917            }
10918        }
10919    }
10920
10921    class MoveInfo {
10922        final int moveId;
10923        final String fromUuid;
10924        final String toUuid;
10925        final String packageName;
10926        final String dataAppName;
10927        final int appId;
10928        final String seinfo;
10929
10930        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10931                String dataAppName, int appId, String seinfo) {
10932            this.moveId = moveId;
10933            this.fromUuid = fromUuid;
10934            this.toUuid = toUuid;
10935            this.packageName = packageName;
10936            this.dataAppName = dataAppName;
10937            this.appId = appId;
10938            this.seinfo = seinfo;
10939        }
10940    }
10941
10942    class InstallParams extends HandlerParams {
10943        final OriginInfo origin;
10944        final MoveInfo move;
10945        final IPackageInstallObserver2 observer;
10946        int installFlags;
10947        final String installerPackageName;
10948        final String volumeUuid;
10949        final VerificationParams verificationParams;
10950        private InstallArgs mArgs;
10951        private int mRet;
10952        final String packageAbiOverride;
10953        final String[] grantedRuntimePermissions;
10954
10955        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10956                int installFlags, String installerPackageName, String volumeUuid,
10957                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10958                String[] grantedPermissions) {
10959            super(user);
10960            this.origin = origin;
10961            this.move = move;
10962            this.observer = observer;
10963            this.installFlags = installFlags;
10964            this.installerPackageName = installerPackageName;
10965            this.volumeUuid = volumeUuid;
10966            this.verificationParams = verificationParams;
10967            this.packageAbiOverride = packageAbiOverride;
10968            this.grantedRuntimePermissions = grantedPermissions;
10969        }
10970
10971        @Override
10972        public String toString() {
10973            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10974                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10975        }
10976
10977        public ManifestDigest getManifestDigest() {
10978            if (verificationParams == null) {
10979                return null;
10980            }
10981            return verificationParams.getManifestDigest();
10982        }
10983
10984        private int installLocationPolicy(PackageInfoLite pkgLite) {
10985            String packageName = pkgLite.packageName;
10986            int installLocation = pkgLite.installLocation;
10987            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10988            // reader
10989            synchronized (mPackages) {
10990                PackageParser.Package pkg = mPackages.get(packageName);
10991                if (pkg != null) {
10992                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10993                        // Check for downgrading.
10994                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10995                            try {
10996                                checkDowngrade(pkg, pkgLite);
10997                            } catch (PackageManagerException e) {
10998                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10999                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11000                            }
11001                        }
11002                        // Check for updated system application.
11003                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11004                            if (onSd) {
11005                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11006                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11007                            }
11008                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11009                        } else {
11010                            if (onSd) {
11011                                // Install flag overrides everything.
11012                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11013                            }
11014                            // If current upgrade specifies particular preference
11015                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11016                                // Application explicitly specified internal.
11017                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11018                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11019                                // App explictly prefers external. Let policy decide
11020                            } else {
11021                                // Prefer previous location
11022                                if (isExternal(pkg)) {
11023                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11024                                }
11025                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11026                            }
11027                        }
11028                    } else {
11029                        // Invalid install. Return error code
11030                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11031                    }
11032                }
11033            }
11034            // All the special cases have been taken care of.
11035            // Return result based on recommended install location.
11036            if (onSd) {
11037                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11038            }
11039            return pkgLite.recommendedInstallLocation;
11040        }
11041
11042        /*
11043         * Invoke remote method to get package information and install
11044         * location values. Override install location based on default
11045         * policy if needed and then create install arguments based
11046         * on the install location.
11047         */
11048        public void handleStartCopy() throws RemoteException {
11049            int ret = PackageManager.INSTALL_SUCCEEDED;
11050
11051            // If we're already staged, we've firmly committed to an install location
11052            if (origin.staged) {
11053                if (origin.file != null) {
11054                    installFlags |= PackageManager.INSTALL_INTERNAL;
11055                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11056                } else if (origin.cid != null) {
11057                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11058                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11059                } else {
11060                    throw new IllegalStateException("Invalid stage location");
11061                }
11062            }
11063
11064            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11065            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11066            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11067            PackageInfoLite pkgLite = null;
11068
11069            if (onInt && onSd) {
11070                // Check if both bits are set.
11071                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11072                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11073            } else if (onSd && ephemeral) {
11074                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11075                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11076            } else {
11077                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11078                        packageAbiOverride);
11079
11080                if (DEBUG_EPHEMERAL && ephemeral) {
11081                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11082                }
11083
11084                /*
11085                 * If we have too little free space, try to free cache
11086                 * before giving up.
11087                 */
11088                if (!origin.staged && pkgLite.recommendedInstallLocation
11089                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11090                    // TODO: focus freeing disk space on the target device
11091                    final StorageManager storage = StorageManager.from(mContext);
11092                    final long lowThreshold = storage.getStorageLowBytes(
11093                            Environment.getDataDirectory());
11094
11095                    final long sizeBytes = mContainerService.calculateInstalledSize(
11096                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11097
11098                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11099                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11100                                installFlags, packageAbiOverride);
11101                    }
11102
11103                    /*
11104                     * The cache free must have deleted the file we
11105                     * downloaded to install.
11106                     *
11107                     * TODO: fix the "freeCache" call to not delete
11108                     *       the file we care about.
11109                     */
11110                    if (pkgLite.recommendedInstallLocation
11111                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11112                        pkgLite.recommendedInstallLocation
11113                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11114                    }
11115                }
11116            }
11117
11118            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11119                int loc = pkgLite.recommendedInstallLocation;
11120                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11121                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11122                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11123                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11124                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11125                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11126                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11127                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11128                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11129                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11130                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11131                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11132                } else {
11133                    // Override with defaults if needed.
11134                    loc = installLocationPolicy(pkgLite);
11135                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11136                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11137                    } else if (!onSd && !onInt) {
11138                        // Override install location with flags
11139                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11140                            // Set the flag to install on external media.
11141                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11142                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11143                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11144                            if (DEBUG_EPHEMERAL) {
11145                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11146                            }
11147                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11148                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11149                                    |PackageManager.INSTALL_INTERNAL);
11150                        } else {
11151                            // Make sure the flag for installing on external
11152                            // media is unset
11153                            installFlags |= PackageManager.INSTALL_INTERNAL;
11154                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11155                        }
11156                    }
11157                }
11158            }
11159
11160            final InstallArgs args = createInstallArgs(this);
11161            mArgs = args;
11162
11163            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11164                // TODO: http://b/22976637
11165                // Apps installed for "all" users use the device owner to verify the app
11166                UserHandle verifierUser = getUser();
11167                if (verifierUser == UserHandle.ALL) {
11168                    verifierUser = UserHandle.SYSTEM;
11169                }
11170
11171                /*
11172                 * Determine if we have any installed package verifiers. If we
11173                 * do, then we'll defer to them to verify the packages.
11174                 */
11175                final int requiredUid = mRequiredVerifierPackage == null ? -1
11176                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11177                if (!origin.existing && requiredUid != -1
11178                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11179                    final Intent verification = new Intent(
11180                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11181                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11182                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11183                            PACKAGE_MIME_TYPE);
11184                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11185
11186                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11187                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11188                            verifierUser.getIdentifier());
11189
11190                    if (DEBUG_VERIFY) {
11191                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11192                                + verification.toString() + " with " + pkgLite.verifiers.length
11193                                + " optional verifiers");
11194                    }
11195
11196                    final int verificationId = mPendingVerificationToken++;
11197
11198                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11199
11200                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11201                            installerPackageName);
11202
11203                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11204                            installFlags);
11205
11206                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11207                            pkgLite.packageName);
11208
11209                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11210                            pkgLite.versionCode);
11211
11212                    if (verificationParams != null) {
11213                        if (verificationParams.getVerificationURI() != null) {
11214                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11215                                 verificationParams.getVerificationURI());
11216                        }
11217                        if (verificationParams.getOriginatingURI() != null) {
11218                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11219                                  verificationParams.getOriginatingURI());
11220                        }
11221                        if (verificationParams.getReferrer() != null) {
11222                            verification.putExtra(Intent.EXTRA_REFERRER,
11223                                  verificationParams.getReferrer());
11224                        }
11225                        if (verificationParams.getOriginatingUid() >= 0) {
11226                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11227                                  verificationParams.getOriginatingUid());
11228                        }
11229                        if (verificationParams.getInstallerUid() >= 0) {
11230                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11231                                  verificationParams.getInstallerUid());
11232                        }
11233                    }
11234
11235                    final PackageVerificationState verificationState = new PackageVerificationState(
11236                            requiredUid, args);
11237
11238                    mPendingVerification.append(verificationId, verificationState);
11239
11240                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11241                            receivers, verificationState);
11242
11243                    /*
11244                     * If any sufficient verifiers were listed in the package
11245                     * manifest, attempt to ask them.
11246                     */
11247                    if (sufficientVerifiers != null) {
11248                        final int N = sufficientVerifiers.size();
11249                        if (N == 0) {
11250                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11251                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11252                        } else {
11253                            for (int i = 0; i < N; i++) {
11254                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11255
11256                                final Intent sufficientIntent = new Intent(verification);
11257                                sufficientIntent.setComponent(verifierComponent);
11258                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11259                            }
11260                        }
11261                    }
11262
11263                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11264                            mRequiredVerifierPackage, receivers);
11265                    if (ret == PackageManager.INSTALL_SUCCEEDED
11266                            && mRequiredVerifierPackage != null) {
11267                        Trace.asyncTraceBegin(
11268                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11269                        /*
11270                         * Send the intent to the required verification agent,
11271                         * but only start the verification timeout after the
11272                         * target BroadcastReceivers have run.
11273                         */
11274                        verification.setComponent(requiredVerifierComponent);
11275                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11276                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11277                                new BroadcastReceiver() {
11278                                    @Override
11279                                    public void onReceive(Context context, Intent intent) {
11280                                        final Message msg = mHandler
11281                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11282                                        msg.arg1 = verificationId;
11283                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11284                                    }
11285                                }, null, 0, null, null);
11286
11287                        /*
11288                         * We don't want the copy to proceed until verification
11289                         * succeeds, so null out this field.
11290                         */
11291                        mArgs = null;
11292                    }
11293                } else {
11294                    /*
11295                     * No package verification is enabled, so immediately start
11296                     * the remote call to initiate copy using temporary file.
11297                     */
11298                    ret = args.copyApk(mContainerService, true);
11299                }
11300            }
11301
11302            mRet = ret;
11303        }
11304
11305        @Override
11306        void handleReturnCode() {
11307            // If mArgs is null, then MCS couldn't be reached. When it
11308            // reconnects, it will try again to install. At that point, this
11309            // will succeed.
11310            if (mArgs != null) {
11311                processPendingInstall(mArgs, mRet);
11312            }
11313        }
11314
11315        @Override
11316        void handleServiceError() {
11317            mArgs = createInstallArgs(this);
11318            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11319        }
11320
11321        public boolean isForwardLocked() {
11322            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11323        }
11324    }
11325
11326    /**
11327     * Used during creation of InstallArgs
11328     *
11329     * @param installFlags package installation flags
11330     * @return true if should be installed on external storage
11331     */
11332    private static boolean installOnExternalAsec(int installFlags) {
11333        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11334            return false;
11335        }
11336        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11337            return true;
11338        }
11339        return false;
11340    }
11341
11342    /**
11343     * Used during creation of InstallArgs
11344     *
11345     * @param installFlags package installation flags
11346     * @return true if should be installed as forward locked
11347     */
11348    private static boolean installForwardLocked(int installFlags) {
11349        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11350    }
11351
11352    private InstallArgs createInstallArgs(InstallParams params) {
11353        if (params.move != null) {
11354            return new MoveInstallArgs(params);
11355        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11356            return new AsecInstallArgs(params);
11357        } else {
11358            return new FileInstallArgs(params);
11359        }
11360    }
11361
11362    /**
11363     * Create args that describe an existing installed package. Typically used
11364     * when cleaning up old installs, or used as a move source.
11365     */
11366    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11367            String resourcePath, String[] instructionSets) {
11368        final boolean isInAsec;
11369        if (installOnExternalAsec(installFlags)) {
11370            /* Apps on SD card are always in ASEC containers. */
11371            isInAsec = true;
11372        } else if (installForwardLocked(installFlags)
11373                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11374            /*
11375             * Forward-locked apps are only in ASEC containers if they're the
11376             * new style
11377             */
11378            isInAsec = true;
11379        } else {
11380            isInAsec = false;
11381        }
11382
11383        if (isInAsec) {
11384            return new AsecInstallArgs(codePath, instructionSets,
11385                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11386        } else {
11387            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11388        }
11389    }
11390
11391    static abstract class InstallArgs {
11392        /** @see InstallParams#origin */
11393        final OriginInfo origin;
11394        /** @see InstallParams#move */
11395        final MoveInfo move;
11396
11397        final IPackageInstallObserver2 observer;
11398        // Always refers to PackageManager flags only
11399        final int installFlags;
11400        final String installerPackageName;
11401        final String volumeUuid;
11402        final ManifestDigest manifestDigest;
11403        final UserHandle user;
11404        final String abiOverride;
11405        final String[] installGrantPermissions;
11406        /** If non-null, drop an async trace when the install completes */
11407        final String traceMethod;
11408        final int traceCookie;
11409
11410        // The list of instruction sets supported by this app. This is currently
11411        // only used during the rmdex() phase to clean up resources. We can get rid of this
11412        // if we move dex files under the common app path.
11413        /* nullable */ String[] instructionSets;
11414
11415        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11416                int installFlags, String installerPackageName, String volumeUuid,
11417                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11418                String abiOverride, String[] installGrantPermissions,
11419                String traceMethod, int traceCookie) {
11420            this.origin = origin;
11421            this.move = move;
11422            this.installFlags = installFlags;
11423            this.observer = observer;
11424            this.installerPackageName = installerPackageName;
11425            this.volumeUuid = volumeUuid;
11426            this.manifestDigest = manifestDigest;
11427            this.user = user;
11428            this.instructionSets = instructionSets;
11429            this.abiOverride = abiOverride;
11430            this.installGrantPermissions = installGrantPermissions;
11431            this.traceMethod = traceMethod;
11432            this.traceCookie = traceCookie;
11433        }
11434
11435        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11436        abstract int doPreInstall(int status);
11437
11438        /**
11439         * Rename package into final resting place. All paths on the given
11440         * scanned package should be updated to reflect the rename.
11441         */
11442        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11443        abstract int doPostInstall(int status, int uid);
11444
11445        /** @see PackageSettingBase#codePathString */
11446        abstract String getCodePath();
11447        /** @see PackageSettingBase#resourcePathString */
11448        abstract String getResourcePath();
11449
11450        // Need installer lock especially for dex file removal.
11451        abstract void cleanUpResourcesLI();
11452        abstract boolean doPostDeleteLI(boolean delete);
11453
11454        /**
11455         * Called before the source arguments are copied. This is used mostly
11456         * for MoveParams when it needs to read the source file to put it in the
11457         * destination.
11458         */
11459        int doPreCopy() {
11460            return PackageManager.INSTALL_SUCCEEDED;
11461        }
11462
11463        /**
11464         * Called after the source arguments are copied. This is used mostly for
11465         * MoveParams when it needs to read the source file to put it in the
11466         * destination.
11467         *
11468         * @return
11469         */
11470        int doPostCopy(int uid) {
11471            return PackageManager.INSTALL_SUCCEEDED;
11472        }
11473
11474        protected boolean isFwdLocked() {
11475            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11476        }
11477
11478        protected boolean isExternalAsec() {
11479            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11480        }
11481
11482        protected boolean isEphemeral() {
11483            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11484        }
11485
11486        UserHandle getUser() {
11487            return user;
11488        }
11489    }
11490
11491    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11492        if (!allCodePaths.isEmpty()) {
11493            if (instructionSets == null) {
11494                throw new IllegalStateException("instructionSet == null");
11495            }
11496            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11497            for (String codePath : allCodePaths) {
11498                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11499                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11500                    if (retCode < 0) {
11501                        Slog.w(TAG, "Couldn't remove dex file for package: "
11502                                + " at location " + codePath + ", retcode=" + retCode);
11503                        // we don't consider this to be a failure of the core package deletion
11504                    }
11505                }
11506            }
11507        }
11508    }
11509
11510    /**
11511     * Logic to handle installation of non-ASEC applications, including copying
11512     * and renaming logic.
11513     */
11514    class FileInstallArgs extends InstallArgs {
11515        private File codeFile;
11516        private File resourceFile;
11517
11518        // Example topology:
11519        // /data/app/com.example/base.apk
11520        // /data/app/com.example/split_foo.apk
11521        // /data/app/com.example/lib/arm/libfoo.so
11522        // /data/app/com.example/lib/arm64/libfoo.so
11523        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11524
11525        /** New install */
11526        FileInstallArgs(InstallParams params) {
11527            super(params.origin, params.move, params.observer, params.installFlags,
11528                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11529                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11530                    params.grantedRuntimePermissions,
11531                    params.traceMethod, params.traceCookie);
11532            if (isFwdLocked()) {
11533                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11534            }
11535        }
11536
11537        /** Existing install */
11538        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11539            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11540                    null, null, null, 0);
11541            this.codeFile = (codePath != null) ? new File(codePath) : null;
11542            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11543        }
11544
11545        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11546            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11547            try {
11548                return doCopyApk(imcs, temp);
11549            } finally {
11550                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11551            }
11552        }
11553
11554        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11555            if (origin.staged) {
11556                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11557                codeFile = origin.file;
11558                resourceFile = origin.file;
11559                return PackageManager.INSTALL_SUCCEEDED;
11560            }
11561
11562            try {
11563                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11564                final File tempDir =
11565                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11566                codeFile = tempDir;
11567                resourceFile = tempDir;
11568            } catch (IOException e) {
11569                Slog.w(TAG, "Failed to create copy file: " + e);
11570                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11571            }
11572
11573            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11574                @Override
11575                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11576                    if (!FileUtils.isValidExtFilename(name)) {
11577                        throw new IllegalArgumentException("Invalid filename: " + name);
11578                    }
11579                    try {
11580                        final File file = new File(codeFile, name);
11581                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11582                                O_RDWR | O_CREAT, 0644);
11583                        Os.chmod(file.getAbsolutePath(), 0644);
11584                        return new ParcelFileDescriptor(fd);
11585                    } catch (ErrnoException e) {
11586                        throw new RemoteException("Failed to open: " + e.getMessage());
11587                    }
11588                }
11589            };
11590
11591            int ret = PackageManager.INSTALL_SUCCEEDED;
11592            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11593            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11594                Slog.e(TAG, "Failed to copy package");
11595                return ret;
11596            }
11597
11598            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11599            NativeLibraryHelper.Handle handle = null;
11600            try {
11601                handle = NativeLibraryHelper.Handle.create(codeFile);
11602                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11603                        abiOverride);
11604            } catch (IOException e) {
11605                Slog.e(TAG, "Copying native libraries failed", e);
11606                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11607            } finally {
11608                IoUtils.closeQuietly(handle);
11609            }
11610
11611            return ret;
11612        }
11613
11614        int doPreInstall(int status) {
11615            if (status != PackageManager.INSTALL_SUCCEEDED) {
11616                cleanUp();
11617            }
11618            return status;
11619        }
11620
11621        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11622            if (status != PackageManager.INSTALL_SUCCEEDED) {
11623                cleanUp();
11624                return false;
11625            }
11626
11627            final File targetDir = codeFile.getParentFile();
11628            final File beforeCodeFile = codeFile;
11629            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11630
11631            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11632            try {
11633                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11634            } catch (ErrnoException e) {
11635                Slog.w(TAG, "Failed to rename", e);
11636                return false;
11637            }
11638
11639            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11640                Slog.w(TAG, "Failed to restorecon");
11641                return false;
11642            }
11643
11644            // Reflect the rename internally
11645            codeFile = afterCodeFile;
11646            resourceFile = afterCodeFile;
11647
11648            // Reflect the rename in scanned details
11649            pkg.codePath = afterCodeFile.getAbsolutePath();
11650            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11651                    pkg.baseCodePath);
11652            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11653                    pkg.splitCodePaths);
11654
11655            // Reflect the rename in app info
11656            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11657            pkg.applicationInfo.setCodePath(pkg.codePath);
11658            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11659            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11660            pkg.applicationInfo.setResourcePath(pkg.codePath);
11661            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11662            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11663
11664            return true;
11665        }
11666
11667        int doPostInstall(int status, int uid) {
11668            if (status != PackageManager.INSTALL_SUCCEEDED) {
11669                cleanUp();
11670            }
11671            return status;
11672        }
11673
11674        @Override
11675        String getCodePath() {
11676            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11677        }
11678
11679        @Override
11680        String getResourcePath() {
11681            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11682        }
11683
11684        private boolean cleanUp() {
11685            if (codeFile == null || !codeFile.exists()) {
11686                return false;
11687            }
11688
11689            if (codeFile.isDirectory()) {
11690                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11691            } else {
11692                codeFile.delete();
11693            }
11694
11695            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11696                resourceFile.delete();
11697            }
11698
11699            return true;
11700        }
11701
11702        void cleanUpResourcesLI() {
11703            // Try enumerating all code paths before deleting
11704            List<String> allCodePaths = Collections.EMPTY_LIST;
11705            if (codeFile != null && codeFile.exists()) {
11706                try {
11707                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11708                    allCodePaths = pkg.getAllCodePaths();
11709                } catch (PackageParserException e) {
11710                    // Ignored; we tried our best
11711                }
11712            }
11713
11714            cleanUp();
11715            removeDexFiles(allCodePaths, instructionSets);
11716        }
11717
11718        boolean doPostDeleteLI(boolean delete) {
11719            // XXX err, shouldn't we respect the delete flag?
11720            cleanUpResourcesLI();
11721            return true;
11722        }
11723    }
11724
11725    private boolean isAsecExternal(String cid) {
11726        final String asecPath = PackageHelper.getSdFilesystem(cid);
11727        return !asecPath.startsWith(mAsecInternalPath);
11728    }
11729
11730    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11731            PackageManagerException {
11732        if (copyRet < 0) {
11733            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11734                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11735                throw new PackageManagerException(copyRet, message);
11736            }
11737        }
11738    }
11739
11740    /**
11741     * Extract the MountService "container ID" from the full code path of an
11742     * .apk.
11743     */
11744    static String cidFromCodePath(String fullCodePath) {
11745        int eidx = fullCodePath.lastIndexOf("/");
11746        String subStr1 = fullCodePath.substring(0, eidx);
11747        int sidx = subStr1.lastIndexOf("/");
11748        return subStr1.substring(sidx+1, eidx);
11749    }
11750
11751    /**
11752     * Logic to handle installation of ASEC applications, including copying and
11753     * renaming logic.
11754     */
11755    class AsecInstallArgs extends InstallArgs {
11756        static final String RES_FILE_NAME = "pkg.apk";
11757        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11758
11759        String cid;
11760        String packagePath;
11761        String resourcePath;
11762
11763        /** New install */
11764        AsecInstallArgs(InstallParams params) {
11765            super(params.origin, params.move, params.observer, params.installFlags,
11766                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11767                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11768                    params.grantedRuntimePermissions,
11769                    params.traceMethod, params.traceCookie);
11770        }
11771
11772        /** Existing install */
11773        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11774                        boolean isExternal, boolean isForwardLocked) {
11775            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11776                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11777                    instructionSets, null, null, null, 0);
11778            // Hackily pretend we're still looking at a full code path
11779            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11780                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11781            }
11782
11783            // Extract cid from fullCodePath
11784            int eidx = fullCodePath.lastIndexOf("/");
11785            String subStr1 = fullCodePath.substring(0, eidx);
11786            int sidx = subStr1.lastIndexOf("/");
11787            cid = subStr1.substring(sidx+1, eidx);
11788            setMountPath(subStr1);
11789        }
11790
11791        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11792            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11793                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11794                    instructionSets, null, null, null, 0);
11795            this.cid = cid;
11796            setMountPath(PackageHelper.getSdDir(cid));
11797        }
11798
11799        void createCopyFile() {
11800            cid = mInstallerService.allocateExternalStageCidLegacy();
11801        }
11802
11803        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11804            if (origin.staged && origin.cid != null) {
11805                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11806                cid = origin.cid;
11807                setMountPath(PackageHelper.getSdDir(cid));
11808                return PackageManager.INSTALL_SUCCEEDED;
11809            }
11810
11811            if (temp) {
11812                createCopyFile();
11813            } else {
11814                /*
11815                 * Pre-emptively destroy the container since it's destroyed if
11816                 * copying fails due to it existing anyway.
11817                 */
11818                PackageHelper.destroySdDir(cid);
11819            }
11820
11821            final String newMountPath = imcs.copyPackageToContainer(
11822                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11823                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11824
11825            if (newMountPath != null) {
11826                setMountPath(newMountPath);
11827                return PackageManager.INSTALL_SUCCEEDED;
11828            } else {
11829                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11830            }
11831        }
11832
11833        @Override
11834        String getCodePath() {
11835            return packagePath;
11836        }
11837
11838        @Override
11839        String getResourcePath() {
11840            return resourcePath;
11841        }
11842
11843        int doPreInstall(int status) {
11844            if (status != PackageManager.INSTALL_SUCCEEDED) {
11845                // Destroy container
11846                PackageHelper.destroySdDir(cid);
11847            } else {
11848                boolean mounted = PackageHelper.isContainerMounted(cid);
11849                if (!mounted) {
11850                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11851                            Process.SYSTEM_UID);
11852                    if (newMountPath != null) {
11853                        setMountPath(newMountPath);
11854                    } else {
11855                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11856                    }
11857                }
11858            }
11859            return status;
11860        }
11861
11862        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11863            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11864            String newMountPath = null;
11865            if (PackageHelper.isContainerMounted(cid)) {
11866                // Unmount the container
11867                if (!PackageHelper.unMountSdDir(cid)) {
11868                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11869                    return false;
11870                }
11871            }
11872            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11873                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11874                        " which might be stale. Will try to clean up.");
11875                // Clean up the stale container and proceed to recreate.
11876                if (!PackageHelper.destroySdDir(newCacheId)) {
11877                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11878                    return false;
11879                }
11880                // Successfully cleaned up stale container. Try to rename again.
11881                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11882                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11883                            + " inspite of cleaning it up.");
11884                    return false;
11885                }
11886            }
11887            if (!PackageHelper.isContainerMounted(newCacheId)) {
11888                Slog.w(TAG, "Mounting container " + newCacheId);
11889                newMountPath = PackageHelper.mountSdDir(newCacheId,
11890                        getEncryptKey(), Process.SYSTEM_UID);
11891            } else {
11892                newMountPath = PackageHelper.getSdDir(newCacheId);
11893            }
11894            if (newMountPath == null) {
11895                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11896                return false;
11897            }
11898            Log.i(TAG, "Succesfully renamed " + cid +
11899                    " to " + newCacheId +
11900                    " at new path: " + newMountPath);
11901            cid = newCacheId;
11902
11903            final File beforeCodeFile = new File(packagePath);
11904            setMountPath(newMountPath);
11905            final File afterCodeFile = new File(packagePath);
11906
11907            // Reflect the rename in scanned details
11908            pkg.codePath = afterCodeFile.getAbsolutePath();
11909            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11910                    pkg.baseCodePath);
11911            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11912                    pkg.splitCodePaths);
11913
11914            // Reflect the rename in app info
11915            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11916            pkg.applicationInfo.setCodePath(pkg.codePath);
11917            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11918            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11919            pkg.applicationInfo.setResourcePath(pkg.codePath);
11920            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11921            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11922
11923            return true;
11924        }
11925
11926        private void setMountPath(String mountPath) {
11927            final File mountFile = new File(mountPath);
11928
11929            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11930            if (monolithicFile.exists()) {
11931                packagePath = monolithicFile.getAbsolutePath();
11932                if (isFwdLocked()) {
11933                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11934                } else {
11935                    resourcePath = packagePath;
11936                }
11937            } else {
11938                packagePath = mountFile.getAbsolutePath();
11939                resourcePath = packagePath;
11940            }
11941        }
11942
11943        int doPostInstall(int status, int uid) {
11944            if (status != PackageManager.INSTALL_SUCCEEDED) {
11945                cleanUp();
11946            } else {
11947                final int groupOwner;
11948                final String protectedFile;
11949                if (isFwdLocked()) {
11950                    groupOwner = UserHandle.getSharedAppGid(uid);
11951                    protectedFile = RES_FILE_NAME;
11952                } else {
11953                    groupOwner = -1;
11954                    protectedFile = null;
11955                }
11956
11957                if (uid < Process.FIRST_APPLICATION_UID
11958                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11959                    Slog.e(TAG, "Failed to finalize " + cid);
11960                    PackageHelper.destroySdDir(cid);
11961                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11962                }
11963
11964                boolean mounted = PackageHelper.isContainerMounted(cid);
11965                if (!mounted) {
11966                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11967                }
11968            }
11969            return status;
11970        }
11971
11972        private void cleanUp() {
11973            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11974
11975            // Destroy secure container
11976            PackageHelper.destroySdDir(cid);
11977        }
11978
11979        private List<String> getAllCodePaths() {
11980            final File codeFile = new File(getCodePath());
11981            if (codeFile != null && codeFile.exists()) {
11982                try {
11983                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11984                    return pkg.getAllCodePaths();
11985                } catch (PackageParserException e) {
11986                    // Ignored; we tried our best
11987                }
11988            }
11989            return Collections.EMPTY_LIST;
11990        }
11991
11992        void cleanUpResourcesLI() {
11993            // Enumerate all code paths before deleting
11994            cleanUpResourcesLI(getAllCodePaths());
11995        }
11996
11997        private void cleanUpResourcesLI(List<String> allCodePaths) {
11998            cleanUp();
11999            removeDexFiles(allCodePaths, instructionSets);
12000        }
12001
12002        String getPackageName() {
12003            return getAsecPackageName(cid);
12004        }
12005
12006        boolean doPostDeleteLI(boolean delete) {
12007            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12008            final List<String> allCodePaths = getAllCodePaths();
12009            boolean mounted = PackageHelper.isContainerMounted(cid);
12010            if (mounted) {
12011                // Unmount first
12012                if (PackageHelper.unMountSdDir(cid)) {
12013                    mounted = false;
12014                }
12015            }
12016            if (!mounted && delete) {
12017                cleanUpResourcesLI(allCodePaths);
12018            }
12019            return !mounted;
12020        }
12021
12022        @Override
12023        int doPreCopy() {
12024            if (isFwdLocked()) {
12025                if (!PackageHelper.fixSdPermissions(cid,
12026                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12027                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12028                }
12029            }
12030
12031            return PackageManager.INSTALL_SUCCEEDED;
12032        }
12033
12034        @Override
12035        int doPostCopy(int uid) {
12036            if (isFwdLocked()) {
12037                if (uid < Process.FIRST_APPLICATION_UID
12038                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12039                                RES_FILE_NAME)) {
12040                    Slog.e(TAG, "Failed to finalize " + cid);
12041                    PackageHelper.destroySdDir(cid);
12042                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12043                }
12044            }
12045
12046            return PackageManager.INSTALL_SUCCEEDED;
12047        }
12048    }
12049
12050    /**
12051     * Logic to handle movement of existing installed applications.
12052     */
12053    class MoveInstallArgs extends InstallArgs {
12054        private File codeFile;
12055        private File resourceFile;
12056
12057        /** New install */
12058        MoveInstallArgs(InstallParams params) {
12059            super(params.origin, params.move, params.observer, params.installFlags,
12060                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
12061                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12062                    params.grantedRuntimePermissions,
12063                    params.traceMethod, params.traceCookie);
12064        }
12065
12066        int copyApk(IMediaContainerService imcs, boolean temp) {
12067            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12068                    + move.fromUuid + " to " + move.toUuid);
12069            synchronized (mInstaller) {
12070                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12071                        move.dataAppName, move.appId, move.seinfo) != 0) {
12072                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12073                }
12074            }
12075
12076            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12077            resourceFile = codeFile;
12078            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12079
12080            return PackageManager.INSTALL_SUCCEEDED;
12081        }
12082
12083        int doPreInstall(int status) {
12084            if (status != PackageManager.INSTALL_SUCCEEDED) {
12085                cleanUp(move.toUuid);
12086            }
12087            return status;
12088        }
12089
12090        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12091            if (status != PackageManager.INSTALL_SUCCEEDED) {
12092                cleanUp(move.toUuid);
12093                return false;
12094            }
12095
12096            // Reflect the move in app info
12097            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12098            pkg.applicationInfo.setCodePath(pkg.codePath);
12099            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12100            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12101            pkg.applicationInfo.setResourcePath(pkg.codePath);
12102            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12103            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12104
12105            return true;
12106        }
12107
12108        int doPostInstall(int status, int uid) {
12109            if (status == PackageManager.INSTALL_SUCCEEDED) {
12110                cleanUp(move.fromUuid);
12111            } else {
12112                cleanUp(move.toUuid);
12113            }
12114            return status;
12115        }
12116
12117        @Override
12118        String getCodePath() {
12119            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12120        }
12121
12122        @Override
12123        String getResourcePath() {
12124            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12125        }
12126
12127        private boolean cleanUp(String volumeUuid) {
12128            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12129                    move.dataAppName);
12130            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12131            synchronized (mInstallLock) {
12132                // Clean up both app data and code
12133                removeDataDirsLI(volumeUuid, move.packageName);
12134                if (codeFile.isDirectory()) {
12135                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12136                } else {
12137                    codeFile.delete();
12138                }
12139            }
12140            return true;
12141        }
12142
12143        void cleanUpResourcesLI() {
12144            throw new UnsupportedOperationException();
12145        }
12146
12147        boolean doPostDeleteLI(boolean delete) {
12148            throw new UnsupportedOperationException();
12149        }
12150    }
12151
12152    static String getAsecPackageName(String packageCid) {
12153        int idx = packageCid.lastIndexOf("-");
12154        if (idx == -1) {
12155            return packageCid;
12156        }
12157        return packageCid.substring(0, idx);
12158    }
12159
12160    // Utility method used to create code paths based on package name and available index.
12161    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12162        String idxStr = "";
12163        int idx = 1;
12164        // Fall back to default value of idx=1 if prefix is not
12165        // part of oldCodePath
12166        if (oldCodePath != null) {
12167            String subStr = oldCodePath;
12168            // Drop the suffix right away
12169            if (suffix != null && subStr.endsWith(suffix)) {
12170                subStr = subStr.substring(0, subStr.length() - suffix.length());
12171            }
12172            // If oldCodePath already contains prefix find out the
12173            // ending index to either increment or decrement.
12174            int sidx = subStr.lastIndexOf(prefix);
12175            if (sidx != -1) {
12176                subStr = subStr.substring(sidx + prefix.length());
12177                if (subStr != null) {
12178                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12179                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12180                    }
12181                    try {
12182                        idx = Integer.parseInt(subStr);
12183                        if (idx <= 1) {
12184                            idx++;
12185                        } else {
12186                            idx--;
12187                        }
12188                    } catch(NumberFormatException e) {
12189                    }
12190                }
12191            }
12192        }
12193        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12194        return prefix + idxStr;
12195    }
12196
12197    private File getNextCodePath(File targetDir, String packageName) {
12198        int suffix = 1;
12199        File result;
12200        do {
12201            result = new File(targetDir, packageName + "-" + suffix);
12202            suffix++;
12203        } while (result.exists());
12204        return result;
12205    }
12206
12207    // Utility method that returns the relative package path with respect
12208    // to the installation directory. Like say for /data/data/com.test-1.apk
12209    // string com.test-1 is returned.
12210    static String deriveCodePathName(String codePath) {
12211        if (codePath == null) {
12212            return null;
12213        }
12214        final File codeFile = new File(codePath);
12215        final String name = codeFile.getName();
12216        if (codeFile.isDirectory()) {
12217            return name;
12218        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12219            final int lastDot = name.lastIndexOf('.');
12220            return name.substring(0, lastDot);
12221        } else {
12222            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12223            return null;
12224        }
12225    }
12226
12227    class PackageInstalledInfo {
12228        String name;
12229        int uid;
12230        // The set of users that originally had this package installed.
12231        int[] origUsers;
12232        // The set of users that now have this package installed.
12233        int[] newUsers;
12234        PackageParser.Package pkg;
12235        int returnCode;
12236        String returnMsg;
12237        PackageRemovedInfo removedInfo;
12238
12239        public void setError(int code, String msg) {
12240            returnCode = code;
12241            returnMsg = msg;
12242            Slog.w(TAG, msg);
12243        }
12244
12245        public void setError(String msg, PackageParserException e) {
12246            returnCode = e.error;
12247            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12248            Slog.w(TAG, msg, e);
12249        }
12250
12251        public void setError(String msg, PackageManagerException e) {
12252            returnCode = e.error;
12253            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12254            Slog.w(TAG, msg, e);
12255        }
12256
12257        // In some error cases we want to convey more info back to the observer
12258        String origPackage;
12259        String origPermission;
12260    }
12261
12262    /*
12263     * Install a non-existing package.
12264     */
12265    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12266            UserHandle user, String installerPackageName, String volumeUuid,
12267            PackageInstalledInfo res) {
12268        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12269
12270        // Remember this for later, in case we need to rollback this install
12271        String pkgName = pkg.packageName;
12272
12273        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12274        // TODO: b/23350563
12275        final boolean dataDirExists = Environment
12276                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12277
12278        synchronized(mPackages) {
12279            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12280                // A package with the same name is already installed, though
12281                // it has been renamed to an older name.  The package we
12282                // are trying to install should be installed as an update to
12283                // the existing one, but that has not been requested, so bail.
12284                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12285                        + " without first uninstalling package running as "
12286                        + mSettings.mRenamedPackages.get(pkgName));
12287                return;
12288            }
12289            if (mPackages.containsKey(pkgName)) {
12290                // Don't allow installation over an existing package with the same name.
12291                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12292                        + " without first uninstalling.");
12293                return;
12294            }
12295        }
12296
12297        try {
12298            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12299                    System.currentTimeMillis(), user);
12300
12301            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12302            // delete the partially installed application. the data directory will have to be
12303            // restored if it was already existing
12304            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12305                // remove package from internal structures.  Note that we want deletePackageX to
12306                // delete the package data and cache directories that it created in
12307                // scanPackageLocked, unless those directories existed before we even tried to
12308                // install.
12309                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12310                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12311                                res.removedInfo, true);
12312            }
12313
12314        } catch (PackageManagerException e) {
12315            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12316        }
12317
12318        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12319    }
12320
12321    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12322        // Can't rotate keys during boot or if sharedUser.
12323        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12324                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12325            return false;
12326        }
12327        // app is using upgradeKeySets; make sure all are valid
12328        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12329        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12330        for (int i = 0; i < upgradeKeySets.length; i++) {
12331            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12332                Slog.wtf(TAG, "Package "
12333                         + (oldPs.name != null ? oldPs.name : "<null>")
12334                         + " contains upgrade-key-set reference to unknown key-set: "
12335                         + upgradeKeySets[i]
12336                         + " reverting to signatures check.");
12337                return false;
12338            }
12339        }
12340        return true;
12341    }
12342
12343    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12344        // Upgrade keysets are being used.  Determine if new package has a superset of the
12345        // required keys.
12346        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12347        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12348        for (int i = 0; i < upgradeKeySets.length; i++) {
12349            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12350            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12351                return true;
12352            }
12353        }
12354        return false;
12355    }
12356
12357    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12358            UserHandle user, String installerPackageName, String volumeUuid,
12359            PackageInstalledInfo res) {
12360        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12361
12362        final PackageParser.Package oldPackage;
12363        final String pkgName = pkg.packageName;
12364        final int[] allUsers;
12365        final boolean[] perUserInstalled;
12366
12367        // First find the old package info and check signatures
12368        synchronized(mPackages) {
12369            oldPackage = mPackages.get(pkgName);
12370            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12371            if (isEphemeral && !oldIsEphemeral) {
12372                // can't downgrade from full to ephemeral
12373                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12374                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12375                return;
12376            }
12377            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12378            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12379            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12380                if(!checkUpgradeKeySetLP(ps, pkg)) {
12381                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12382                            "New package not signed by keys specified by upgrade-keysets: "
12383                            + pkgName);
12384                    return;
12385                }
12386            } else {
12387                // default to original signature matching
12388                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12389                    != PackageManager.SIGNATURE_MATCH) {
12390                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12391                            "New package has a different signature: " + pkgName);
12392                    return;
12393                }
12394            }
12395
12396            // In case of rollback, remember per-user/profile install state
12397            allUsers = sUserManager.getUserIds();
12398            perUserInstalled = new boolean[allUsers.length];
12399            for (int i = 0; i < allUsers.length; i++) {
12400                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12401            }
12402        }
12403
12404        boolean sysPkg = (isSystemApp(oldPackage));
12405        if (sysPkg) {
12406            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12407                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12408        } else {
12409            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12410                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12411        }
12412    }
12413
12414    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12415            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12416            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12417            String volumeUuid, PackageInstalledInfo res) {
12418        String pkgName = deletedPackage.packageName;
12419        boolean deletedPkg = true;
12420        boolean updatedSettings = false;
12421
12422        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12423                + deletedPackage);
12424        long origUpdateTime;
12425        if (pkg.mExtras != null) {
12426            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12427        } else {
12428            origUpdateTime = 0;
12429        }
12430
12431        // First delete the existing package while retaining the data directory
12432        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12433                res.removedInfo, true)) {
12434            // If the existing package wasn't successfully deleted
12435            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12436            deletedPkg = false;
12437        } else {
12438            // Successfully deleted the old package; proceed with replace.
12439
12440            // If deleted package lived in a container, give users a chance to
12441            // relinquish resources before killing.
12442            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12443                if (DEBUG_INSTALL) {
12444                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12445                }
12446                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12447                final ArrayList<String> pkgList = new ArrayList<String>(1);
12448                pkgList.add(deletedPackage.applicationInfo.packageName);
12449                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12450            }
12451
12452            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12453            try {
12454                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12455                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12456                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12457                        perUserInstalled, res, user);
12458                updatedSettings = true;
12459            } catch (PackageManagerException e) {
12460                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12461            }
12462        }
12463
12464        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12465            // remove package from internal structures.  Note that we want deletePackageX to
12466            // delete the package data and cache directories that it created in
12467            // scanPackageLocked, unless those directories existed before we even tried to
12468            // install.
12469            if(updatedSettings) {
12470                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12471                deletePackageLI(
12472                        pkgName, null, true, allUsers, perUserInstalled,
12473                        PackageManager.DELETE_KEEP_DATA,
12474                                res.removedInfo, true);
12475            }
12476            // Since we failed to install the new package we need to restore the old
12477            // package that we deleted.
12478            if (deletedPkg) {
12479                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12480                File restoreFile = new File(deletedPackage.codePath);
12481                // Parse old package
12482                boolean oldExternal = isExternal(deletedPackage);
12483                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12484                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12485                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12486                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12487                try {
12488                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12489                            null);
12490                } catch (PackageManagerException e) {
12491                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12492                            + e.getMessage());
12493                    return;
12494                }
12495                // Restore of old package succeeded. Update permissions.
12496                // writer
12497                synchronized (mPackages) {
12498                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12499                            UPDATE_PERMISSIONS_ALL);
12500                    // can downgrade to reader
12501                    mSettings.writeLPr();
12502                }
12503                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12504            }
12505        }
12506    }
12507
12508    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12509            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12510            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12511            String volumeUuid, PackageInstalledInfo res) {
12512        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12513                + ", old=" + deletedPackage);
12514        boolean disabledSystem = false;
12515        boolean updatedSettings = false;
12516        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12517        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12518                != 0) {
12519            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12520        }
12521        String packageName = deletedPackage.packageName;
12522        if (packageName == null) {
12523            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12524                    "Attempt to delete null packageName.");
12525            return;
12526        }
12527        PackageParser.Package oldPkg;
12528        PackageSetting oldPkgSetting;
12529        // reader
12530        synchronized (mPackages) {
12531            oldPkg = mPackages.get(packageName);
12532            oldPkgSetting = mSettings.mPackages.get(packageName);
12533            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12534                    (oldPkgSetting == null)) {
12535                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12536                        "Couldn't find package:" + packageName + " information");
12537                return;
12538            }
12539        }
12540
12541        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12542
12543        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12544        res.removedInfo.removedPackage = packageName;
12545        // Remove existing system package
12546        removePackageLI(oldPkgSetting, true);
12547        // writer
12548        synchronized (mPackages) {
12549            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12550            if (!disabledSystem && deletedPackage != null) {
12551                // We didn't need to disable the .apk as a current system package,
12552                // which means we are replacing another update that is already
12553                // installed.  We need to make sure to delete the older one's .apk.
12554                res.removedInfo.args = createInstallArgsForExisting(0,
12555                        deletedPackage.applicationInfo.getCodePath(),
12556                        deletedPackage.applicationInfo.getResourcePath(),
12557                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12558            } else {
12559                res.removedInfo.args = null;
12560            }
12561        }
12562
12563        // Successfully disabled the old package. Now proceed with re-installation
12564        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12565
12566        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12567        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12568
12569        PackageParser.Package newPackage = null;
12570        try {
12571            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12572            if (newPackage.mExtras != null) {
12573                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12574                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12575                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12576
12577                // is the update attempting to change shared user? that isn't going to work...
12578                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12579                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12580                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12581                            + " to " + newPkgSetting.sharedUser);
12582                    updatedSettings = true;
12583                }
12584            }
12585
12586            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12587                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12588                        perUserInstalled, res, user);
12589                updatedSettings = true;
12590            }
12591
12592        } catch (PackageManagerException e) {
12593            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12594        }
12595
12596        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12597            // Re installation failed. Restore old information
12598            // Remove new pkg information
12599            if (newPackage != null) {
12600                removeInstalledPackageLI(newPackage, true);
12601            }
12602            // Add back the old system package
12603            try {
12604                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12605            } catch (PackageManagerException e) {
12606                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12607            }
12608            // Restore the old system information in Settings
12609            synchronized (mPackages) {
12610                if (disabledSystem) {
12611                    mSettings.enableSystemPackageLPw(packageName);
12612                }
12613                if (updatedSettings) {
12614                    mSettings.setInstallerPackageName(packageName,
12615                            oldPkgSetting.installerPackageName);
12616                }
12617                mSettings.writeLPr();
12618            }
12619        }
12620    }
12621
12622    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12623        // Collect all used permissions in the UID
12624        ArraySet<String> usedPermissions = new ArraySet<>();
12625        final int packageCount = su.packages.size();
12626        for (int i = 0; i < packageCount; i++) {
12627            PackageSetting ps = su.packages.valueAt(i);
12628            if (ps.pkg == null) {
12629                continue;
12630            }
12631            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12632            for (int j = 0; j < requestedPermCount; j++) {
12633                String permission = ps.pkg.requestedPermissions.get(j);
12634                BasePermission bp = mSettings.mPermissions.get(permission);
12635                if (bp != null) {
12636                    usedPermissions.add(permission);
12637                }
12638            }
12639        }
12640
12641        PermissionsState permissionsState = su.getPermissionsState();
12642        // Prune install permissions
12643        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12644        final int installPermCount = installPermStates.size();
12645        for (int i = installPermCount - 1; i >= 0;  i--) {
12646            PermissionState permissionState = installPermStates.get(i);
12647            if (!usedPermissions.contains(permissionState.getName())) {
12648                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12649                if (bp != null) {
12650                    permissionsState.revokeInstallPermission(bp);
12651                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12652                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12653                }
12654            }
12655        }
12656
12657        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12658
12659        // Prune runtime permissions
12660        for (int userId : allUserIds) {
12661            List<PermissionState> runtimePermStates = permissionsState
12662                    .getRuntimePermissionStates(userId);
12663            final int runtimePermCount = runtimePermStates.size();
12664            for (int i = runtimePermCount - 1; i >= 0; i--) {
12665                PermissionState permissionState = runtimePermStates.get(i);
12666                if (!usedPermissions.contains(permissionState.getName())) {
12667                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12668                    if (bp != null) {
12669                        permissionsState.revokeRuntimePermission(bp, userId);
12670                        permissionsState.updatePermissionFlags(bp, userId,
12671                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12672                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12673                                runtimePermissionChangedUserIds, userId);
12674                    }
12675                }
12676            }
12677        }
12678
12679        return runtimePermissionChangedUserIds;
12680    }
12681
12682    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12683            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12684            UserHandle user) {
12685        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12686
12687        String pkgName = newPackage.packageName;
12688        synchronized (mPackages) {
12689            //write settings. the installStatus will be incomplete at this stage.
12690            //note that the new package setting would have already been
12691            //added to mPackages. It hasn't been persisted yet.
12692            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12693            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12694            mSettings.writeLPr();
12695            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12696        }
12697
12698        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12699        synchronized (mPackages) {
12700            updatePermissionsLPw(newPackage.packageName, newPackage,
12701                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12702                            ? UPDATE_PERMISSIONS_ALL : 0));
12703            // For system-bundled packages, we assume that installing an upgraded version
12704            // of the package implies that the user actually wants to run that new code,
12705            // so we enable the package.
12706            PackageSetting ps = mSettings.mPackages.get(pkgName);
12707            if (ps != null) {
12708                if (isSystemApp(newPackage)) {
12709                    // NB: implicit assumption that system package upgrades apply to all users
12710                    if (DEBUG_INSTALL) {
12711                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12712                    }
12713                    if (res.origUsers != null) {
12714                        for (int userHandle : res.origUsers) {
12715                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12716                                    userHandle, installerPackageName);
12717                        }
12718                    }
12719                    // Also convey the prior install/uninstall state
12720                    if (allUsers != null && perUserInstalled != null) {
12721                        for (int i = 0; i < allUsers.length; i++) {
12722                            if (DEBUG_INSTALL) {
12723                                Slog.d(TAG, "    user " + allUsers[i]
12724                                        + " => " + perUserInstalled[i]);
12725                            }
12726                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12727                        }
12728                        // these install state changes will be persisted in the
12729                        // upcoming call to mSettings.writeLPr().
12730                    }
12731                }
12732                // It's implied that when a user requests installation, they want the app to be
12733                // installed and enabled.
12734                int userId = user.getIdentifier();
12735                if (userId != UserHandle.USER_ALL) {
12736                    ps.setInstalled(true, userId);
12737                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12738                }
12739            }
12740            res.name = pkgName;
12741            res.uid = newPackage.applicationInfo.uid;
12742            res.pkg = newPackage;
12743            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12744            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12745            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12746            //to update install status
12747            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12748            mSettings.writeLPr();
12749            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12750        }
12751
12752        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12753    }
12754
12755    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12756        try {
12757            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12758            installPackageLI(args, res);
12759        } finally {
12760            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12761        }
12762    }
12763
12764    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12765        final int installFlags = args.installFlags;
12766        final String installerPackageName = args.installerPackageName;
12767        final String volumeUuid = args.volumeUuid;
12768        final File tmpPackageFile = new File(args.getCodePath());
12769        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12770        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12771                || (args.volumeUuid != null));
12772        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12773        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12774        boolean replace = false;
12775        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12776        if (args.move != null) {
12777            // moving a complete application; perfom an initial scan on the new install location
12778            scanFlags |= SCAN_INITIAL;
12779        }
12780        // Result object to be returned
12781        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12782
12783        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12784
12785        // Sanity check
12786        if (ephemeral && (forwardLocked || onExternal)) {
12787            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12788                    + " external=" + onExternal);
12789            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12790            return;
12791        }
12792
12793        // Retrieve PackageSettings and parse package
12794        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12795                | PackageParser.PARSE_ENFORCE_CODE
12796                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12797                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12798                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0)
12799                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12800        PackageParser pp = new PackageParser();
12801        pp.setSeparateProcesses(mSeparateProcesses);
12802        pp.setDisplayMetrics(mMetrics);
12803
12804        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12805        final PackageParser.Package pkg;
12806        try {
12807            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12808        } catch (PackageParserException e) {
12809            res.setError("Failed parse during installPackageLI", e);
12810            return;
12811        } finally {
12812            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12813        }
12814
12815        // Mark that we have an install time CPU ABI override.
12816        pkg.cpuAbiOverride = args.abiOverride;
12817
12818        String pkgName = res.name = pkg.packageName;
12819        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12820            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12821                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12822                return;
12823            }
12824        }
12825
12826        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12827        try {
12828            pp.collectCertificates(pkg, parseFlags);
12829        } catch (PackageParserException e) {
12830            res.setError("Failed collect during installPackageLI", e);
12831            return;
12832        } finally {
12833            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12834        }
12835
12836        /* If the installer passed in a manifest digest, compare it now. */
12837        if (args.manifestDigest != null) {
12838            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12839            try {
12840                pp.collectManifestDigest(pkg);
12841            } catch (PackageParserException e) {
12842                res.setError("Failed collect during installPackageLI", e);
12843                return;
12844            } finally {
12845                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12846            }
12847
12848            if (DEBUG_INSTALL) {
12849                final String parsedManifest = pkg.manifestDigest == null ? "null"
12850                        : pkg.manifestDigest.toString();
12851                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12852                        + parsedManifest);
12853            }
12854
12855            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12856                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12857                return;
12858            }
12859        } else if (DEBUG_INSTALL) {
12860            final String parsedManifest = pkg.manifestDigest == null
12861                    ? "null" : pkg.manifestDigest.toString();
12862            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12863        }
12864
12865        // Get rid of all references to package scan path via parser.
12866        pp = null;
12867        String oldCodePath = null;
12868        boolean systemApp = false;
12869        synchronized (mPackages) {
12870            // Check if installing already existing package
12871            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12872                String oldName = mSettings.mRenamedPackages.get(pkgName);
12873                if (pkg.mOriginalPackages != null
12874                        && pkg.mOriginalPackages.contains(oldName)
12875                        && mPackages.containsKey(oldName)) {
12876                    // This package is derived from an original package,
12877                    // and this device has been updating from that original
12878                    // name.  We must continue using the original name, so
12879                    // rename the new package here.
12880                    pkg.setPackageName(oldName);
12881                    pkgName = pkg.packageName;
12882                    replace = true;
12883                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12884                            + oldName + " pkgName=" + pkgName);
12885                } else if (mPackages.containsKey(pkgName)) {
12886                    // This package, under its official name, already exists
12887                    // on the device; we should replace it.
12888                    replace = true;
12889                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12890                }
12891
12892                // Prevent apps opting out from runtime permissions
12893                if (replace) {
12894                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12895                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12896                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12897                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12898                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12899                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12900                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12901                                        + " doesn't support runtime permissions but the old"
12902                                        + " target SDK " + oldTargetSdk + " does.");
12903                        return;
12904                    }
12905                }
12906            }
12907
12908            PackageSetting ps = mSettings.mPackages.get(pkgName);
12909            if (ps != null) {
12910                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12911
12912                // Quick sanity check that we're signed correctly if updating;
12913                // we'll check this again later when scanning, but we want to
12914                // bail early here before tripping over redefined permissions.
12915                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12916                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12917                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12918                                + pkg.packageName + " upgrade keys do not match the "
12919                                + "previously installed version");
12920                        return;
12921                    }
12922                } else {
12923                    try {
12924                        verifySignaturesLP(ps, pkg);
12925                    } catch (PackageManagerException e) {
12926                        res.setError(e.error, e.getMessage());
12927                        return;
12928                    }
12929                }
12930
12931                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12932                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12933                    systemApp = (ps.pkg.applicationInfo.flags &
12934                            ApplicationInfo.FLAG_SYSTEM) != 0;
12935                }
12936                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12937            }
12938
12939            // Check whether the newly-scanned package wants to define an already-defined perm
12940            int N = pkg.permissions.size();
12941            for (int i = N-1; i >= 0; i--) {
12942                PackageParser.Permission perm = pkg.permissions.get(i);
12943                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12944                if (bp != null) {
12945                    // If the defining package is signed with our cert, it's okay.  This
12946                    // also includes the "updating the same package" case, of course.
12947                    // "updating same package" could also involve key-rotation.
12948                    final boolean sigsOk;
12949                    if (bp.sourcePackage.equals(pkg.packageName)
12950                            && (bp.packageSetting instanceof PackageSetting)
12951                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12952                                    scanFlags))) {
12953                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12954                    } else {
12955                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12956                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12957                    }
12958                    if (!sigsOk) {
12959                        // If the owning package is the system itself, we log but allow
12960                        // install to proceed; we fail the install on all other permission
12961                        // redefinitions.
12962                        if (!bp.sourcePackage.equals("android")) {
12963                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12964                                    + pkg.packageName + " attempting to redeclare permission "
12965                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12966                            res.origPermission = perm.info.name;
12967                            res.origPackage = bp.sourcePackage;
12968                            return;
12969                        } else {
12970                            Slog.w(TAG, "Package " + pkg.packageName
12971                                    + " attempting to redeclare system permission "
12972                                    + perm.info.name + "; ignoring new declaration");
12973                            pkg.permissions.remove(i);
12974                        }
12975                    }
12976                }
12977            }
12978
12979        }
12980
12981        if (systemApp) {
12982            if (onExternal) {
12983                // Abort update; system app can't be replaced with app on sdcard
12984                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12985                        "Cannot install updates to system apps on sdcard");
12986                return;
12987            } else if (ephemeral) {
12988                // Abort update; system app can't be replaced with an ephemeral app
12989                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12990                        "Cannot update a system app with an ephemeral app");
12991                return;
12992            }
12993        }
12994
12995        if (args.move != null) {
12996            // We did an in-place move, so dex is ready to roll
12997            scanFlags |= SCAN_NO_DEX;
12998            scanFlags |= SCAN_MOVE;
12999
13000            synchronized (mPackages) {
13001                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13002                if (ps == null) {
13003                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13004                            "Missing settings for moved package " + pkgName);
13005                }
13006
13007                // We moved the entire application as-is, so bring over the
13008                // previously derived ABI information.
13009                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13010                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13011            }
13012
13013        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13014            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13015            scanFlags |= SCAN_NO_DEX;
13016
13017            try {
13018                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13019                        true /* extract libs */);
13020            } catch (PackageManagerException pme) {
13021                Slog.e(TAG, "Error deriving application ABI", pme);
13022                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13023                return;
13024            }
13025        }
13026
13027        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13028            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13029            return;
13030        }
13031
13032        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13033
13034        if (replace) {
13035            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13036                    installerPackageName, volumeUuid, res);
13037        } else {
13038            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13039                    args.user, installerPackageName, volumeUuid, res);
13040        }
13041        synchronized (mPackages) {
13042            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13043            if (ps != null) {
13044                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13045            }
13046        }
13047    }
13048
13049    private void startIntentFilterVerifications(int userId, boolean replacing,
13050            PackageParser.Package pkg) {
13051        if (mIntentFilterVerifierComponent == null) {
13052            Slog.w(TAG, "No IntentFilter verification will not be done as "
13053                    + "there is no IntentFilterVerifier available!");
13054            return;
13055        }
13056
13057        final int verifierUid = getPackageUid(
13058                mIntentFilterVerifierComponent.getPackageName(),
13059                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13060
13061        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13062        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13063        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13064        mHandler.sendMessage(msg);
13065    }
13066
13067    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13068            PackageParser.Package pkg) {
13069        int size = pkg.activities.size();
13070        if (size == 0) {
13071            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13072                    "No activity, so no need to verify any IntentFilter!");
13073            return;
13074        }
13075
13076        final boolean hasDomainURLs = hasDomainURLs(pkg);
13077        if (!hasDomainURLs) {
13078            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13079                    "No domain URLs, so no need to verify any IntentFilter!");
13080            return;
13081        }
13082
13083        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13084                + " if any IntentFilter from the " + size
13085                + " Activities needs verification ...");
13086
13087        int count = 0;
13088        final String packageName = pkg.packageName;
13089
13090        synchronized (mPackages) {
13091            // If this is a new install and we see that we've already run verification for this
13092            // package, we have nothing to do: it means the state was restored from backup.
13093            if (!replacing) {
13094                IntentFilterVerificationInfo ivi =
13095                        mSettings.getIntentFilterVerificationLPr(packageName);
13096                if (ivi != null) {
13097                    if (DEBUG_DOMAIN_VERIFICATION) {
13098                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13099                                + ivi.getStatusString());
13100                    }
13101                    return;
13102                }
13103            }
13104
13105            // If any filters need to be verified, then all need to be.
13106            boolean needToVerify = false;
13107            for (PackageParser.Activity a : pkg.activities) {
13108                for (ActivityIntentInfo filter : a.intents) {
13109                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13110                        if (DEBUG_DOMAIN_VERIFICATION) {
13111                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13112                        }
13113                        needToVerify = true;
13114                        break;
13115                    }
13116                }
13117            }
13118
13119            if (needToVerify) {
13120                final int verificationId = mIntentFilterVerificationToken++;
13121                for (PackageParser.Activity a : pkg.activities) {
13122                    for (ActivityIntentInfo filter : a.intents) {
13123                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13124                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13125                                    "Verification needed for IntentFilter:" + filter.toString());
13126                            mIntentFilterVerifier.addOneIntentFilterVerification(
13127                                    verifierUid, userId, verificationId, filter, packageName);
13128                            count++;
13129                        }
13130                    }
13131                }
13132            }
13133        }
13134
13135        if (count > 0) {
13136            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13137                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13138                    +  " for userId:" + userId);
13139            mIntentFilterVerifier.startVerifications(userId);
13140        } else {
13141            if (DEBUG_DOMAIN_VERIFICATION) {
13142                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13143            }
13144        }
13145    }
13146
13147    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13148        final ComponentName cn  = filter.activity.getComponentName();
13149        final String packageName = cn.getPackageName();
13150
13151        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13152                packageName);
13153        if (ivi == null) {
13154            return true;
13155        }
13156        int status = ivi.getStatus();
13157        switch (status) {
13158            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13159            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13160                return true;
13161
13162            default:
13163                // Nothing to do
13164                return false;
13165        }
13166    }
13167
13168    private static boolean isMultiArch(PackageSetting ps) {
13169        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13170    }
13171
13172    private static boolean isMultiArch(ApplicationInfo info) {
13173        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13174    }
13175
13176    private static boolean isExternal(PackageParser.Package pkg) {
13177        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13178    }
13179
13180    private static boolean isExternal(PackageSetting ps) {
13181        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13182    }
13183
13184    private static boolean isExternal(ApplicationInfo info) {
13185        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13186    }
13187
13188    private static boolean isEphemeral(PackageParser.Package pkg) {
13189        return pkg.applicationInfo.isEphemeralApp();
13190    }
13191
13192    private static boolean isEphemeral(PackageSetting ps) {
13193        return ps.pkg != null && isEphemeral(ps.pkg);
13194    }
13195
13196    private static boolean isSystemApp(PackageParser.Package pkg) {
13197        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13198    }
13199
13200    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13201        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13202    }
13203
13204    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13205        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13206    }
13207
13208    private static boolean isSystemApp(PackageSetting ps) {
13209        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13210    }
13211
13212    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13213        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13214    }
13215
13216    private int packageFlagsToInstallFlags(PackageSetting ps) {
13217        int installFlags = 0;
13218        if (isEphemeral(ps)) {
13219            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13220        }
13221        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13222            // This existing package was an external ASEC install when we have
13223            // the external flag without a UUID
13224            installFlags |= PackageManager.INSTALL_EXTERNAL;
13225        }
13226        if (ps.isForwardLocked()) {
13227            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13228        }
13229        return installFlags;
13230    }
13231
13232    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13233        if (isExternal(pkg)) {
13234            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13235                return StorageManager.UUID_PRIMARY_PHYSICAL;
13236            } else {
13237                return pkg.volumeUuid;
13238            }
13239        } else {
13240            return StorageManager.UUID_PRIVATE_INTERNAL;
13241        }
13242    }
13243
13244    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13245        if (isExternal(pkg)) {
13246            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13247                return mSettings.getExternalVersion();
13248            } else {
13249                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13250            }
13251        } else {
13252            return mSettings.getInternalVersion();
13253        }
13254    }
13255
13256    private void deleteTempPackageFiles() {
13257        final FilenameFilter filter = new FilenameFilter() {
13258            public boolean accept(File dir, String name) {
13259                return name.startsWith("vmdl") && name.endsWith(".tmp");
13260            }
13261        };
13262        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13263            file.delete();
13264        }
13265    }
13266
13267    @Override
13268    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13269            int flags) {
13270        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13271                flags);
13272    }
13273
13274    @Override
13275    public void deletePackage(final String packageName,
13276            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13277        mContext.enforceCallingOrSelfPermission(
13278                android.Manifest.permission.DELETE_PACKAGES, null);
13279        Preconditions.checkNotNull(packageName);
13280        Preconditions.checkNotNull(observer);
13281        final int uid = Binder.getCallingUid();
13282        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13283        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13284        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13285            mContext.enforceCallingOrSelfPermission(
13286                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13287                    "deletePackage for user " + userId);
13288        }
13289
13290        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13291            try {
13292                observer.onPackageDeleted(packageName,
13293                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13294            } catch (RemoteException re) {
13295            }
13296            return;
13297        }
13298
13299        for (int currentUserId : users) {
13300            if (getBlockUninstallForUser(packageName, currentUserId)) {
13301                try {
13302                    observer.onPackageDeleted(packageName,
13303                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13304                } catch (RemoteException re) {
13305                }
13306                return;
13307            }
13308        }
13309
13310        if (DEBUG_REMOVE) {
13311            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13312        }
13313        // Queue up an async operation since the package deletion may take a little while.
13314        mHandler.post(new Runnable() {
13315            public void run() {
13316                mHandler.removeCallbacks(this);
13317                final int returnCode = deletePackageX(packageName, userId, flags);
13318                try {
13319                    observer.onPackageDeleted(packageName, returnCode, null);
13320                } catch (RemoteException e) {
13321                    Log.i(TAG, "Observer no longer exists.");
13322                } //end catch
13323            } //end run
13324        });
13325    }
13326
13327    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13328        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13329                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13330        try {
13331            if (dpm != null) {
13332                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13333                        /* callingUserOnly =*/ false);
13334                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13335                        : deviceOwnerComponentName.getPackageName();
13336                // Does the package contains the device owner?
13337                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13338                // this check is probably not needed, since DO should be registered as a device
13339                // admin on some user too. (Original bug for this: b/17657954)
13340                if (packageName.equals(deviceOwnerPackageName)) {
13341                    return true;
13342                }
13343                // Does it contain a device admin for any user?
13344                int[] users;
13345                if (userId == UserHandle.USER_ALL) {
13346                    users = sUserManager.getUserIds();
13347                } else {
13348                    users = new int[]{userId};
13349                }
13350                for (int i = 0; i < users.length; ++i) {
13351                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13352                        return true;
13353                    }
13354                }
13355            }
13356        } catch (RemoteException e) {
13357        }
13358        return false;
13359    }
13360
13361    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13362        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13363    }
13364
13365    /**
13366     *  This method is an internal method that could be get invoked either
13367     *  to delete an installed package or to clean up a failed installation.
13368     *  After deleting an installed package, a broadcast is sent to notify any
13369     *  listeners that the package has been installed. For cleaning up a failed
13370     *  installation, the broadcast is not necessary since the package's
13371     *  installation wouldn't have sent the initial broadcast either
13372     *  The key steps in deleting a package are
13373     *  deleting the package information in internal structures like mPackages,
13374     *  deleting the packages base directories through installd
13375     *  updating mSettings to reflect current status
13376     *  persisting settings for later use
13377     *  sending a broadcast if necessary
13378     */
13379    private int deletePackageX(String packageName, int userId, int flags) {
13380        final PackageRemovedInfo info = new PackageRemovedInfo();
13381        final boolean res;
13382
13383        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13384                ? UserHandle.ALL : new UserHandle(userId);
13385
13386        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13387            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13388            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13389        }
13390
13391        boolean removedForAllUsers = false;
13392        boolean systemUpdate = false;
13393
13394        PackageParser.Package uninstalledPkg;
13395
13396        // for the uninstall-updates case and restricted profiles, remember the per-
13397        // userhandle installed state
13398        int[] allUsers;
13399        boolean[] perUserInstalled;
13400        synchronized (mPackages) {
13401            uninstalledPkg = mPackages.get(packageName);
13402            PackageSetting ps = mSettings.mPackages.get(packageName);
13403            allUsers = sUserManager.getUserIds();
13404            perUserInstalled = new boolean[allUsers.length];
13405            for (int i = 0; i < allUsers.length; i++) {
13406                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13407            }
13408        }
13409
13410        synchronized (mInstallLock) {
13411            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13412            res = deletePackageLI(packageName, removeForUser,
13413                    true, allUsers, perUserInstalled,
13414                    flags | REMOVE_CHATTY, info, true);
13415            systemUpdate = info.isRemovedPackageSystemUpdate;
13416            synchronized (mPackages) {
13417                if (res) {
13418                    if (!systemUpdate && mPackages.get(packageName) == null) {
13419                        removedForAllUsers = true;
13420                    }
13421                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13422                }
13423            }
13424            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13425                    + " removedForAllUsers=" + removedForAllUsers);
13426        }
13427
13428        if (res) {
13429            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13430
13431            // If the removed package was a system update, the old system package
13432            // was re-enabled; we need to broadcast this information
13433            if (systemUpdate) {
13434                Bundle extras = new Bundle(1);
13435                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13436                        ? info.removedAppId : info.uid);
13437                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13438
13439                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13440                        extras, 0, null, null, null);
13441                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13442                        extras, 0, null, null, null);
13443                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13444                        null, 0, packageName, null, null);
13445            }
13446        }
13447        // Force a gc here.
13448        Runtime.getRuntime().gc();
13449        // Delete the resources here after sending the broadcast to let
13450        // other processes clean up before deleting resources.
13451        if (info.args != null) {
13452            synchronized (mInstallLock) {
13453                info.args.doPostDeleteLI(true);
13454            }
13455        }
13456
13457        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13458    }
13459
13460    class PackageRemovedInfo {
13461        String removedPackage;
13462        int uid = -1;
13463        int removedAppId = -1;
13464        int[] removedUsers = null;
13465        boolean isRemovedPackageSystemUpdate = false;
13466        // Clean up resources deleted packages.
13467        InstallArgs args = null;
13468
13469        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13470            Bundle extras = new Bundle(1);
13471            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13472            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13473            if (replacing) {
13474                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13475            }
13476            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13477            if (removedPackage != null) {
13478                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13479                        extras, 0, null, null, removedUsers);
13480                if (fullRemove && !replacing) {
13481                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13482                            extras, 0, null, null, removedUsers);
13483                }
13484            }
13485            if (removedAppId >= 0) {
13486                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13487                        removedUsers);
13488            }
13489        }
13490    }
13491
13492    /*
13493     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13494     * flag is not set, the data directory is removed as well.
13495     * make sure this flag is set for partially installed apps. If not its meaningless to
13496     * delete a partially installed application.
13497     */
13498    private void removePackageDataLI(PackageSetting ps,
13499            int[] allUserHandles, boolean[] perUserInstalled,
13500            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13501        String packageName = ps.name;
13502        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13503        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13504        // Retrieve object to delete permissions for shared user later on
13505        final PackageSetting deletedPs;
13506        // reader
13507        synchronized (mPackages) {
13508            deletedPs = mSettings.mPackages.get(packageName);
13509            if (outInfo != null) {
13510                outInfo.removedPackage = packageName;
13511                outInfo.removedUsers = deletedPs != null
13512                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13513                        : null;
13514            }
13515        }
13516        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13517            removeDataDirsLI(ps.volumeUuid, packageName);
13518            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13519        }
13520        // writer
13521        synchronized (mPackages) {
13522            if (deletedPs != null) {
13523                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13524                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13525                    clearDefaultBrowserIfNeeded(packageName);
13526                    if (outInfo != null) {
13527                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13528                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13529                    }
13530                    updatePermissionsLPw(deletedPs.name, null, 0);
13531                    if (deletedPs.sharedUser != null) {
13532                        // Remove permissions associated with package. Since runtime
13533                        // permissions are per user we have to kill the removed package
13534                        // or packages running under the shared user of the removed
13535                        // package if revoking the permissions requested only by the removed
13536                        // package is successful and this causes a change in gids.
13537                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13538                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13539                                    userId);
13540                            if (userIdToKill == UserHandle.USER_ALL
13541                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13542                                // If gids changed for this user, kill all affected packages.
13543                                mHandler.post(new Runnable() {
13544                                    @Override
13545                                    public void run() {
13546                                        // This has to happen with no lock held.
13547                                        killApplication(deletedPs.name, deletedPs.appId,
13548                                                KILL_APP_REASON_GIDS_CHANGED);
13549                                    }
13550                                });
13551                                break;
13552                            }
13553                        }
13554                    }
13555                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13556                }
13557                // make sure to preserve per-user disabled state if this removal was just
13558                // a downgrade of a system app to the factory package
13559                if (allUserHandles != null && perUserInstalled != null) {
13560                    if (DEBUG_REMOVE) {
13561                        Slog.d(TAG, "Propagating install state across downgrade");
13562                    }
13563                    for (int i = 0; i < allUserHandles.length; i++) {
13564                        if (DEBUG_REMOVE) {
13565                            Slog.d(TAG, "    user " + allUserHandles[i]
13566                                    + " => " + perUserInstalled[i]);
13567                        }
13568                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13569                    }
13570                }
13571            }
13572            // can downgrade to reader
13573            if (writeSettings) {
13574                // Save settings now
13575                mSettings.writeLPr();
13576            }
13577        }
13578        if (outInfo != null) {
13579            // A user ID was deleted here. Go through all users and remove it
13580            // from KeyStore.
13581            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13582        }
13583    }
13584
13585    static boolean locationIsPrivileged(File path) {
13586        try {
13587            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13588                    .getCanonicalPath();
13589            return path.getCanonicalPath().startsWith(privilegedAppDir);
13590        } catch (IOException e) {
13591            Slog.e(TAG, "Unable to access code path " + path);
13592        }
13593        return false;
13594    }
13595
13596    /*
13597     * Tries to delete system package.
13598     */
13599    private boolean deleteSystemPackageLI(PackageSetting newPs,
13600            int[] allUserHandles, boolean[] perUserInstalled,
13601            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13602        final boolean applyUserRestrictions
13603                = (allUserHandles != null) && (perUserInstalled != null);
13604        PackageSetting disabledPs = null;
13605        // Confirm if the system package has been updated
13606        // An updated system app can be deleted. This will also have to restore
13607        // the system pkg from system partition
13608        // reader
13609        synchronized (mPackages) {
13610            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13611        }
13612        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13613                + " disabledPs=" + disabledPs);
13614        if (disabledPs == null) {
13615            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13616            return false;
13617        } else if (DEBUG_REMOVE) {
13618            Slog.d(TAG, "Deleting system pkg from data partition");
13619        }
13620        if (DEBUG_REMOVE) {
13621            if (applyUserRestrictions) {
13622                Slog.d(TAG, "Remembering install states:");
13623                for (int i = 0; i < allUserHandles.length; i++) {
13624                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13625                }
13626            }
13627        }
13628        // Delete the updated package
13629        outInfo.isRemovedPackageSystemUpdate = true;
13630        if (disabledPs.versionCode < newPs.versionCode) {
13631            // Delete data for downgrades
13632            flags &= ~PackageManager.DELETE_KEEP_DATA;
13633        } else {
13634            // Preserve data by setting flag
13635            flags |= PackageManager.DELETE_KEEP_DATA;
13636        }
13637        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13638                allUserHandles, perUserInstalled, outInfo, writeSettings);
13639        if (!ret) {
13640            return false;
13641        }
13642        // writer
13643        synchronized (mPackages) {
13644            // Reinstate the old system package
13645            mSettings.enableSystemPackageLPw(newPs.name);
13646            // Remove any native libraries from the upgraded package.
13647            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13648        }
13649        // Install the system package
13650        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13651        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13652        if (locationIsPrivileged(disabledPs.codePath)) {
13653            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13654        }
13655
13656        final PackageParser.Package newPkg;
13657        try {
13658            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13659        } catch (PackageManagerException e) {
13660            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13661            return false;
13662        }
13663
13664        // writer
13665        synchronized (mPackages) {
13666            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13667
13668            // Propagate the permissions state as we do not want to drop on the floor
13669            // runtime permissions. The update permissions method below will take
13670            // care of removing obsolete permissions and grant install permissions.
13671            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13672            updatePermissionsLPw(newPkg.packageName, newPkg,
13673                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13674
13675            if (applyUserRestrictions) {
13676                if (DEBUG_REMOVE) {
13677                    Slog.d(TAG, "Propagating install state across reinstall");
13678                }
13679                for (int i = 0; i < allUserHandles.length; i++) {
13680                    if (DEBUG_REMOVE) {
13681                        Slog.d(TAG, "    user " + allUserHandles[i]
13682                                + " => " + perUserInstalled[i]);
13683                    }
13684                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13685
13686                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13687                }
13688                // Regardless of writeSettings we need to ensure that this restriction
13689                // state propagation is persisted
13690                mSettings.writeAllUsersPackageRestrictionsLPr();
13691            }
13692            // can downgrade to reader here
13693            if (writeSettings) {
13694                mSettings.writeLPr();
13695            }
13696        }
13697        return true;
13698    }
13699
13700    private boolean deleteInstalledPackageLI(PackageSetting ps,
13701            boolean deleteCodeAndResources, int flags,
13702            int[] allUserHandles, boolean[] perUserInstalled,
13703            PackageRemovedInfo outInfo, boolean writeSettings) {
13704        if (outInfo != null) {
13705            outInfo.uid = ps.appId;
13706        }
13707
13708        // Delete package data from internal structures and also remove data if flag is set
13709        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13710
13711        // Delete application code and resources
13712        if (deleteCodeAndResources && (outInfo != null)) {
13713            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13714                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13715            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13716        }
13717        return true;
13718    }
13719
13720    @Override
13721    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13722            int userId) {
13723        mContext.enforceCallingOrSelfPermission(
13724                android.Manifest.permission.DELETE_PACKAGES, null);
13725        synchronized (mPackages) {
13726            PackageSetting ps = mSettings.mPackages.get(packageName);
13727            if (ps == null) {
13728                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13729                return false;
13730            }
13731            if (!ps.getInstalled(userId)) {
13732                // Can't block uninstall for an app that is not installed or enabled.
13733                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13734                return false;
13735            }
13736            ps.setBlockUninstall(blockUninstall, userId);
13737            mSettings.writePackageRestrictionsLPr(userId);
13738        }
13739        return true;
13740    }
13741
13742    @Override
13743    public boolean getBlockUninstallForUser(String packageName, int userId) {
13744        synchronized (mPackages) {
13745            PackageSetting ps = mSettings.mPackages.get(packageName);
13746            if (ps == null) {
13747                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13748                return false;
13749            }
13750            return ps.getBlockUninstall(userId);
13751        }
13752    }
13753
13754    /*
13755     * This method handles package deletion in general
13756     */
13757    private boolean deletePackageLI(String packageName, UserHandle user,
13758            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13759            int flags, PackageRemovedInfo outInfo,
13760            boolean writeSettings) {
13761        if (packageName == null) {
13762            Slog.w(TAG, "Attempt to delete null packageName.");
13763            return false;
13764        }
13765        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13766        PackageSetting ps;
13767        boolean dataOnly = false;
13768        int removeUser = -1;
13769        int appId = -1;
13770        synchronized (mPackages) {
13771            ps = mSettings.mPackages.get(packageName);
13772            if (ps == null) {
13773                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13774                return false;
13775            }
13776            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13777                    && user.getIdentifier() != UserHandle.USER_ALL) {
13778                // The caller is asking that the package only be deleted for a single
13779                // user.  To do this, we just mark its uninstalled state and delete
13780                // its data.  If this is a system app, we only allow this to happen if
13781                // they have set the special DELETE_SYSTEM_APP which requests different
13782                // semantics than normal for uninstalling system apps.
13783                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13784                final int userId = user.getIdentifier();
13785                ps.setUserState(userId,
13786                        COMPONENT_ENABLED_STATE_DEFAULT,
13787                        false, //installed
13788                        true,  //stopped
13789                        true,  //notLaunched
13790                        false, //hidden
13791                        null, null, null,
13792                        false, // blockUninstall
13793                        ps.readUserState(userId).domainVerificationStatus, 0);
13794                if (!isSystemApp(ps)) {
13795                    // Do not uninstall the APK if an app should be cached
13796                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13797                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13798                        // Other user still have this package installed, so all
13799                        // we need to do is clear this user's data and save that
13800                        // it is uninstalled.
13801                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13802                        removeUser = user.getIdentifier();
13803                        appId = ps.appId;
13804                        scheduleWritePackageRestrictionsLocked(removeUser);
13805                    } else {
13806                        // We need to set it back to 'installed' so the uninstall
13807                        // broadcasts will be sent correctly.
13808                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13809                        ps.setInstalled(true, user.getIdentifier());
13810                    }
13811                } else {
13812                    // This is a system app, so we assume that the
13813                    // other users still have this package installed, so all
13814                    // we need to do is clear this user's data and save that
13815                    // it is uninstalled.
13816                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13817                    removeUser = user.getIdentifier();
13818                    appId = ps.appId;
13819                    scheduleWritePackageRestrictionsLocked(removeUser);
13820                }
13821            }
13822        }
13823
13824        if (removeUser >= 0) {
13825            // From above, we determined that we are deleting this only
13826            // for a single user.  Continue the work here.
13827            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13828            if (outInfo != null) {
13829                outInfo.removedPackage = packageName;
13830                outInfo.removedAppId = appId;
13831                outInfo.removedUsers = new int[] {removeUser};
13832            }
13833            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13834            removeKeystoreDataIfNeeded(removeUser, appId);
13835            schedulePackageCleaning(packageName, removeUser, false);
13836            synchronized (mPackages) {
13837                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13838                    scheduleWritePackageRestrictionsLocked(removeUser);
13839                }
13840                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13841            }
13842            return true;
13843        }
13844
13845        if (dataOnly) {
13846            // Delete application data first
13847            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13848            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13849            return true;
13850        }
13851
13852        boolean ret = false;
13853        if (isSystemApp(ps)) {
13854            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13855            // When an updated system application is deleted we delete the existing resources as well and
13856            // fall back to existing code in system partition
13857            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13858                    flags, outInfo, writeSettings);
13859        } else {
13860            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13861            // Kill application pre-emptively especially for apps on sd.
13862            killApplication(packageName, ps.appId, "uninstall pkg");
13863            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13864                    allUserHandles, perUserInstalled,
13865                    outInfo, writeSettings);
13866        }
13867
13868        return ret;
13869    }
13870
13871    private final class ClearStorageConnection implements ServiceConnection {
13872        IMediaContainerService mContainerService;
13873
13874        @Override
13875        public void onServiceConnected(ComponentName name, IBinder service) {
13876            synchronized (this) {
13877                mContainerService = IMediaContainerService.Stub.asInterface(service);
13878                notifyAll();
13879            }
13880        }
13881
13882        @Override
13883        public void onServiceDisconnected(ComponentName name) {
13884        }
13885    }
13886
13887    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13888        final boolean mounted;
13889        if (Environment.isExternalStorageEmulated()) {
13890            mounted = true;
13891        } else {
13892            final String status = Environment.getExternalStorageState();
13893
13894            mounted = status.equals(Environment.MEDIA_MOUNTED)
13895                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13896        }
13897
13898        if (!mounted) {
13899            return;
13900        }
13901
13902        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13903        int[] users;
13904        if (userId == UserHandle.USER_ALL) {
13905            users = sUserManager.getUserIds();
13906        } else {
13907            users = new int[] { userId };
13908        }
13909        final ClearStorageConnection conn = new ClearStorageConnection();
13910        if (mContext.bindServiceAsUser(
13911                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13912            try {
13913                for (int curUser : users) {
13914                    long timeout = SystemClock.uptimeMillis() + 5000;
13915                    synchronized (conn) {
13916                        long now = SystemClock.uptimeMillis();
13917                        while (conn.mContainerService == null && now < timeout) {
13918                            try {
13919                                conn.wait(timeout - now);
13920                            } catch (InterruptedException e) {
13921                            }
13922                        }
13923                    }
13924                    if (conn.mContainerService == null) {
13925                        return;
13926                    }
13927
13928                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13929                    clearDirectory(conn.mContainerService,
13930                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13931                    if (allData) {
13932                        clearDirectory(conn.mContainerService,
13933                                userEnv.buildExternalStorageAppDataDirs(packageName));
13934                        clearDirectory(conn.mContainerService,
13935                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13936                    }
13937                }
13938            } finally {
13939                mContext.unbindService(conn);
13940            }
13941        }
13942    }
13943
13944    @Override
13945    public void clearApplicationUserData(final String packageName,
13946            final IPackageDataObserver observer, final int userId) {
13947        mContext.enforceCallingOrSelfPermission(
13948                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13949        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13950        // Queue up an async operation since the package deletion may take a little while.
13951        mHandler.post(new Runnable() {
13952            public void run() {
13953                mHandler.removeCallbacks(this);
13954                final boolean succeeded;
13955                synchronized (mInstallLock) {
13956                    succeeded = clearApplicationUserDataLI(packageName, userId);
13957                }
13958                clearExternalStorageDataSync(packageName, userId, true);
13959                if (succeeded) {
13960                    // invoke DeviceStorageMonitor's update method to clear any notifications
13961                    DeviceStorageMonitorInternal
13962                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13963                    if (dsm != null) {
13964                        dsm.checkMemory();
13965                    }
13966                }
13967                if(observer != null) {
13968                    try {
13969                        observer.onRemoveCompleted(packageName, succeeded);
13970                    } catch (RemoteException e) {
13971                        Log.i(TAG, "Observer no longer exists.");
13972                    }
13973                } //end if observer
13974            } //end run
13975        });
13976    }
13977
13978    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13979        if (packageName == null) {
13980            Slog.w(TAG, "Attempt to delete null packageName.");
13981            return false;
13982        }
13983
13984        // Try finding details about the requested package
13985        PackageParser.Package pkg;
13986        synchronized (mPackages) {
13987            pkg = mPackages.get(packageName);
13988            if (pkg == null) {
13989                final PackageSetting ps = mSettings.mPackages.get(packageName);
13990                if (ps != null) {
13991                    pkg = ps.pkg;
13992                }
13993            }
13994
13995            if (pkg == null) {
13996                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13997                return false;
13998            }
13999
14000            PackageSetting ps = (PackageSetting) pkg.mExtras;
14001            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14002        }
14003
14004        // Always delete data directories for package, even if we found no other
14005        // record of app. This helps users recover from UID mismatches without
14006        // resorting to a full data wipe.
14007        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14008        if (retCode < 0) {
14009            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
14010            return false;
14011        }
14012
14013        final int appId = pkg.applicationInfo.uid;
14014        removeKeystoreDataIfNeeded(userId, appId);
14015
14016        // Create a native library symlink only if we have native libraries
14017        // and if the native libraries are 32 bit libraries. We do not provide
14018        // this symlink for 64 bit libraries.
14019        if (pkg.applicationInfo.primaryCpuAbi != null &&
14020                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14021            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14022            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14023                    nativeLibPath, userId) < 0) {
14024                Slog.w(TAG, "Failed linking native library dir");
14025                return false;
14026            }
14027        }
14028
14029        return true;
14030    }
14031
14032    /**
14033     * Reverts user permission state changes (permissions and flags) in
14034     * all packages for a given user.
14035     *
14036     * @param userId The device user for which to do a reset.
14037     */
14038    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14039        final int packageCount = mPackages.size();
14040        for (int i = 0; i < packageCount; i++) {
14041            PackageParser.Package pkg = mPackages.valueAt(i);
14042            PackageSetting ps = (PackageSetting) pkg.mExtras;
14043            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14044        }
14045    }
14046
14047    /**
14048     * Reverts user permission state changes (permissions and flags).
14049     *
14050     * @param ps The package for which to reset.
14051     * @param userId The device user for which to do a reset.
14052     */
14053    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14054            final PackageSetting ps, final int userId) {
14055        if (ps.pkg == null) {
14056            return;
14057        }
14058
14059        // These are flags that can change base on user actions.
14060        final int userSettableMask = FLAG_PERMISSION_USER_SET
14061                | FLAG_PERMISSION_USER_FIXED
14062                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14063                | FLAG_PERMISSION_REVIEW_REQUIRED;
14064
14065        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14066                | FLAG_PERMISSION_POLICY_FIXED;
14067
14068        boolean writeInstallPermissions = false;
14069        boolean writeRuntimePermissions = false;
14070
14071        final int permissionCount = ps.pkg.requestedPermissions.size();
14072        for (int i = 0; i < permissionCount; i++) {
14073            String permission = ps.pkg.requestedPermissions.get(i);
14074
14075            BasePermission bp = mSettings.mPermissions.get(permission);
14076            if (bp == null) {
14077                continue;
14078            }
14079
14080            // If shared user we just reset the state to which only this app contributed.
14081            if (ps.sharedUser != null) {
14082                boolean used = false;
14083                final int packageCount = ps.sharedUser.packages.size();
14084                for (int j = 0; j < packageCount; j++) {
14085                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14086                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14087                            && pkg.pkg.requestedPermissions.contains(permission)) {
14088                        used = true;
14089                        break;
14090                    }
14091                }
14092                if (used) {
14093                    continue;
14094                }
14095            }
14096
14097            PermissionsState permissionsState = ps.getPermissionsState();
14098
14099            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14100
14101            // Always clear the user settable flags.
14102            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14103                    bp.name) != null;
14104            // If permission review is enabled and this is a legacy app, mark the
14105            // permission as requiring a review as this is the initial state.
14106            int flags = 0;
14107            if (Build.PERMISSIONS_REVIEW_REQUIRED
14108                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14109                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14110            }
14111            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14112                if (hasInstallState) {
14113                    writeInstallPermissions = true;
14114                } else {
14115                    writeRuntimePermissions = true;
14116                }
14117            }
14118
14119            // Below is only runtime permission handling.
14120            if (!bp.isRuntime()) {
14121                continue;
14122            }
14123
14124            // Never clobber system or policy.
14125            if ((oldFlags & policyOrSystemFlags) != 0) {
14126                continue;
14127            }
14128
14129            // If this permission was granted by default, make sure it is.
14130            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14131                if (permissionsState.grantRuntimePermission(bp, userId)
14132                        != PERMISSION_OPERATION_FAILURE) {
14133                    writeRuntimePermissions = true;
14134                }
14135            // If permission review is enabled the permissions for a legacy apps
14136            // are represented as constantly granted runtime ones, so don't revoke.
14137            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14138                // Otherwise, reset the permission.
14139                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14140                switch (revokeResult) {
14141                    case PERMISSION_OPERATION_SUCCESS: {
14142                        writeRuntimePermissions = true;
14143                    } break;
14144
14145                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14146                        writeRuntimePermissions = true;
14147                        final int appId = ps.appId;
14148                        mHandler.post(new Runnable() {
14149                            @Override
14150                            public void run() {
14151                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14152                            }
14153                        });
14154                    } break;
14155                }
14156            }
14157        }
14158
14159        // Synchronously write as we are taking permissions away.
14160        if (writeRuntimePermissions) {
14161            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14162        }
14163
14164        // Synchronously write as we are taking permissions away.
14165        if (writeInstallPermissions) {
14166            mSettings.writeLPr();
14167        }
14168    }
14169
14170    /**
14171     * Remove entries from the keystore daemon. Will only remove it if the
14172     * {@code appId} is valid.
14173     */
14174    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14175        if (appId < 0) {
14176            return;
14177        }
14178
14179        final KeyStore keyStore = KeyStore.getInstance();
14180        if (keyStore != null) {
14181            if (userId == UserHandle.USER_ALL) {
14182                for (final int individual : sUserManager.getUserIds()) {
14183                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14184                }
14185            } else {
14186                keyStore.clearUid(UserHandle.getUid(userId, appId));
14187            }
14188        } else {
14189            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14190        }
14191    }
14192
14193    @Override
14194    public void deleteApplicationCacheFiles(final String packageName,
14195            final IPackageDataObserver observer) {
14196        mContext.enforceCallingOrSelfPermission(
14197                android.Manifest.permission.DELETE_CACHE_FILES, null);
14198        // Queue up an async operation since the package deletion may take a little while.
14199        final int userId = UserHandle.getCallingUserId();
14200        mHandler.post(new Runnable() {
14201            public void run() {
14202                mHandler.removeCallbacks(this);
14203                final boolean succeded;
14204                synchronized (mInstallLock) {
14205                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14206                }
14207                clearExternalStorageDataSync(packageName, userId, false);
14208                if (observer != null) {
14209                    try {
14210                        observer.onRemoveCompleted(packageName, succeded);
14211                    } catch (RemoteException e) {
14212                        Log.i(TAG, "Observer no longer exists.");
14213                    }
14214                } //end if observer
14215            } //end run
14216        });
14217    }
14218
14219    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14220        if (packageName == null) {
14221            Slog.w(TAG, "Attempt to delete null packageName.");
14222            return false;
14223        }
14224        PackageParser.Package p;
14225        synchronized (mPackages) {
14226            p = mPackages.get(packageName);
14227        }
14228        if (p == null) {
14229            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14230            return false;
14231        }
14232        final ApplicationInfo applicationInfo = p.applicationInfo;
14233        if (applicationInfo == null) {
14234            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14235            return false;
14236        }
14237        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14238        if (retCode < 0) {
14239            Slog.w(TAG, "Couldn't remove cache files for package: "
14240                       + packageName + " u" + userId);
14241            return false;
14242        }
14243        return true;
14244    }
14245
14246    @Override
14247    public void getPackageSizeInfo(final String packageName, int userHandle,
14248            final IPackageStatsObserver observer) {
14249        mContext.enforceCallingOrSelfPermission(
14250                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14251        if (packageName == null) {
14252            throw new IllegalArgumentException("Attempt to get size of null packageName");
14253        }
14254
14255        PackageStats stats = new PackageStats(packageName, userHandle);
14256
14257        /*
14258         * Queue up an async operation since the package measurement may take a
14259         * little while.
14260         */
14261        Message msg = mHandler.obtainMessage(INIT_COPY);
14262        msg.obj = new MeasureParams(stats, observer);
14263        mHandler.sendMessage(msg);
14264    }
14265
14266    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14267            PackageStats pStats) {
14268        if (packageName == null) {
14269            Slog.w(TAG, "Attempt to get size of null packageName.");
14270            return false;
14271        }
14272        PackageParser.Package p;
14273        boolean dataOnly = false;
14274        String libDirRoot = null;
14275        String asecPath = null;
14276        PackageSetting ps = null;
14277        synchronized (mPackages) {
14278            p = mPackages.get(packageName);
14279            ps = mSettings.mPackages.get(packageName);
14280            if(p == null) {
14281                dataOnly = true;
14282                if((ps == null) || (ps.pkg == null)) {
14283                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14284                    return false;
14285                }
14286                p = ps.pkg;
14287            }
14288            if (ps != null) {
14289                libDirRoot = ps.legacyNativeLibraryPathString;
14290            }
14291            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14292                final long token = Binder.clearCallingIdentity();
14293                try {
14294                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14295                    if (secureContainerId != null) {
14296                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14297                    }
14298                } finally {
14299                    Binder.restoreCallingIdentity(token);
14300                }
14301            }
14302        }
14303        String publicSrcDir = null;
14304        if(!dataOnly) {
14305            final ApplicationInfo applicationInfo = p.applicationInfo;
14306            if (applicationInfo == null) {
14307                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14308                return false;
14309            }
14310            if (p.isForwardLocked()) {
14311                publicSrcDir = applicationInfo.getBaseResourcePath();
14312            }
14313        }
14314        // TODO: extend to measure size of split APKs
14315        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14316        // not just the first level.
14317        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14318        // just the primary.
14319        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14320
14321        String apkPath;
14322        File packageDir = new File(p.codePath);
14323
14324        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14325            apkPath = packageDir.getAbsolutePath();
14326            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14327            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14328                libDirRoot = null;
14329            }
14330        } else {
14331            apkPath = p.baseCodePath;
14332        }
14333
14334        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14335                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14336        if (res < 0) {
14337            return false;
14338        }
14339
14340        // Fix-up for forward-locked applications in ASEC containers.
14341        if (!isExternal(p)) {
14342            pStats.codeSize += pStats.externalCodeSize;
14343            pStats.externalCodeSize = 0L;
14344        }
14345
14346        return true;
14347    }
14348
14349
14350    @Override
14351    public void addPackageToPreferred(String packageName) {
14352        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14353    }
14354
14355    @Override
14356    public void removePackageFromPreferred(String packageName) {
14357        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14358    }
14359
14360    @Override
14361    public List<PackageInfo> getPreferredPackages(int flags) {
14362        return new ArrayList<PackageInfo>();
14363    }
14364
14365    private int getUidTargetSdkVersionLockedLPr(int uid) {
14366        Object obj = mSettings.getUserIdLPr(uid);
14367        if (obj instanceof SharedUserSetting) {
14368            final SharedUserSetting sus = (SharedUserSetting) obj;
14369            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14370            final Iterator<PackageSetting> it = sus.packages.iterator();
14371            while (it.hasNext()) {
14372                final PackageSetting ps = it.next();
14373                if (ps.pkg != null) {
14374                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14375                    if (v < vers) vers = v;
14376                }
14377            }
14378            return vers;
14379        } else if (obj instanceof PackageSetting) {
14380            final PackageSetting ps = (PackageSetting) obj;
14381            if (ps.pkg != null) {
14382                return ps.pkg.applicationInfo.targetSdkVersion;
14383            }
14384        }
14385        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14386    }
14387
14388    @Override
14389    public void addPreferredActivity(IntentFilter filter, int match,
14390            ComponentName[] set, ComponentName activity, int userId) {
14391        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14392                "Adding preferred");
14393    }
14394
14395    private void addPreferredActivityInternal(IntentFilter filter, int match,
14396            ComponentName[] set, ComponentName activity, boolean always, int userId,
14397            String opname) {
14398        // writer
14399        int callingUid = Binder.getCallingUid();
14400        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14401        if (filter.countActions() == 0) {
14402            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14403            return;
14404        }
14405        synchronized (mPackages) {
14406            if (mContext.checkCallingOrSelfPermission(
14407                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14408                    != PackageManager.PERMISSION_GRANTED) {
14409                if (getUidTargetSdkVersionLockedLPr(callingUid)
14410                        < Build.VERSION_CODES.FROYO) {
14411                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14412                            + callingUid);
14413                    return;
14414                }
14415                mContext.enforceCallingOrSelfPermission(
14416                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14417            }
14418
14419            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14420            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14421                    + userId + ":");
14422            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14423            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14424            scheduleWritePackageRestrictionsLocked(userId);
14425        }
14426    }
14427
14428    @Override
14429    public void replacePreferredActivity(IntentFilter filter, int match,
14430            ComponentName[] set, ComponentName activity, int userId) {
14431        if (filter.countActions() != 1) {
14432            throw new IllegalArgumentException(
14433                    "replacePreferredActivity expects filter to have only 1 action.");
14434        }
14435        if (filter.countDataAuthorities() != 0
14436                || filter.countDataPaths() != 0
14437                || filter.countDataSchemes() > 1
14438                || filter.countDataTypes() != 0) {
14439            throw new IllegalArgumentException(
14440                    "replacePreferredActivity expects filter to have no data authorities, " +
14441                    "paths, or types; and at most one scheme.");
14442        }
14443
14444        final int callingUid = Binder.getCallingUid();
14445        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14446        synchronized (mPackages) {
14447            if (mContext.checkCallingOrSelfPermission(
14448                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14449                    != PackageManager.PERMISSION_GRANTED) {
14450                if (getUidTargetSdkVersionLockedLPr(callingUid)
14451                        < Build.VERSION_CODES.FROYO) {
14452                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14453                            + Binder.getCallingUid());
14454                    return;
14455                }
14456                mContext.enforceCallingOrSelfPermission(
14457                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14458            }
14459
14460            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14461            if (pir != null) {
14462                // Get all of the existing entries that exactly match this filter.
14463                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14464                if (existing != null && existing.size() == 1) {
14465                    PreferredActivity cur = existing.get(0);
14466                    if (DEBUG_PREFERRED) {
14467                        Slog.i(TAG, "Checking replace of preferred:");
14468                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14469                        if (!cur.mPref.mAlways) {
14470                            Slog.i(TAG, "  -- CUR; not mAlways!");
14471                        } else {
14472                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14473                            Slog.i(TAG, "  -- CUR: mSet="
14474                                    + Arrays.toString(cur.mPref.mSetComponents));
14475                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14476                            Slog.i(TAG, "  -- NEW: mMatch="
14477                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14478                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14479                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14480                        }
14481                    }
14482                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14483                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14484                            && cur.mPref.sameSet(set)) {
14485                        // Setting the preferred activity to what it happens to be already
14486                        if (DEBUG_PREFERRED) {
14487                            Slog.i(TAG, "Replacing with same preferred activity "
14488                                    + cur.mPref.mShortComponent + " for user "
14489                                    + userId + ":");
14490                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14491                        }
14492                        return;
14493                    }
14494                }
14495
14496                if (existing != null) {
14497                    if (DEBUG_PREFERRED) {
14498                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14499                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14500                    }
14501                    for (int i = 0; i < existing.size(); i++) {
14502                        PreferredActivity pa = existing.get(i);
14503                        if (DEBUG_PREFERRED) {
14504                            Slog.i(TAG, "Removing existing preferred activity "
14505                                    + pa.mPref.mComponent + ":");
14506                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14507                        }
14508                        pir.removeFilter(pa);
14509                    }
14510                }
14511            }
14512            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14513                    "Replacing preferred");
14514        }
14515    }
14516
14517    @Override
14518    public void clearPackagePreferredActivities(String packageName) {
14519        final int uid = Binder.getCallingUid();
14520        // writer
14521        synchronized (mPackages) {
14522            PackageParser.Package pkg = mPackages.get(packageName);
14523            if (pkg == null || pkg.applicationInfo.uid != uid) {
14524                if (mContext.checkCallingOrSelfPermission(
14525                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14526                        != PackageManager.PERMISSION_GRANTED) {
14527                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14528                            < Build.VERSION_CODES.FROYO) {
14529                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14530                                + Binder.getCallingUid());
14531                        return;
14532                    }
14533                    mContext.enforceCallingOrSelfPermission(
14534                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14535                }
14536            }
14537
14538            int user = UserHandle.getCallingUserId();
14539            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14540                scheduleWritePackageRestrictionsLocked(user);
14541            }
14542        }
14543    }
14544
14545    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14546    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14547        ArrayList<PreferredActivity> removed = null;
14548        boolean changed = false;
14549        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14550            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14551            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14552            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14553                continue;
14554            }
14555            Iterator<PreferredActivity> it = pir.filterIterator();
14556            while (it.hasNext()) {
14557                PreferredActivity pa = it.next();
14558                // Mark entry for removal only if it matches the package name
14559                // and the entry is of type "always".
14560                if (packageName == null ||
14561                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14562                                && pa.mPref.mAlways)) {
14563                    if (removed == null) {
14564                        removed = new ArrayList<PreferredActivity>();
14565                    }
14566                    removed.add(pa);
14567                }
14568            }
14569            if (removed != null) {
14570                for (int j=0; j<removed.size(); j++) {
14571                    PreferredActivity pa = removed.get(j);
14572                    pir.removeFilter(pa);
14573                }
14574                changed = true;
14575            }
14576        }
14577        return changed;
14578    }
14579
14580    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14581    private void clearIntentFilterVerificationsLPw(int userId) {
14582        final int packageCount = mPackages.size();
14583        for (int i = 0; i < packageCount; i++) {
14584            PackageParser.Package pkg = mPackages.valueAt(i);
14585            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14586        }
14587    }
14588
14589    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14590    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14591        if (userId == UserHandle.USER_ALL) {
14592            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14593                    sUserManager.getUserIds())) {
14594                for (int oneUserId : sUserManager.getUserIds()) {
14595                    scheduleWritePackageRestrictionsLocked(oneUserId);
14596                }
14597            }
14598        } else {
14599            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14600                scheduleWritePackageRestrictionsLocked(userId);
14601            }
14602        }
14603    }
14604
14605    void clearDefaultBrowserIfNeeded(String packageName) {
14606        for (int oneUserId : sUserManager.getUserIds()) {
14607            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14608            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14609            if (packageName.equals(defaultBrowserPackageName)) {
14610                setDefaultBrowserPackageName(null, oneUserId);
14611            }
14612        }
14613    }
14614
14615    @Override
14616    public void resetApplicationPreferences(int userId) {
14617        mContext.enforceCallingOrSelfPermission(
14618                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14619        // writer
14620        synchronized (mPackages) {
14621            final long identity = Binder.clearCallingIdentity();
14622            try {
14623                clearPackagePreferredActivitiesLPw(null, userId);
14624                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14625                // TODO: We have to reset the default SMS and Phone. This requires
14626                // significant refactoring to keep all default apps in the package
14627                // manager (cleaner but more work) or have the services provide
14628                // callbacks to the package manager to request a default app reset.
14629                applyFactoryDefaultBrowserLPw(userId);
14630                clearIntentFilterVerificationsLPw(userId);
14631                primeDomainVerificationsLPw(userId);
14632                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14633                scheduleWritePackageRestrictionsLocked(userId);
14634            } finally {
14635                Binder.restoreCallingIdentity(identity);
14636            }
14637        }
14638    }
14639
14640    @Override
14641    public int getPreferredActivities(List<IntentFilter> outFilters,
14642            List<ComponentName> outActivities, String packageName) {
14643
14644        int num = 0;
14645        final int userId = UserHandle.getCallingUserId();
14646        // reader
14647        synchronized (mPackages) {
14648            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14649            if (pir != null) {
14650                final Iterator<PreferredActivity> it = pir.filterIterator();
14651                while (it.hasNext()) {
14652                    final PreferredActivity pa = it.next();
14653                    if (packageName == null
14654                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14655                                    && pa.mPref.mAlways)) {
14656                        if (outFilters != null) {
14657                            outFilters.add(new IntentFilter(pa));
14658                        }
14659                        if (outActivities != null) {
14660                            outActivities.add(pa.mPref.mComponent);
14661                        }
14662                    }
14663                }
14664            }
14665        }
14666
14667        return num;
14668    }
14669
14670    @Override
14671    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14672            int userId) {
14673        int callingUid = Binder.getCallingUid();
14674        if (callingUid != Process.SYSTEM_UID) {
14675            throw new SecurityException(
14676                    "addPersistentPreferredActivity can only be run by the system");
14677        }
14678        if (filter.countActions() == 0) {
14679            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14680            return;
14681        }
14682        synchronized (mPackages) {
14683            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14684                    " :");
14685            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14686            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14687                    new PersistentPreferredActivity(filter, activity));
14688            scheduleWritePackageRestrictionsLocked(userId);
14689        }
14690    }
14691
14692    @Override
14693    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14694        int callingUid = Binder.getCallingUid();
14695        if (callingUid != Process.SYSTEM_UID) {
14696            throw new SecurityException(
14697                    "clearPackagePersistentPreferredActivities can only be run by the system");
14698        }
14699        ArrayList<PersistentPreferredActivity> removed = null;
14700        boolean changed = false;
14701        synchronized (mPackages) {
14702            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14703                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14704                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14705                        .valueAt(i);
14706                if (userId != thisUserId) {
14707                    continue;
14708                }
14709                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14710                while (it.hasNext()) {
14711                    PersistentPreferredActivity ppa = it.next();
14712                    // Mark entry for removal only if it matches the package name.
14713                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14714                        if (removed == null) {
14715                            removed = new ArrayList<PersistentPreferredActivity>();
14716                        }
14717                        removed.add(ppa);
14718                    }
14719                }
14720                if (removed != null) {
14721                    for (int j=0; j<removed.size(); j++) {
14722                        PersistentPreferredActivity ppa = removed.get(j);
14723                        ppir.removeFilter(ppa);
14724                    }
14725                    changed = true;
14726                }
14727            }
14728
14729            if (changed) {
14730                scheduleWritePackageRestrictionsLocked(userId);
14731            }
14732        }
14733    }
14734
14735    /**
14736     * Common machinery for picking apart a restored XML blob and passing
14737     * it to a caller-supplied functor to be applied to the running system.
14738     */
14739    private void restoreFromXml(XmlPullParser parser, int userId,
14740            String expectedStartTag, BlobXmlRestorer functor)
14741            throws IOException, XmlPullParserException {
14742        int type;
14743        while ((type = parser.next()) != XmlPullParser.START_TAG
14744                && type != XmlPullParser.END_DOCUMENT) {
14745        }
14746        if (type != XmlPullParser.START_TAG) {
14747            // oops didn't find a start tag?!
14748            if (DEBUG_BACKUP) {
14749                Slog.e(TAG, "Didn't find start tag during restore");
14750            }
14751            return;
14752        }
14753
14754        // this is supposed to be TAG_PREFERRED_BACKUP
14755        if (!expectedStartTag.equals(parser.getName())) {
14756            if (DEBUG_BACKUP) {
14757                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14758            }
14759            return;
14760        }
14761
14762        // skip interfering stuff, then we're aligned with the backing implementation
14763        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14764        functor.apply(parser, userId);
14765    }
14766
14767    private interface BlobXmlRestorer {
14768        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14769    }
14770
14771    /**
14772     * Non-Binder method, support for the backup/restore mechanism: write the
14773     * full set of preferred activities in its canonical XML format.  Returns the
14774     * XML output as a byte array, or null if there is none.
14775     */
14776    @Override
14777    public byte[] getPreferredActivityBackup(int userId) {
14778        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14779            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14780        }
14781
14782        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14783        try {
14784            final XmlSerializer serializer = new FastXmlSerializer();
14785            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14786            serializer.startDocument(null, true);
14787            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14788
14789            synchronized (mPackages) {
14790                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14791            }
14792
14793            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14794            serializer.endDocument();
14795            serializer.flush();
14796        } catch (Exception e) {
14797            if (DEBUG_BACKUP) {
14798                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14799            }
14800            return null;
14801        }
14802
14803        return dataStream.toByteArray();
14804    }
14805
14806    @Override
14807    public void restorePreferredActivities(byte[] backup, int userId) {
14808        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14809            throw new SecurityException("Only the system may call restorePreferredActivities()");
14810        }
14811
14812        try {
14813            final XmlPullParser parser = Xml.newPullParser();
14814            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14815            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14816                    new BlobXmlRestorer() {
14817                        @Override
14818                        public void apply(XmlPullParser parser, int userId)
14819                                throws XmlPullParserException, IOException {
14820                            synchronized (mPackages) {
14821                                mSettings.readPreferredActivitiesLPw(parser, userId);
14822                            }
14823                        }
14824                    } );
14825        } catch (Exception e) {
14826            if (DEBUG_BACKUP) {
14827                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14828            }
14829        }
14830    }
14831
14832    /**
14833     * Non-Binder method, support for the backup/restore mechanism: write the
14834     * default browser (etc) settings in its canonical XML format.  Returns the default
14835     * browser XML representation as a byte array, or null if there is none.
14836     */
14837    @Override
14838    public byte[] getDefaultAppsBackup(int userId) {
14839        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14840            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14841        }
14842
14843        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14844        try {
14845            final XmlSerializer serializer = new FastXmlSerializer();
14846            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14847            serializer.startDocument(null, true);
14848            serializer.startTag(null, TAG_DEFAULT_APPS);
14849
14850            synchronized (mPackages) {
14851                mSettings.writeDefaultAppsLPr(serializer, userId);
14852            }
14853
14854            serializer.endTag(null, TAG_DEFAULT_APPS);
14855            serializer.endDocument();
14856            serializer.flush();
14857        } catch (Exception e) {
14858            if (DEBUG_BACKUP) {
14859                Slog.e(TAG, "Unable to write default apps for backup", e);
14860            }
14861            return null;
14862        }
14863
14864        return dataStream.toByteArray();
14865    }
14866
14867    @Override
14868    public void restoreDefaultApps(byte[] backup, int userId) {
14869        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14870            throw new SecurityException("Only the system may call restoreDefaultApps()");
14871        }
14872
14873        try {
14874            final XmlPullParser parser = Xml.newPullParser();
14875            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14876            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14877                    new BlobXmlRestorer() {
14878                        @Override
14879                        public void apply(XmlPullParser parser, int userId)
14880                                throws XmlPullParserException, IOException {
14881                            synchronized (mPackages) {
14882                                mSettings.readDefaultAppsLPw(parser, userId);
14883                            }
14884                        }
14885                    } );
14886        } catch (Exception e) {
14887            if (DEBUG_BACKUP) {
14888                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14889            }
14890        }
14891    }
14892
14893    @Override
14894    public byte[] getIntentFilterVerificationBackup(int userId) {
14895        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14896            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14897        }
14898
14899        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14900        try {
14901            final XmlSerializer serializer = new FastXmlSerializer();
14902            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14903            serializer.startDocument(null, true);
14904            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14905
14906            synchronized (mPackages) {
14907                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14908            }
14909
14910            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14911            serializer.endDocument();
14912            serializer.flush();
14913        } catch (Exception e) {
14914            if (DEBUG_BACKUP) {
14915                Slog.e(TAG, "Unable to write default apps for backup", e);
14916            }
14917            return null;
14918        }
14919
14920        return dataStream.toByteArray();
14921    }
14922
14923    @Override
14924    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14925        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14926            throw new SecurityException("Only the system may call restorePreferredActivities()");
14927        }
14928
14929        try {
14930            final XmlPullParser parser = Xml.newPullParser();
14931            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14932            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14933                    new BlobXmlRestorer() {
14934                        @Override
14935                        public void apply(XmlPullParser parser, int userId)
14936                                throws XmlPullParserException, IOException {
14937                            synchronized (mPackages) {
14938                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14939                                mSettings.writeLPr();
14940                            }
14941                        }
14942                    } );
14943        } catch (Exception e) {
14944            if (DEBUG_BACKUP) {
14945                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14946            }
14947        }
14948    }
14949
14950    @Override
14951    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14952            int sourceUserId, int targetUserId, int flags) {
14953        mContext.enforceCallingOrSelfPermission(
14954                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14955        int callingUid = Binder.getCallingUid();
14956        enforceOwnerRights(ownerPackage, callingUid);
14957        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14958        if (intentFilter.countActions() == 0) {
14959            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14960            return;
14961        }
14962        synchronized (mPackages) {
14963            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14964                    ownerPackage, targetUserId, flags);
14965            CrossProfileIntentResolver resolver =
14966                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14967            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14968            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14969            if (existing != null) {
14970                int size = existing.size();
14971                for (int i = 0; i < size; i++) {
14972                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14973                        return;
14974                    }
14975                }
14976            }
14977            resolver.addFilter(newFilter);
14978            scheduleWritePackageRestrictionsLocked(sourceUserId);
14979        }
14980    }
14981
14982    @Override
14983    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14984        mContext.enforceCallingOrSelfPermission(
14985                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14986        int callingUid = Binder.getCallingUid();
14987        enforceOwnerRights(ownerPackage, callingUid);
14988        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14989        synchronized (mPackages) {
14990            CrossProfileIntentResolver resolver =
14991                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14992            ArraySet<CrossProfileIntentFilter> set =
14993                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14994            for (CrossProfileIntentFilter filter : set) {
14995                if (filter.getOwnerPackage().equals(ownerPackage)) {
14996                    resolver.removeFilter(filter);
14997                }
14998            }
14999            scheduleWritePackageRestrictionsLocked(sourceUserId);
15000        }
15001    }
15002
15003    // Enforcing that callingUid is owning pkg on userId
15004    private void enforceOwnerRights(String pkg, int callingUid) {
15005        // The system owns everything.
15006        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15007            return;
15008        }
15009        int callingUserId = UserHandle.getUserId(callingUid);
15010        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15011        if (pi == null) {
15012            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15013                    + callingUserId);
15014        }
15015        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15016            throw new SecurityException("Calling uid " + callingUid
15017                    + " does not own package " + pkg);
15018        }
15019    }
15020
15021    @Override
15022    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15023        Intent intent = new Intent(Intent.ACTION_MAIN);
15024        intent.addCategory(Intent.CATEGORY_HOME);
15025
15026        final int callingUserId = UserHandle.getCallingUserId();
15027        List<ResolveInfo> list = queryIntentActivities(intent, null,
15028                PackageManager.GET_META_DATA, callingUserId);
15029        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15030                true, false, false, callingUserId);
15031
15032        allHomeCandidates.clear();
15033        if (list != null) {
15034            for (ResolveInfo ri : list) {
15035                allHomeCandidates.add(ri);
15036            }
15037        }
15038        return (preferred == null || preferred.activityInfo == null)
15039                ? null
15040                : new ComponentName(preferred.activityInfo.packageName,
15041                        preferred.activityInfo.name);
15042    }
15043
15044    @Override
15045    public void setApplicationEnabledSetting(String appPackageName,
15046            int newState, int flags, int userId, String callingPackage) {
15047        if (!sUserManager.exists(userId)) return;
15048        if (callingPackage == null) {
15049            callingPackage = Integer.toString(Binder.getCallingUid());
15050        }
15051        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15052    }
15053
15054    @Override
15055    public void setComponentEnabledSetting(ComponentName componentName,
15056            int newState, int flags, int userId) {
15057        if (!sUserManager.exists(userId)) return;
15058        setEnabledSetting(componentName.getPackageName(),
15059                componentName.getClassName(), newState, flags, userId, null);
15060    }
15061
15062    private void setEnabledSetting(final String packageName, String className, int newState,
15063            final int flags, int userId, String callingPackage) {
15064        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15065              || newState == COMPONENT_ENABLED_STATE_ENABLED
15066              || newState == COMPONENT_ENABLED_STATE_DISABLED
15067              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15068              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15069            throw new IllegalArgumentException("Invalid new component state: "
15070                    + newState);
15071        }
15072        PackageSetting pkgSetting;
15073        final int uid = Binder.getCallingUid();
15074        final int permission = mContext.checkCallingOrSelfPermission(
15075                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15076        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15077        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15078        boolean sendNow = false;
15079        boolean isApp = (className == null);
15080        String componentName = isApp ? packageName : className;
15081        int packageUid = -1;
15082        ArrayList<String> components;
15083
15084        // writer
15085        synchronized (mPackages) {
15086            pkgSetting = mSettings.mPackages.get(packageName);
15087            if (pkgSetting == null) {
15088                if (className == null) {
15089                    throw new IllegalArgumentException(
15090                            "Unknown package: " + packageName);
15091                }
15092                throw new IllegalArgumentException(
15093                        "Unknown component: " + packageName
15094                        + "/" + className);
15095            }
15096            // Allow root and verify that userId is not being specified by a different user
15097            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15098                throw new SecurityException(
15099                        "Permission Denial: attempt to change component state from pid="
15100                        + Binder.getCallingPid()
15101                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15102            }
15103            if (className == null) {
15104                // We're dealing with an application/package level state change
15105                if (pkgSetting.getEnabled(userId) == newState) {
15106                    // Nothing to do
15107                    return;
15108                }
15109                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15110                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15111                    // Don't care about who enables an app.
15112                    callingPackage = null;
15113                }
15114                pkgSetting.setEnabled(newState, userId, callingPackage);
15115                // pkgSetting.pkg.mSetEnabled = newState;
15116            } else {
15117                // We're dealing with a component level state change
15118                // First, verify that this is a valid class name.
15119                PackageParser.Package pkg = pkgSetting.pkg;
15120                if (pkg == null || !pkg.hasComponentClassName(className)) {
15121                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
15122                        throw new IllegalArgumentException("Component class " + className
15123                                + " does not exist in " + packageName);
15124                    } else {
15125                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15126                                + className + " does not exist in " + packageName);
15127                    }
15128                }
15129                switch (newState) {
15130                case COMPONENT_ENABLED_STATE_ENABLED:
15131                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15132                        return;
15133                    }
15134                    break;
15135                case COMPONENT_ENABLED_STATE_DISABLED:
15136                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15137                        return;
15138                    }
15139                    break;
15140                case COMPONENT_ENABLED_STATE_DEFAULT:
15141                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15142                        return;
15143                    }
15144                    break;
15145                default:
15146                    Slog.e(TAG, "Invalid new component state: " + newState);
15147                    return;
15148                }
15149            }
15150            scheduleWritePackageRestrictionsLocked(userId);
15151            components = mPendingBroadcasts.get(userId, packageName);
15152            final boolean newPackage = components == null;
15153            if (newPackage) {
15154                components = new ArrayList<String>();
15155            }
15156            if (!components.contains(componentName)) {
15157                components.add(componentName);
15158            }
15159            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15160                sendNow = true;
15161                // Purge entry from pending broadcast list if another one exists already
15162                // since we are sending one right away.
15163                mPendingBroadcasts.remove(userId, packageName);
15164            } else {
15165                if (newPackage) {
15166                    mPendingBroadcasts.put(userId, packageName, components);
15167                }
15168                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15169                    // Schedule a message
15170                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15171                }
15172            }
15173        }
15174
15175        long callingId = Binder.clearCallingIdentity();
15176        try {
15177            if (sendNow) {
15178                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15179                sendPackageChangedBroadcast(packageName,
15180                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15181            }
15182        } finally {
15183            Binder.restoreCallingIdentity(callingId);
15184        }
15185    }
15186
15187    private void sendPackageChangedBroadcast(String packageName,
15188            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15189        if (DEBUG_INSTALL)
15190            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15191                    + componentNames);
15192        Bundle extras = new Bundle(4);
15193        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15194        String nameList[] = new String[componentNames.size()];
15195        componentNames.toArray(nameList);
15196        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15197        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15198        extras.putInt(Intent.EXTRA_UID, packageUid);
15199        // If this is not reporting a change of the overall package, then only send it
15200        // to registered receivers.  We don't want to launch a swath of apps for every
15201        // little component state change.
15202        final int flags = !componentNames.contains(packageName)
15203                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15204        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15205                new int[] {UserHandle.getUserId(packageUid)});
15206    }
15207
15208    @Override
15209    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15210        if (!sUserManager.exists(userId)) return;
15211        final int uid = Binder.getCallingUid();
15212        final int permission = mContext.checkCallingOrSelfPermission(
15213                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15214        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15215        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15216        // writer
15217        synchronized (mPackages) {
15218            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15219                    allowedByPermission, uid, userId)) {
15220                scheduleWritePackageRestrictionsLocked(userId);
15221            }
15222        }
15223    }
15224
15225    @Override
15226    public String getInstallerPackageName(String packageName) {
15227        // reader
15228        synchronized (mPackages) {
15229            return mSettings.getInstallerPackageNameLPr(packageName);
15230        }
15231    }
15232
15233    @Override
15234    public int getApplicationEnabledSetting(String packageName, int userId) {
15235        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15236        int uid = Binder.getCallingUid();
15237        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15238        // reader
15239        synchronized (mPackages) {
15240            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15241        }
15242    }
15243
15244    @Override
15245    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15246        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15247        int uid = Binder.getCallingUid();
15248        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15249        // reader
15250        synchronized (mPackages) {
15251            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15252        }
15253    }
15254
15255    @Override
15256    public void enterSafeMode() {
15257        enforceSystemOrRoot("Only the system can request entering safe mode");
15258
15259        if (!mSystemReady) {
15260            mSafeMode = true;
15261        }
15262    }
15263
15264    @Override
15265    public void systemReady() {
15266        mSystemReady = true;
15267
15268        // Read the compatibilty setting when the system is ready.
15269        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15270                mContext.getContentResolver(),
15271                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15272        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15273        if (DEBUG_SETTINGS) {
15274            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15275        }
15276
15277        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15278
15279        synchronized (mPackages) {
15280            // Verify that all of the preferred activity components actually
15281            // exist.  It is possible for applications to be updated and at
15282            // that point remove a previously declared activity component that
15283            // had been set as a preferred activity.  We try to clean this up
15284            // the next time we encounter that preferred activity, but it is
15285            // possible for the user flow to never be able to return to that
15286            // situation so here we do a sanity check to make sure we haven't
15287            // left any junk around.
15288            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15289            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15290                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15291                removed.clear();
15292                for (PreferredActivity pa : pir.filterSet()) {
15293                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15294                        removed.add(pa);
15295                    }
15296                }
15297                if (removed.size() > 0) {
15298                    for (int r=0; r<removed.size(); r++) {
15299                        PreferredActivity pa = removed.get(r);
15300                        Slog.w(TAG, "Removing dangling preferred activity: "
15301                                + pa.mPref.mComponent);
15302                        pir.removeFilter(pa);
15303                    }
15304                    mSettings.writePackageRestrictionsLPr(
15305                            mSettings.mPreferredActivities.keyAt(i));
15306                }
15307            }
15308
15309            for (int userId : UserManagerService.getInstance().getUserIds()) {
15310                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15311                    grantPermissionsUserIds = ArrayUtils.appendInt(
15312                            grantPermissionsUserIds, userId);
15313                }
15314            }
15315        }
15316        sUserManager.systemReady();
15317
15318        // If we upgraded grant all default permissions before kicking off.
15319        for (int userId : grantPermissionsUserIds) {
15320            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15321        }
15322
15323        // Kick off any messages waiting for system ready
15324        if (mPostSystemReadyMessages != null) {
15325            for (Message msg : mPostSystemReadyMessages) {
15326                msg.sendToTarget();
15327            }
15328            mPostSystemReadyMessages = null;
15329        }
15330
15331        // Watch for external volumes that come and go over time
15332        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15333        storage.registerListener(mStorageListener);
15334
15335        mInstallerService.systemReady();
15336        mPackageDexOptimizer.systemReady();
15337
15338        MountServiceInternal mountServiceInternal = LocalServices.getService(
15339                MountServiceInternal.class);
15340        mountServiceInternal.addExternalStoragePolicy(
15341                new MountServiceInternal.ExternalStorageMountPolicy() {
15342            @Override
15343            public int getMountMode(int uid, String packageName) {
15344                if (Process.isIsolated(uid)) {
15345                    return Zygote.MOUNT_EXTERNAL_NONE;
15346                }
15347                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15348                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15349                }
15350                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15351                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15352                }
15353                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15354                    return Zygote.MOUNT_EXTERNAL_READ;
15355                }
15356                return Zygote.MOUNT_EXTERNAL_WRITE;
15357            }
15358
15359            @Override
15360            public boolean hasExternalStorage(int uid, String packageName) {
15361                return true;
15362            }
15363        });
15364    }
15365
15366    @Override
15367    public boolean isSafeMode() {
15368        return mSafeMode;
15369    }
15370
15371    @Override
15372    public boolean hasSystemUidErrors() {
15373        return mHasSystemUidErrors;
15374    }
15375
15376    static String arrayToString(int[] array) {
15377        StringBuffer buf = new StringBuffer(128);
15378        buf.append('[');
15379        if (array != null) {
15380            for (int i=0; i<array.length; i++) {
15381                if (i > 0) buf.append(", ");
15382                buf.append(array[i]);
15383            }
15384        }
15385        buf.append(']');
15386        return buf.toString();
15387    }
15388
15389    static class DumpState {
15390        public static final int DUMP_LIBS = 1 << 0;
15391        public static final int DUMP_FEATURES = 1 << 1;
15392        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15393        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15394        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15395        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15396        public static final int DUMP_PERMISSIONS = 1 << 6;
15397        public static final int DUMP_PACKAGES = 1 << 7;
15398        public static final int DUMP_SHARED_USERS = 1 << 8;
15399        public static final int DUMP_MESSAGES = 1 << 9;
15400        public static final int DUMP_PROVIDERS = 1 << 10;
15401        public static final int DUMP_VERIFIERS = 1 << 11;
15402        public static final int DUMP_PREFERRED = 1 << 12;
15403        public static final int DUMP_PREFERRED_XML = 1 << 13;
15404        public static final int DUMP_KEYSETS = 1 << 14;
15405        public static final int DUMP_VERSION = 1 << 15;
15406        public static final int DUMP_INSTALLS = 1 << 16;
15407        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15408        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15409
15410        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15411
15412        private int mTypes;
15413
15414        private int mOptions;
15415
15416        private boolean mTitlePrinted;
15417
15418        private SharedUserSetting mSharedUser;
15419
15420        public boolean isDumping(int type) {
15421            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15422                return true;
15423            }
15424
15425            return (mTypes & type) != 0;
15426        }
15427
15428        public void setDump(int type) {
15429            mTypes |= type;
15430        }
15431
15432        public boolean isOptionEnabled(int option) {
15433            return (mOptions & option) != 0;
15434        }
15435
15436        public void setOptionEnabled(int option) {
15437            mOptions |= option;
15438        }
15439
15440        public boolean onTitlePrinted() {
15441            final boolean printed = mTitlePrinted;
15442            mTitlePrinted = true;
15443            return printed;
15444        }
15445
15446        public boolean getTitlePrinted() {
15447            return mTitlePrinted;
15448        }
15449
15450        public void setTitlePrinted(boolean enabled) {
15451            mTitlePrinted = enabled;
15452        }
15453
15454        public SharedUserSetting getSharedUser() {
15455            return mSharedUser;
15456        }
15457
15458        public void setSharedUser(SharedUserSetting user) {
15459            mSharedUser = user;
15460        }
15461    }
15462
15463    @Override
15464    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15465            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15466        (new PackageManagerShellCommand(this)).exec(
15467                this, in, out, err, args, resultReceiver);
15468    }
15469
15470    @Override
15471    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15472        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15473                != PackageManager.PERMISSION_GRANTED) {
15474            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15475                    + Binder.getCallingPid()
15476                    + ", uid=" + Binder.getCallingUid()
15477                    + " without permission "
15478                    + android.Manifest.permission.DUMP);
15479            return;
15480        }
15481
15482        DumpState dumpState = new DumpState();
15483        boolean fullPreferred = false;
15484        boolean checkin = false;
15485
15486        String packageName = null;
15487        ArraySet<String> permissionNames = null;
15488
15489        int opti = 0;
15490        while (opti < args.length) {
15491            String opt = args[opti];
15492            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15493                break;
15494            }
15495            opti++;
15496
15497            if ("-a".equals(opt)) {
15498                // Right now we only know how to print all.
15499            } else if ("-h".equals(opt)) {
15500                pw.println("Package manager dump options:");
15501                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15502                pw.println("    --checkin: dump for a checkin");
15503                pw.println("    -f: print details of intent filters");
15504                pw.println("    -h: print this help");
15505                pw.println("  cmd may be one of:");
15506                pw.println("    l[ibraries]: list known shared libraries");
15507                pw.println("    f[eatures]: list device features");
15508                pw.println("    k[eysets]: print known keysets");
15509                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15510                pw.println("    perm[issions]: dump permissions");
15511                pw.println("    permission [name ...]: dump declaration and use of given permission");
15512                pw.println("    pref[erred]: print preferred package settings");
15513                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15514                pw.println("    prov[iders]: dump content providers");
15515                pw.println("    p[ackages]: dump installed packages");
15516                pw.println("    s[hared-users]: dump shared user IDs");
15517                pw.println("    m[essages]: print collected runtime messages");
15518                pw.println("    v[erifiers]: print package verifier info");
15519                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15520                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15521                pw.println("    version: print database version info");
15522                pw.println("    write: write current settings now");
15523                pw.println("    installs: details about install sessions");
15524                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15525                pw.println("    <package.name>: info about given package");
15526                return;
15527            } else if ("--checkin".equals(opt)) {
15528                checkin = true;
15529            } else if ("-f".equals(opt)) {
15530                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15531            } else {
15532                pw.println("Unknown argument: " + opt + "; use -h for help");
15533            }
15534        }
15535
15536        // Is the caller requesting to dump a particular piece of data?
15537        if (opti < args.length) {
15538            String cmd = args[opti];
15539            opti++;
15540            // Is this a package name?
15541            if ("android".equals(cmd) || cmd.contains(".")) {
15542                packageName = cmd;
15543                // When dumping a single package, we always dump all of its
15544                // filter information since the amount of data will be reasonable.
15545                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15546            } else if ("check-permission".equals(cmd)) {
15547                if (opti >= args.length) {
15548                    pw.println("Error: check-permission missing permission argument");
15549                    return;
15550                }
15551                String perm = args[opti];
15552                opti++;
15553                if (opti >= args.length) {
15554                    pw.println("Error: check-permission missing package argument");
15555                    return;
15556                }
15557                String pkg = args[opti];
15558                opti++;
15559                int user = UserHandle.getUserId(Binder.getCallingUid());
15560                if (opti < args.length) {
15561                    try {
15562                        user = Integer.parseInt(args[opti]);
15563                    } catch (NumberFormatException e) {
15564                        pw.println("Error: check-permission user argument is not a number: "
15565                                + args[opti]);
15566                        return;
15567                    }
15568                }
15569                pw.println(checkPermission(perm, pkg, user));
15570                return;
15571            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15572                dumpState.setDump(DumpState.DUMP_LIBS);
15573            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15574                dumpState.setDump(DumpState.DUMP_FEATURES);
15575            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15576                if (opti >= args.length) {
15577                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15578                            | DumpState.DUMP_SERVICE_RESOLVERS
15579                            | DumpState.DUMP_RECEIVER_RESOLVERS
15580                            | DumpState.DUMP_CONTENT_RESOLVERS);
15581                } else {
15582                    while (opti < args.length) {
15583                        String name = args[opti];
15584                        if ("a".equals(name) || "activity".equals(name)) {
15585                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15586                        } else if ("s".equals(name) || "service".equals(name)) {
15587                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15588                        } else if ("r".equals(name) || "receiver".equals(name)) {
15589                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15590                        } else if ("c".equals(name) || "content".equals(name)) {
15591                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15592                        } else {
15593                            pw.println("Error: unknown resolver table type: " + name);
15594                            return;
15595                        }
15596                        opti++;
15597                    }
15598                }
15599            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15600                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15601            } else if ("permission".equals(cmd)) {
15602                if (opti >= args.length) {
15603                    pw.println("Error: permission requires permission name");
15604                    return;
15605                }
15606                permissionNames = new ArraySet<>();
15607                while (opti < args.length) {
15608                    permissionNames.add(args[opti]);
15609                    opti++;
15610                }
15611                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15612                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15613            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15614                dumpState.setDump(DumpState.DUMP_PREFERRED);
15615            } else if ("preferred-xml".equals(cmd)) {
15616                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15617                if (opti < args.length && "--full".equals(args[opti])) {
15618                    fullPreferred = true;
15619                    opti++;
15620                }
15621            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15622                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15623            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15624                dumpState.setDump(DumpState.DUMP_PACKAGES);
15625            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15626                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15627            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15628                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15629            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15630                dumpState.setDump(DumpState.DUMP_MESSAGES);
15631            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15632                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15633            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15634                    || "intent-filter-verifiers".equals(cmd)) {
15635                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15636            } else if ("version".equals(cmd)) {
15637                dumpState.setDump(DumpState.DUMP_VERSION);
15638            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15639                dumpState.setDump(DumpState.DUMP_KEYSETS);
15640            } else if ("installs".equals(cmd)) {
15641                dumpState.setDump(DumpState.DUMP_INSTALLS);
15642            } else if ("write".equals(cmd)) {
15643                synchronized (mPackages) {
15644                    mSettings.writeLPr();
15645                    pw.println("Settings written.");
15646                    return;
15647                }
15648            }
15649        }
15650
15651        if (checkin) {
15652            pw.println("vers,1");
15653        }
15654
15655        // reader
15656        synchronized (mPackages) {
15657            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15658                if (!checkin) {
15659                    if (dumpState.onTitlePrinted())
15660                        pw.println();
15661                    pw.println("Database versions:");
15662                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15663                }
15664            }
15665
15666            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15667                if (!checkin) {
15668                    if (dumpState.onTitlePrinted())
15669                        pw.println();
15670                    pw.println("Verifiers:");
15671                    pw.print("  Required: ");
15672                    pw.print(mRequiredVerifierPackage);
15673                    pw.print(" (uid=");
15674                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15675                    pw.println(")");
15676                } else if (mRequiredVerifierPackage != null) {
15677                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15678                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15679                }
15680            }
15681
15682            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15683                    packageName == null) {
15684                if (mIntentFilterVerifierComponent != null) {
15685                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15686                    if (!checkin) {
15687                        if (dumpState.onTitlePrinted())
15688                            pw.println();
15689                        pw.println("Intent Filter Verifier:");
15690                        pw.print("  Using: ");
15691                        pw.print(verifierPackageName);
15692                        pw.print(" (uid=");
15693                        pw.print(getPackageUid(verifierPackageName, 0));
15694                        pw.println(")");
15695                    } else if (verifierPackageName != null) {
15696                        pw.print("ifv,"); pw.print(verifierPackageName);
15697                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15698                    }
15699                } else {
15700                    pw.println();
15701                    pw.println("No Intent Filter Verifier available!");
15702                }
15703            }
15704
15705            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15706                boolean printedHeader = false;
15707                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15708                while (it.hasNext()) {
15709                    String name = it.next();
15710                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15711                    if (!checkin) {
15712                        if (!printedHeader) {
15713                            if (dumpState.onTitlePrinted())
15714                                pw.println();
15715                            pw.println("Libraries:");
15716                            printedHeader = true;
15717                        }
15718                        pw.print("  ");
15719                    } else {
15720                        pw.print("lib,");
15721                    }
15722                    pw.print(name);
15723                    if (!checkin) {
15724                        pw.print(" -> ");
15725                    }
15726                    if (ent.path != null) {
15727                        if (!checkin) {
15728                            pw.print("(jar) ");
15729                            pw.print(ent.path);
15730                        } else {
15731                            pw.print(",jar,");
15732                            pw.print(ent.path);
15733                        }
15734                    } else {
15735                        if (!checkin) {
15736                            pw.print("(apk) ");
15737                            pw.print(ent.apk);
15738                        } else {
15739                            pw.print(",apk,");
15740                            pw.print(ent.apk);
15741                        }
15742                    }
15743                    pw.println();
15744                }
15745            }
15746
15747            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15748                if (dumpState.onTitlePrinted())
15749                    pw.println();
15750                if (!checkin) {
15751                    pw.println("Features:");
15752                }
15753                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15754                while (it.hasNext()) {
15755                    String name = it.next();
15756                    if (!checkin) {
15757                        pw.print("  ");
15758                    } else {
15759                        pw.print("feat,");
15760                    }
15761                    pw.println(name);
15762                }
15763            }
15764
15765            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15766                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15767                        : "Activity Resolver Table:", "  ", packageName,
15768                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15769                    dumpState.setTitlePrinted(true);
15770                }
15771            }
15772            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15773                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15774                        : "Receiver Resolver Table:", "  ", packageName,
15775                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15776                    dumpState.setTitlePrinted(true);
15777                }
15778            }
15779            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15780                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15781                        : "Service Resolver Table:", "  ", packageName,
15782                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15783                    dumpState.setTitlePrinted(true);
15784                }
15785            }
15786            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15787                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15788                        : "Provider Resolver Table:", "  ", packageName,
15789                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15790                    dumpState.setTitlePrinted(true);
15791                }
15792            }
15793
15794            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15795                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15796                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15797                    int user = mSettings.mPreferredActivities.keyAt(i);
15798                    if (pir.dump(pw,
15799                            dumpState.getTitlePrinted()
15800                                ? "\nPreferred Activities User " + user + ":"
15801                                : "Preferred Activities User " + user + ":", "  ",
15802                            packageName, true, false)) {
15803                        dumpState.setTitlePrinted(true);
15804                    }
15805                }
15806            }
15807
15808            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15809                pw.flush();
15810                FileOutputStream fout = new FileOutputStream(fd);
15811                BufferedOutputStream str = new BufferedOutputStream(fout);
15812                XmlSerializer serializer = new FastXmlSerializer();
15813                try {
15814                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15815                    serializer.startDocument(null, true);
15816                    serializer.setFeature(
15817                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15818                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15819                    serializer.endDocument();
15820                    serializer.flush();
15821                } catch (IllegalArgumentException e) {
15822                    pw.println("Failed writing: " + e);
15823                } catch (IllegalStateException e) {
15824                    pw.println("Failed writing: " + e);
15825                } catch (IOException e) {
15826                    pw.println("Failed writing: " + e);
15827                }
15828            }
15829
15830            if (!checkin
15831                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15832                    && packageName == null) {
15833                pw.println();
15834                int count = mSettings.mPackages.size();
15835                if (count == 0) {
15836                    pw.println("No applications!");
15837                    pw.println();
15838                } else {
15839                    final String prefix = "  ";
15840                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15841                    if (allPackageSettings.size() == 0) {
15842                        pw.println("No domain preferred apps!");
15843                        pw.println();
15844                    } else {
15845                        pw.println("App verification status:");
15846                        pw.println();
15847                        count = 0;
15848                        for (PackageSetting ps : allPackageSettings) {
15849                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15850                            if (ivi == null || ivi.getPackageName() == null) continue;
15851                            pw.println(prefix + "Package: " + ivi.getPackageName());
15852                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15853                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15854                            pw.println();
15855                            count++;
15856                        }
15857                        if (count == 0) {
15858                            pw.println(prefix + "No app verification established.");
15859                            pw.println();
15860                        }
15861                        for (int userId : sUserManager.getUserIds()) {
15862                            pw.println("App linkages for user " + userId + ":");
15863                            pw.println();
15864                            count = 0;
15865                            for (PackageSetting ps : allPackageSettings) {
15866                                final long status = ps.getDomainVerificationStatusForUser(userId);
15867                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15868                                    continue;
15869                                }
15870                                pw.println(prefix + "Package: " + ps.name);
15871                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15872                                String statusStr = IntentFilterVerificationInfo.
15873                                        getStatusStringFromValue(status);
15874                                pw.println(prefix + "Status:  " + statusStr);
15875                                pw.println();
15876                                count++;
15877                            }
15878                            if (count == 0) {
15879                                pw.println(prefix + "No configured app linkages.");
15880                                pw.println();
15881                            }
15882                        }
15883                    }
15884                }
15885            }
15886
15887            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15888                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15889                if (packageName == null && permissionNames == null) {
15890                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15891                        if (iperm == 0) {
15892                            if (dumpState.onTitlePrinted())
15893                                pw.println();
15894                            pw.println("AppOp Permissions:");
15895                        }
15896                        pw.print("  AppOp Permission ");
15897                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15898                        pw.println(":");
15899                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15900                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15901                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15902                        }
15903                    }
15904                }
15905            }
15906
15907            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15908                boolean printedSomething = false;
15909                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15910                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15911                        continue;
15912                    }
15913                    if (!printedSomething) {
15914                        if (dumpState.onTitlePrinted())
15915                            pw.println();
15916                        pw.println("Registered ContentProviders:");
15917                        printedSomething = true;
15918                    }
15919                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15920                    pw.print("    "); pw.println(p.toString());
15921                }
15922                printedSomething = false;
15923                for (Map.Entry<String, PackageParser.Provider> entry :
15924                        mProvidersByAuthority.entrySet()) {
15925                    PackageParser.Provider p = entry.getValue();
15926                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15927                        continue;
15928                    }
15929                    if (!printedSomething) {
15930                        if (dumpState.onTitlePrinted())
15931                            pw.println();
15932                        pw.println("ContentProvider Authorities:");
15933                        printedSomething = true;
15934                    }
15935                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15936                    pw.print("    "); pw.println(p.toString());
15937                    if (p.info != null && p.info.applicationInfo != null) {
15938                        final String appInfo = p.info.applicationInfo.toString();
15939                        pw.print("      applicationInfo="); pw.println(appInfo);
15940                    }
15941                }
15942            }
15943
15944            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15945                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15946            }
15947
15948            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15949                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15950            }
15951
15952            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15953                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15954            }
15955
15956            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15957                // XXX should handle packageName != null by dumping only install data that
15958                // the given package is involved with.
15959                if (dumpState.onTitlePrinted()) pw.println();
15960                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15961            }
15962
15963            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15964                if (dumpState.onTitlePrinted()) pw.println();
15965                mSettings.dumpReadMessagesLPr(pw, dumpState);
15966
15967                pw.println();
15968                pw.println("Package warning messages:");
15969                BufferedReader in = null;
15970                String line = null;
15971                try {
15972                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15973                    while ((line = in.readLine()) != null) {
15974                        if (line.contains("ignored: updated version")) continue;
15975                        pw.println(line);
15976                    }
15977                } catch (IOException ignored) {
15978                } finally {
15979                    IoUtils.closeQuietly(in);
15980                }
15981            }
15982
15983            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15984                BufferedReader in = null;
15985                String line = null;
15986                try {
15987                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15988                    while ((line = in.readLine()) != null) {
15989                        if (line.contains("ignored: updated version")) continue;
15990                        pw.print("msg,");
15991                        pw.println(line);
15992                    }
15993                } catch (IOException ignored) {
15994                } finally {
15995                    IoUtils.closeQuietly(in);
15996                }
15997            }
15998        }
15999    }
16000
16001    private String dumpDomainString(String packageName) {
16002        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16003        List<IntentFilter> filters = getAllIntentFilters(packageName);
16004
16005        ArraySet<String> result = new ArraySet<>();
16006        if (iviList.size() > 0) {
16007            for (IntentFilterVerificationInfo ivi : iviList) {
16008                for (String host : ivi.getDomains()) {
16009                    result.add(host);
16010                }
16011            }
16012        }
16013        if (filters != null && filters.size() > 0) {
16014            for (IntentFilter filter : filters) {
16015                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16016                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16017                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16018                    result.addAll(filter.getHostsList());
16019                }
16020            }
16021        }
16022
16023        StringBuilder sb = new StringBuilder(result.size() * 16);
16024        for (String domain : result) {
16025            if (sb.length() > 0) sb.append(" ");
16026            sb.append(domain);
16027        }
16028        return sb.toString();
16029    }
16030
16031    // ------- apps on sdcard specific code -------
16032    static final boolean DEBUG_SD_INSTALL = false;
16033
16034    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16035
16036    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16037
16038    private boolean mMediaMounted = false;
16039
16040    static String getEncryptKey() {
16041        try {
16042            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16043                    SD_ENCRYPTION_KEYSTORE_NAME);
16044            if (sdEncKey == null) {
16045                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16046                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16047                if (sdEncKey == null) {
16048                    Slog.e(TAG, "Failed to create encryption keys");
16049                    return null;
16050                }
16051            }
16052            return sdEncKey;
16053        } catch (NoSuchAlgorithmException nsae) {
16054            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16055            return null;
16056        } catch (IOException ioe) {
16057            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16058            return null;
16059        }
16060    }
16061
16062    /*
16063     * Update media status on PackageManager.
16064     */
16065    @Override
16066    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16067        int callingUid = Binder.getCallingUid();
16068        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16069            throw new SecurityException("Media status can only be updated by the system");
16070        }
16071        // reader; this apparently protects mMediaMounted, but should probably
16072        // be a different lock in that case.
16073        synchronized (mPackages) {
16074            Log.i(TAG, "Updating external media status from "
16075                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16076                    + (mediaStatus ? "mounted" : "unmounted"));
16077            if (DEBUG_SD_INSTALL)
16078                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16079                        + ", mMediaMounted=" + mMediaMounted);
16080            if (mediaStatus == mMediaMounted) {
16081                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16082                        : 0, -1);
16083                mHandler.sendMessage(msg);
16084                return;
16085            }
16086            mMediaMounted = mediaStatus;
16087        }
16088        // Queue up an async operation since the package installation may take a
16089        // little while.
16090        mHandler.post(new Runnable() {
16091            public void run() {
16092                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16093            }
16094        });
16095    }
16096
16097    /**
16098     * Called by MountService when the initial ASECs to scan are available.
16099     * Should block until all the ASEC containers are finished being scanned.
16100     */
16101    public void scanAvailableAsecs() {
16102        updateExternalMediaStatusInner(true, false, false);
16103        if (mShouldRestoreconData) {
16104            SELinuxMMAC.setRestoreconDone();
16105            mShouldRestoreconData = false;
16106        }
16107    }
16108
16109    /*
16110     * Collect information of applications on external media, map them against
16111     * existing containers and update information based on current mount status.
16112     * Please note that we always have to report status if reportStatus has been
16113     * set to true especially when unloading packages.
16114     */
16115    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16116            boolean externalStorage) {
16117        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16118        int[] uidArr = EmptyArray.INT;
16119
16120        final String[] list = PackageHelper.getSecureContainerList();
16121        if (ArrayUtils.isEmpty(list)) {
16122            Log.i(TAG, "No secure containers found");
16123        } else {
16124            // Process list of secure containers and categorize them
16125            // as active or stale based on their package internal state.
16126
16127            // reader
16128            synchronized (mPackages) {
16129                for (String cid : list) {
16130                    // Leave stages untouched for now; installer service owns them
16131                    if (PackageInstallerService.isStageName(cid)) continue;
16132
16133                    if (DEBUG_SD_INSTALL)
16134                        Log.i(TAG, "Processing container " + cid);
16135                    String pkgName = getAsecPackageName(cid);
16136                    if (pkgName == null) {
16137                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16138                        continue;
16139                    }
16140                    if (DEBUG_SD_INSTALL)
16141                        Log.i(TAG, "Looking for pkg : " + pkgName);
16142
16143                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16144                    if (ps == null) {
16145                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16146                        continue;
16147                    }
16148
16149                    /*
16150                     * Skip packages that are not external if we're unmounting
16151                     * external storage.
16152                     */
16153                    if (externalStorage && !isMounted && !isExternal(ps)) {
16154                        continue;
16155                    }
16156
16157                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16158                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16159                    // The package status is changed only if the code path
16160                    // matches between settings and the container id.
16161                    if (ps.codePathString != null
16162                            && ps.codePathString.startsWith(args.getCodePath())) {
16163                        if (DEBUG_SD_INSTALL) {
16164                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16165                                    + " at code path: " + ps.codePathString);
16166                        }
16167
16168                        // We do have a valid package installed on sdcard
16169                        processCids.put(args, ps.codePathString);
16170                        final int uid = ps.appId;
16171                        if (uid != -1) {
16172                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16173                        }
16174                    } else {
16175                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16176                                + ps.codePathString);
16177                    }
16178                }
16179            }
16180
16181            Arrays.sort(uidArr);
16182        }
16183
16184        // Process packages with valid entries.
16185        if (isMounted) {
16186            if (DEBUG_SD_INSTALL)
16187                Log.i(TAG, "Loading packages");
16188            loadMediaPackages(processCids, uidArr, externalStorage);
16189            startCleaningPackages();
16190            mInstallerService.onSecureContainersAvailable();
16191        } else {
16192            if (DEBUG_SD_INSTALL)
16193                Log.i(TAG, "Unloading packages");
16194            unloadMediaPackages(processCids, uidArr, reportStatus);
16195        }
16196    }
16197
16198    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16199            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16200        final int size = infos.size();
16201        final String[] packageNames = new String[size];
16202        final int[] packageUids = new int[size];
16203        for (int i = 0; i < size; i++) {
16204            final ApplicationInfo info = infos.get(i);
16205            packageNames[i] = info.packageName;
16206            packageUids[i] = info.uid;
16207        }
16208        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16209                finishedReceiver);
16210    }
16211
16212    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16213            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16214        sendResourcesChangedBroadcast(mediaStatus, replacing,
16215                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16216    }
16217
16218    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16219            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16220        int size = pkgList.length;
16221        if (size > 0) {
16222            // Send broadcasts here
16223            Bundle extras = new Bundle();
16224            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16225            if (uidArr != null) {
16226                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16227            }
16228            if (replacing) {
16229                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16230            }
16231            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16232                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16233            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16234        }
16235    }
16236
16237   /*
16238     * Look at potentially valid container ids from processCids If package
16239     * information doesn't match the one on record or package scanning fails,
16240     * the cid is added to list of removeCids. We currently don't delete stale
16241     * containers.
16242     */
16243    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16244            boolean externalStorage) {
16245        ArrayList<String> pkgList = new ArrayList<String>();
16246        Set<AsecInstallArgs> keys = processCids.keySet();
16247
16248        for (AsecInstallArgs args : keys) {
16249            String codePath = processCids.get(args);
16250            if (DEBUG_SD_INSTALL)
16251                Log.i(TAG, "Loading container : " + args.cid);
16252            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16253            try {
16254                // Make sure there are no container errors first.
16255                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16256                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16257                            + " when installing from sdcard");
16258                    continue;
16259                }
16260                // Check code path here.
16261                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16262                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16263                            + " does not match one in settings " + codePath);
16264                    continue;
16265                }
16266                // Parse package
16267                int parseFlags = mDefParseFlags;
16268                if (args.isExternalAsec()) {
16269                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16270                }
16271                if (args.isFwdLocked()) {
16272                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16273                }
16274
16275                synchronized (mInstallLock) {
16276                    PackageParser.Package pkg = null;
16277                    try {
16278                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16279                    } catch (PackageManagerException e) {
16280                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16281                    }
16282                    // Scan the package
16283                    if (pkg != null) {
16284                        /*
16285                         * TODO why is the lock being held? doPostInstall is
16286                         * called in other places without the lock. This needs
16287                         * to be straightened out.
16288                         */
16289                        // writer
16290                        synchronized (mPackages) {
16291                            retCode = PackageManager.INSTALL_SUCCEEDED;
16292                            pkgList.add(pkg.packageName);
16293                            // Post process args
16294                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16295                                    pkg.applicationInfo.uid);
16296                        }
16297                    } else {
16298                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16299                    }
16300                }
16301
16302            } finally {
16303                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16304                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16305                }
16306            }
16307        }
16308        // writer
16309        synchronized (mPackages) {
16310            // If the platform SDK has changed since the last time we booted,
16311            // we need to re-grant app permission to catch any new ones that
16312            // appear. This is really a hack, and means that apps can in some
16313            // cases get permissions that the user didn't initially explicitly
16314            // allow... it would be nice to have some better way to handle
16315            // this situation.
16316            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16317                    : mSettings.getInternalVersion();
16318            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16319                    : StorageManager.UUID_PRIVATE_INTERNAL;
16320
16321            int updateFlags = UPDATE_PERMISSIONS_ALL;
16322            if (ver.sdkVersion != mSdkVersion) {
16323                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16324                        + mSdkVersion + "; regranting permissions for external");
16325                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16326            }
16327            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16328
16329            // Yay, everything is now upgraded
16330            ver.forceCurrent();
16331
16332            // can downgrade to reader
16333            // Persist settings
16334            mSettings.writeLPr();
16335        }
16336        // Send a broadcast to let everyone know we are done processing
16337        if (pkgList.size() > 0) {
16338            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16339        }
16340    }
16341
16342   /*
16343     * Utility method to unload a list of specified containers
16344     */
16345    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16346        // Just unmount all valid containers.
16347        for (AsecInstallArgs arg : cidArgs) {
16348            synchronized (mInstallLock) {
16349                arg.doPostDeleteLI(false);
16350           }
16351       }
16352   }
16353
16354    /*
16355     * Unload packages mounted on external media. This involves deleting package
16356     * data from internal structures, sending broadcasts about diabled packages,
16357     * gc'ing to free up references, unmounting all secure containers
16358     * corresponding to packages on external media, and posting a
16359     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16360     * that we always have to post this message if status has been requested no
16361     * matter what.
16362     */
16363    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16364            final boolean reportStatus) {
16365        if (DEBUG_SD_INSTALL)
16366            Log.i(TAG, "unloading media packages");
16367        ArrayList<String> pkgList = new ArrayList<String>();
16368        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16369        final Set<AsecInstallArgs> keys = processCids.keySet();
16370        for (AsecInstallArgs args : keys) {
16371            String pkgName = args.getPackageName();
16372            if (DEBUG_SD_INSTALL)
16373                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16374            // Delete package internally
16375            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16376            synchronized (mInstallLock) {
16377                boolean res = deletePackageLI(pkgName, null, false, null, null,
16378                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16379                if (res) {
16380                    pkgList.add(pkgName);
16381                } else {
16382                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16383                    failedList.add(args);
16384                }
16385            }
16386        }
16387
16388        // reader
16389        synchronized (mPackages) {
16390            // We didn't update the settings after removing each package;
16391            // write them now for all packages.
16392            mSettings.writeLPr();
16393        }
16394
16395        // We have to absolutely send UPDATED_MEDIA_STATUS only
16396        // after confirming that all the receivers processed the ordered
16397        // broadcast when packages get disabled, force a gc to clean things up.
16398        // and unload all the containers.
16399        if (pkgList.size() > 0) {
16400            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16401                    new IIntentReceiver.Stub() {
16402                public void performReceive(Intent intent, int resultCode, String data,
16403                        Bundle extras, boolean ordered, boolean sticky,
16404                        int sendingUser) throws RemoteException {
16405                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16406                            reportStatus ? 1 : 0, 1, keys);
16407                    mHandler.sendMessage(msg);
16408                }
16409            });
16410        } else {
16411            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16412                    keys);
16413            mHandler.sendMessage(msg);
16414        }
16415    }
16416
16417    private void loadPrivatePackages(final VolumeInfo vol) {
16418        mHandler.post(new Runnable() {
16419            @Override
16420            public void run() {
16421                loadPrivatePackagesInner(vol);
16422            }
16423        });
16424    }
16425
16426    private void loadPrivatePackagesInner(VolumeInfo vol) {
16427        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16428        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16429
16430        final VersionInfo ver;
16431        final List<PackageSetting> packages;
16432        synchronized (mPackages) {
16433            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16434            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16435        }
16436
16437        for (PackageSetting ps : packages) {
16438            synchronized (mInstallLock) {
16439                final PackageParser.Package pkg;
16440                try {
16441                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16442                    loaded.add(pkg.applicationInfo);
16443                } catch (PackageManagerException e) {
16444                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16445                }
16446
16447                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16448                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16449                }
16450            }
16451        }
16452
16453        synchronized (mPackages) {
16454            int updateFlags = UPDATE_PERMISSIONS_ALL;
16455            if (ver.sdkVersion != mSdkVersion) {
16456                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16457                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16458                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16459            }
16460            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16461
16462            // Yay, everything is now upgraded
16463            ver.forceCurrent();
16464
16465            mSettings.writeLPr();
16466        }
16467
16468        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16469        sendResourcesChangedBroadcast(true, false, loaded, null);
16470    }
16471
16472    private void unloadPrivatePackages(final VolumeInfo vol) {
16473        mHandler.post(new Runnable() {
16474            @Override
16475            public void run() {
16476                unloadPrivatePackagesInner(vol);
16477            }
16478        });
16479    }
16480
16481    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16482        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16483        synchronized (mInstallLock) {
16484        synchronized (mPackages) {
16485            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16486            for (PackageSetting ps : packages) {
16487                if (ps.pkg == null) continue;
16488
16489                final ApplicationInfo info = ps.pkg.applicationInfo;
16490                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16491                if (deletePackageLI(ps.name, null, false, null, null,
16492                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16493                    unloaded.add(info);
16494                } else {
16495                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16496                }
16497            }
16498
16499            mSettings.writeLPr();
16500        }
16501        }
16502
16503        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16504        sendResourcesChangedBroadcast(false, false, unloaded, null);
16505    }
16506
16507    /**
16508     * Examine all users present on given mounted volume, and destroy data
16509     * belonging to users that are no longer valid, or whose user ID has been
16510     * recycled.
16511     */
16512    private void reconcileUsers(String volumeUuid) {
16513        final File[] files = FileUtils
16514                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16515        for (File file : files) {
16516            if (!file.isDirectory()) continue;
16517
16518            final int userId;
16519            final UserInfo info;
16520            try {
16521                userId = Integer.parseInt(file.getName());
16522                info = sUserManager.getUserInfo(userId);
16523            } catch (NumberFormatException e) {
16524                Slog.w(TAG, "Invalid user directory " + file);
16525                continue;
16526            }
16527
16528            boolean destroyUser = false;
16529            if (info == null) {
16530                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16531                        + " because no matching user was found");
16532                destroyUser = true;
16533            } else {
16534                try {
16535                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16536                } catch (IOException e) {
16537                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16538                            + " because we failed to enforce serial number: " + e);
16539                    destroyUser = true;
16540                }
16541            }
16542
16543            if (destroyUser) {
16544                synchronized (mInstallLock) {
16545                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16546                }
16547            }
16548        }
16549
16550        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16551        final UserManager um = mContext.getSystemService(UserManager.class);
16552        for (UserInfo user : um.getUsers()) {
16553            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16554            if (userDir.exists()) continue;
16555
16556            try {
16557                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16558                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16559            } catch (IOException e) {
16560                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16561            }
16562        }
16563    }
16564
16565    /**
16566     * Examine all apps present on given mounted volume, and destroy apps that
16567     * aren't expected, either due to uninstallation or reinstallation on
16568     * another volume.
16569     */
16570    private void reconcileApps(String volumeUuid) {
16571        final File[] files = FileUtils
16572                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16573        for (File file : files) {
16574            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16575                    && !PackageInstallerService.isStageName(file.getName());
16576            if (!isPackage) {
16577                // Ignore entries which are not packages
16578                continue;
16579            }
16580
16581            boolean destroyApp = false;
16582            String packageName = null;
16583            try {
16584                final PackageLite pkg = PackageParser.parsePackageLite(file,
16585                        PackageParser.PARSE_MUST_BE_APK);
16586                packageName = pkg.packageName;
16587
16588                synchronized (mPackages) {
16589                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16590                    if (ps == null) {
16591                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16592                                + volumeUuid + " because we found no install record");
16593                        destroyApp = true;
16594                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16595                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16596                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16597                        destroyApp = true;
16598                    }
16599                }
16600
16601            } catch (PackageParserException e) {
16602                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16603                destroyApp = true;
16604            }
16605
16606            if (destroyApp) {
16607                synchronized (mInstallLock) {
16608                    if (packageName != null) {
16609                        removeDataDirsLI(volumeUuid, packageName);
16610                    }
16611                    if (file.isDirectory()) {
16612                        mInstaller.rmPackageDir(file.getAbsolutePath());
16613                    } else {
16614                        file.delete();
16615                    }
16616                }
16617            }
16618        }
16619    }
16620
16621    private void unfreezePackage(String packageName) {
16622        synchronized (mPackages) {
16623            final PackageSetting ps = mSettings.mPackages.get(packageName);
16624            if (ps != null) {
16625                ps.frozen = false;
16626            }
16627        }
16628    }
16629
16630    @Override
16631    public int movePackage(final String packageName, final String volumeUuid) {
16632        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16633
16634        final int moveId = mNextMoveId.getAndIncrement();
16635        mHandler.post(new Runnable() {
16636            @Override
16637            public void run() {
16638                try {
16639                    movePackageInternal(packageName, volumeUuid, moveId);
16640                } catch (PackageManagerException e) {
16641                    Slog.w(TAG, "Failed to move " + packageName, e);
16642                    mMoveCallbacks.notifyStatusChanged(moveId,
16643                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16644                }
16645            }
16646        });
16647        return moveId;
16648    }
16649
16650    private void movePackageInternal(final String packageName, final String volumeUuid,
16651            final int moveId) throws PackageManagerException {
16652        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16653        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16654        final PackageManager pm = mContext.getPackageManager();
16655
16656        final boolean currentAsec;
16657        final String currentVolumeUuid;
16658        final File codeFile;
16659        final String installerPackageName;
16660        final String packageAbiOverride;
16661        final int appId;
16662        final String seinfo;
16663        final String label;
16664
16665        // reader
16666        synchronized (mPackages) {
16667            final PackageParser.Package pkg = mPackages.get(packageName);
16668            final PackageSetting ps = mSettings.mPackages.get(packageName);
16669            if (pkg == null || ps == null) {
16670                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16671            }
16672
16673            if (pkg.applicationInfo.isSystemApp()) {
16674                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16675                        "Cannot move system application");
16676            }
16677
16678            if (pkg.applicationInfo.isExternalAsec()) {
16679                currentAsec = true;
16680                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16681            } else if (pkg.applicationInfo.isForwardLocked()) {
16682                currentAsec = true;
16683                currentVolumeUuid = "forward_locked";
16684            } else {
16685                currentAsec = false;
16686                currentVolumeUuid = ps.volumeUuid;
16687
16688                final File probe = new File(pkg.codePath);
16689                final File probeOat = new File(probe, "oat");
16690                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16691                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16692                            "Move only supported for modern cluster style installs");
16693                }
16694            }
16695
16696            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16697                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16698                        "Package already moved to " + volumeUuid);
16699            }
16700
16701            if (ps.frozen) {
16702                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16703                        "Failed to move already frozen package");
16704            }
16705            ps.frozen = true;
16706
16707            codeFile = new File(pkg.codePath);
16708            installerPackageName = ps.installerPackageName;
16709            packageAbiOverride = ps.cpuAbiOverrideString;
16710            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16711            seinfo = pkg.applicationInfo.seinfo;
16712            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16713        }
16714
16715        // Now that we're guarded by frozen state, kill app during move
16716        final long token = Binder.clearCallingIdentity();
16717        try {
16718            killApplication(packageName, appId, "move pkg");
16719        } finally {
16720            Binder.restoreCallingIdentity(token);
16721        }
16722
16723        final Bundle extras = new Bundle();
16724        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16725        extras.putString(Intent.EXTRA_TITLE, label);
16726        mMoveCallbacks.notifyCreated(moveId, extras);
16727
16728        int installFlags;
16729        final boolean moveCompleteApp;
16730        final File measurePath;
16731
16732        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16733            installFlags = INSTALL_INTERNAL;
16734            moveCompleteApp = !currentAsec;
16735            measurePath = Environment.getDataAppDirectory(volumeUuid);
16736        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16737            installFlags = INSTALL_EXTERNAL;
16738            moveCompleteApp = false;
16739            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16740        } else {
16741            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16742            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16743                    || !volume.isMountedWritable()) {
16744                unfreezePackage(packageName);
16745                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16746                        "Move location not mounted private volume");
16747            }
16748
16749            Preconditions.checkState(!currentAsec);
16750
16751            installFlags = INSTALL_INTERNAL;
16752            moveCompleteApp = true;
16753            measurePath = Environment.getDataAppDirectory(volumeUuid);
16754        }
16755
16756        final PackageStats stats = new PackageStats(null, -1);
16757        synchronized (mInstaller) {
16758            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16759                unfreezePackage(packageName);
16760                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16761                        "Failed to measure package size");
16762            }
16763        }
16764
16765        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16766                + stats.dataSize);
16767
16768        final long startFreeBytes = measurePath.getFreeSpace();
16769        final long sizeBytes;
16770        if (moveCompleteApp) {
16771            sizeBytes = stats.codeSize + stats.dataSize;
16772        } else {
16773            sizeBytes = stats.codeSize;
16774        }
16775
16776        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16777            unfreezePackage(packageName);
16778            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16779                    "Not enough free space to move");
16780        }
16781
16782        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16783
16784        final CountDownLatch installedLatch = new CountDownLatch(1);
16785        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16786            @Override
16787            public void onUserActionRequired(Intent intent) throws RemoteException {
16788                throw new IllegalStateException();
16789            }
16790
16791            @Override
16792            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16793                    Bundle extras) throws RemoteException {
16794                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16795                        + PackageManager.installStatusToString(returnCode, msg));
16796
16797                installedLatch.countDown();
16798
16799                // Regardless of success or failure of the move operation,
16800                // always unfreeze the package
16801                unfreezePackage(packageName);
16802
16803                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16804                switch (status) {
16805                    case PackageInstaller.STATUS_SUCCESS:
16806                        mMoveCallbacks.notifyStatusChanged(moveId,
16807                                PackageManager.MOVE_SUCCEEDED);
16808                        break;
16809                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16810                        mMoveCallbacks.notifyStatusChanged(moveId,
16811                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16812                        break;
16813                    default:
16814                        mMoveCallbacks.notifyStatusChanged(moveId,
16815                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16816                        break;
16817                }
16818            }
16819        };
16820
16821        final MoveInfo move;
16822        if (moveCompleteApp) {
16823            // Kick off a thread to report progress estimates
16824            new Thread() {
16825                @Override
16826                public void run() {
16827                    while (true) {
16828                        try {
16829                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16830                                break;
16831                            }
16832                        } catch (InterruptedException ignored) {
16833                        }
16834
16835                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16836                        final int progress = 10 + (int) MathUtils.constrain(
16837                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16838                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16839                    }
16840                }
16841            }.start();
16842
16843            final String dataAppName = codeFile.getName();
16844            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16845                    dataAppName, appId, seinfo);
16846        } else {
16847            move = null;
16848        }
16849
16850        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16851
16852        final Message msg = mHandler.obtainMessage(INIT_COPY);
16853        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16854        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16855                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16856        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16857        msg.obj = params;
16858
16859        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16860                System.identityHashCode(msg.obj));
16861        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16862                System.identityHashCode(msg.obj));
16863
16864        mHandler.sendMessage(msg);
16865    }
16866
16867    @Override
16868    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16869        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16870
16871        final int realMoveId = mNextMoveId.getAndIncrement();
16872        final Bundle extras = new Bundle();
16873        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16874        mMoveCallbacks.notifyCreated(realMoveId, extras);
16875
16876        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16877            @Override
16878            public void onCreated(int moveId, Bundle extras) {
16879                // Ignored
16880            }
16881
16882            @Override
16883            public void onStatusChanged(int moveId, int status, long estMillis) {
16884                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16885            }
16886        };
16887
16888        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16889        storage.setPrimaryStorageUuid(volumeUuid, callback);
16890        return realMoveId;
16891    }
16892
16893    @Override
16894    public int getMoveStatus(int moveId) {
16895        mContext.enforceCallingOrSelfPermission(
16896                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16897        return mMoveCallbacks.mLastStatus.get(moveId);
16898    }
16899
16900    @Override
16901    public void registerMoveCallback(IPackageMoveObserver callback) {
16902        mContext.enforceCallingOrSelfPermission(
16903                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16904        mMoveCallbacks.register(callback);
16905    }
16906
16907    @Override
16908    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16909        mContext.enforceCallingOrSelfPermission(
16910                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16911        mMoveCallbacks.unregister(callback);
16912    }
16913
16914    @Override
16915    public boolean setInstallLocation(int loc) {
16916        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16917                null);
16918        if (getInstallLocation() == loc) {
16919            return true;
16920        }
16921        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16922                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16923            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16924                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16925            return true;
16926        }
16927        return false;
16928   }
16929
16930    @Override
16931    public int getInstallLocation() {
16932        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16933                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16934                PackageHelper.APP_INSTALL_AUTO);
16935    }
16936
16937    /** Called by UserManagerService */
16938    void cleanUpUser(UserManagerService userManager, int userHandle) {
16939        synchronized (mPackages) {
16940            mDirtyUsers.remove(userHandle);
16941            mUserNeedsBadging.delete(userHandle);
16942            mSettings.removeUserLPw(userHandle);
16943            mPendingBroadcasts.remove(userHandle);
16944            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16945        }
16946        synchronized (mInstallLock) {
16947            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16948            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16949                final String volumeUuid = vol.getFsUuid();
16950                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16951                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16952            }
16953            synchronized (mPackages) {
16954                removeUnusedPackagesLILPw(userManager, userHandle);
16955            }
16956        }
16957    }
16958
16959    /**
16960     * We're removing userHandle and would like to remove any downloaded packages
16961     * that are no longer in use by any other user.
16962     * @param userHandle the user being removed
16963     */
16964    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16965        final boolean DEBUG_CLEAN_APKS = false;
16966        int [] users = userManager.getUserIds();
16967        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16968        while (psit.hasNext()) {
16969            PackageSetting ps = psit.next();
16970            if (ps.pkg == null) {
16971                continue;
16972            }
16973            final String packageName = ps.pkg.packageName;
16974            // Skip over if system app
16975            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16976                continue;
16977            }
16978            if (DEBUG_CLEAN_APKS) {
16979                Slog.i(TAG, "Checking package " + packageName);
16980            }
16981            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16982            if (keep) {
16983                if (DEBUG_CLEAN_APKS) {
16984                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16985                }
16986            } else {
16987                for (int i = 0; i < users.length; i++) {
16988                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16989                        keep = true;
16990                        if (DEBUG_CLEAN_APKS) {
16991                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
16992                                    + users[i]);
16993                        }
16994                        break;
16995                    }
16996                }
16997            }
16998            if (!keep) {
16999                if (DEBUG_CLEAN_APKS) {
17000                    Slog.i(TAG, "  Removing package " + packageName);
17001                }
17002                mHandler.post(new Runnable() {
17003                    public void run() {
17004                        deletePackageX(packageName, userHandle, 0);
17005                    } //end run
17006                });
17007            }
17008        }
17009    }
17010
17011    /** Called by UserManagerService */
17012    void createNewUser(int userHandle) {
17013        synchronized (mInstallLock) {
17014            mInstaller.createUserConfig(userHandle);
17015            mSettings.createNewUserLI(this, mInstaller, userHandle);
17016        }
17017        synchronized (mPackages) {
17018            applyFactoryDefaultBrowserLPw(userHandle);
17019            primeDomainVerificationsLPw(userHandle);
17020        }
17021    }
17022
17023    void newUserCreated(final int userHandle) {
17024        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17025        // If permission review for legacy apps is required, we represent
17026        // dagerous permissions for such apps as always granted runtime
17027        // permissions to keep per user flag state whether review is needed.
17028        // Hence, if a new user is added we have to propagate dangerous
17029        // permission grants for these legacy apps.
17030        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17031            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17032                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17033        }
17034    }
17035
17036    @Override
17037    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17038        mContext.enforceCallingOrSelfPermission(
17039                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17040                "Only package verification agents can read the verifier device identity");
17041
17042        synchronized (mPackages) {
17043            return mSettings.getVerifierDeviceIdentityLPw();
17044        }
17045    }
17046
17047    @Override
17048    public void setPermissionEnforced(String permission, boolean enforced) {
17049        // TODO: Now that we no longer change GID for storage, this should to away.
17050        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17051                "setPermissionEnforced");
17052        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17053            synchronized (mPackages) {
17054                if (mSettings.mReadExternalStorageEnforced == null
17055                        || mSettings.mReadExternalStorageEnforced != enforced) {
17056                    mSettings.mReadExternalStorageEnforced = enforced;
17057                    mSettings.writeLPr();
17058                }
17059            }
17060            // kill any non-foreground processes so we restart them and
17061            // grant/revoke the GID.
17062            final IActivityManager am = ActivityManagerNative.getDefault();
17063            if (am != null) {
17064                final long token = Binder.clearCallingIdentity();
17065                try {
17066                    am.killProcessesBelowForeground("setPermissionEnforcement");
17067                } catch (RemoteException e) {
17068                } finally {
17069                    Binder.restoreCallingIdentity(token);
17070                }
17071            }
17072        } else {
17073            throw new IllegalArgumentException("No selective enforcement for " + permission);
17074        }
17075    }
17076
17077    @Override
17078    @Deprecated
17079    public boolean isPermissionEnforced(String permission) {
17080        return true;
17081    }
17082
17083    @Override
17084    public boolean isStorageLow() {
17085        final long token = Binder.clearCallingIdentity();
17086        try {
17087            final DeviceStorageMonitorInternal
17088                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17089            if (dsm != null) {
17090                return dsm.isMemoryLow();
17091            } else {
17092                return false;
17093            }
17094        } finally {
17095            Binder.restoreCallingIdentity(token);
17096        }
17097    }
17098
17099    @Override
17100    public IPackageInstaller getPackageInstaller() {
17101        return mInstallerService;
17102    }
17103
17104    private boolean userNeedsBadging(int userId) {
17105        int index = mUserNeedsBadging.indexOfKey(userId);
17106        if (index < 0) {
17107            final UserInfo userInfo;
17108            final long token = Binder.clearCallingIdentity();
17109            try {
17110                userInfo = sUserManager.getUserInfo(userId);
17111            } finally {
17112                Binder.restoreCallingIdentity(token);
17113            }
17114            final boolean b;
17115            if (userInfo != null && userInfo.isManagedProfile()) {
17116                b = true;
17117            } else {
17118                b = false;
17119            }
17120            mUserNeedsBadging.put(userId, b);
17121            return b;
17122        }
17123        return mUserNeedsBadging.valueAt(index);
17124    }
17125
17126    @Override
17127    public KeySet getKeySetByAlias(String packageName, String alias) {
17128        if (packageName == null || alias == null) {
17129            return null;
17130        }
17131        synchronized(mPackages) {
17132            final PackageParser.Package pkg = mPackages.get(packageName);
17133            if (pkg == null) {
17134                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17135                throw new IllegalArgumentException("Unknown package: " + packageName);
17136            }
17137            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17138            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17139        }
17140    }
17141
17142    @Override
17143    public KeySet getSigningKeySet(String packageName) {
17144        if (packageName == null) {
17145            return null;
17146        }
17147        synchronized(mPackages) {
17148            final PackageParser.Package pkg = mPackages.get(packageName);
17149            if (pkg == null) {
17150                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17151                throw new IllegalArgumentException("Unknown package: " + packageName);
17152            }
17153            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17154                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17155                throw new SecurityException("May not access signing KeySet of other apps.");
17156            }
17157            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17158            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17159        }
17160    }
17161
17162    @Override
17163    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17164        if (packageName == null || ks == null) {
17165            return false;
17166        }
17167        synchronized(mPackages) {
17168            final PackageParser.Package pkg = mPackages.get(packageName);
17169            if (pkg == null) {
17170                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17171                throw new IllegalArgumentException("Unknown package: " + packageName);
17172            }
17173            IBinder ksh = ks.getToken();
17174            if (ksh instanceof KeySetHandle) {
17175                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17176                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17177            }
17178            return false;
17179        }
17180    }
17181
17182    @Override
17183    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17184        if (packageName == null || ks == null) {
17185            return false;
17186        }
17187        synchronized(mPackages) {
17188            final PackageParser.Package pkg = mPackages.get(packageName);
17189            if (pkg == null) {
17190                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17191                throw new IllegalArgumentException("Unknown package: " + packageName);
17192            }
17193            IBinder ksh = ks.getToken();
17194            if (ksh instanceof KeySetHandle) {
17195                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17196                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17197            }
17198            return false;
17199        }
17200    }
17201
17202    private void deletePackageIfUnusedLPr(final String packageName) {
17203        PackageSetting ps = mSettings.mPackages.get(packageName);
17204        if (ps == null) {
17205            return;
17206        }
17207        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17208            // TODO Implement atomic delete if package is unused
17209            // It is currently possible that the package will be deleted even if it is installed
17210            // after this method returns.
17211            mHandler.post(new Runnable() {
17212                public void run() {
17213                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17214                }
17215            });
17216        }
17217    }
17218
17219    /**
17220     * Check and throw if the given before/after packages would be considered a
17221     * downgrade.
17222     */
17223    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17224            throws PackageManagerException {
17225        if (after.versionCode < before.mVersionCode) {
17226            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17227                    "Update version code " + after.versionCode + " is older than current "
17228                    + before.mVersionCode);
17229        } else if (after.versionCode == before.mVersionCode) {
17230            if (after.baseRevisionCode < before.baseRevisionCode) {
17231                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17232                        "Update base revision code " + after.baseRevisionCode
17233                        + " is older than current " + before.baseRevisionCode);
17234            }
17235
17236            if (!ArrayUtils.isEmpty(after.splitNames)) {
17237                for (int i = 0; i < after.splitNames.length; i++) {
17238                    final String splitName = after.splitNames[i];
17239                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17240                    if (j != -1) {
17241                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17242                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17243                                    "Update split " + splitName + " revision code "
17244                                    + after.splitRevisionCodes[i] + " is older than current "
17245                                    + before.splitRevisionCodes[j]);
17246                        }
17247                    }
17248                }
17249            }
17250        }
17251    }
17252
17253    private static class MoveCallbacks extends Handler {
17254        private static final int MSG_CREATED = 1;
17255        private static final int MSG_STATUS_CHANGED = 2;
17256
17257        private final RemoteCallbackList<IPackageMoveObserver>
17258                mCallbacks = new RemoteCallbackList<>();
17259
17260        private final SparseIntArray mLastStatus = new SparseIntArray();
17261
17262        public MoveCallbacks(Looper looper) {
17263            super(looper);
17264        }
17265
17266        public void register(IPackageMoveObserver callback) {
17267            mCallbacks.register(callback);
17268        }
17269
17270        public void unregister(IPackageMoveObserver callback) {
17271            mCallbacks.unregister(callback);
17272        }
17273
17274        @Override
17275        public void handleMessage(Message msg) {
17276            final SomeArgs args = (SomeArgs) msg.obj;
17277            final int n = mCallbacks.beginBroadcast();
17278            for (int i = 0; i < n; i++) {
17279                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17280                try {
17281                    invokeCallback(callback, msg.what, args);
17282                } catch (RemoteException ignored) {
17283                }
17284            }
17285            mCallbacks.finishBroadcast();
17286            args.recycle();
17287        }
17288
17289        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17290                throws RemoteException {
17291            switch (what) {
17292                case MSG_CREATED: {
17293                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17294                    break;
17295                }
17296                case MSG_STATUS_CHANGED: {
17297                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17298                    break;
17299                }
17300            }
17301        }
17302
17303        private void notifyCreated(int moveId, Bundle extras) {
17304            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17305
17306            final SomeArgs args = SomeArgs.obtain();
17307            args.argi1 = moveId;
17308            args.arg2 = extras;
17309            obtainMessage(MSG_CREATED, args).sendToTarget();
17310        }
17311
17312        private void notifyStatusChanged(int moveId, int status) {
17313            notifyStatusChanged(moveId, status, -1);
17314        }
17315
17316        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17317            Slog.v(TAG, "Move " + moveId + " status " + status);
17318
17319            final SomeArgs args = SomeArgs.obtain();
17320            args.argi1 = moveId;
17321            args.argi2 = status;
17322            args.arg3 = estMillis;
17323            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17324
17325            synchronized (mLastStatus) {
17326                mLastStatus.put(moveId, status);
17327            }
17328        }
17329    }
17330
17331    private final class OnPermissionChangeListeners extends Handler {
17332        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17333
17334        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17335                new RemoteCallbackList<>();
17336
17337        public OnPermissionChangeListeners(Looper looper) {
17338            super(looper);
17339        }
17340
17341        @Override
17342        public void handleMessage(Message msg) {
17343            switch (msg.what) {
17344                case MSG_ON_PERMISSIONS_CHANGED: {
17345                    final int uid = msg.arg1;
17346                    handleOnPermissionsChanged(uid);
17347                } break;
17348            }
17349        }
17350
17351        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17352            mPermissionListeners.register(listener);
17353
17354        }
17355
17356        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17357            mPermissionListeners.unregister(listener);
17358        }
17359
17360        public void onPermissionsChanged(int uid) {
17361            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17362                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17363            }
17364        }
17365
17366        private void handleOnPermissionsChanged(int uid) {
17367            final int count = mPermissionListeners.beginBroadcast();
17368            try {
17369                for (int i = 0; i < count; i++) {
17370                    IOnPermissionsChangeListener callback = mPermissionListeners
17371                            .getBroadcastItem(i);
17372                    try {
17373                        callback.onPermissionsChanged(uid);
17374                    } catch (RemoteException e) {
17375                        Log.e(TAG, "Permission listener is dead", e);
17376                    }
17377                }
17378            } finally {
17379                mPermissionListeners.finishBroadcast();
17380            }
17381        }
17382    }
17383
17384    private class PackageManagerInternalImpl extends PackageManagerInternal {
17385        @Override
17386        public void setLocationPackagesProvider(PackagesProvider provider) {
17387            synchronized (mPackages) {
17388                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17389            }
17390        }
17391
17392        @Override
17393        public void setImePackagesProvider(PackagesProvider provider) {
17394            synchronized (mPackages) {
17395                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17396            }
17397        }
17398
17399        @Override
17400        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17401            synchronized (mPackages) {
17402                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17403            }
17404        }
17405
17406        @Override
17407        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17408            synchronized (mPackages) {
17409                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17410            }
17411        }
17412
17413        @Override
17414        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17415            synchronized (mPackages) {
17416                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17417            }
17418        }
17419
17420        @Override
17421        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17422            synchronized (mPackages) {
17423                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17424            }
17425        }
17426
17427        @Override
17428        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17429            synchronized (mPackages) {
17430                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17431            }
17432        }
17433
17434        @Override
17435        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17436            synchronized (mPackages) {
17437                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17438                        packageName, userId);
17439            }
17440        }
17441
17442        @Override
17443        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17444            synchronized (mPackages) {
17445                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17446                        packageName, userId);
17447            }
17448        }
17449
17450        @Override
17451        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17452            synchronized (mPackages) {
17453                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17454                        packageName, userId);
17455            }
17456        }
17457
17458        @Override
17459        public void setKeepUninstalledPackages(final List<String> packageList) {
17460            Preconditions.checkNotNull(packageList);
17461            List<String> removedFromList = null;
17462            synchronized (mPackages) {
17463                if (mKeepUninstalledPackages != null) {
17464                    final int packagesCount = mKeepUninstalledPackages.size();
17465                    for (int i = 0; i < packagesCount; i++) {
17466                        String oldPackage = mKeepUninstalledPackages.get(i);
17467                        if (packageList != null && packageList.contains(oldPackage)) {
17468                            continue;
17469                        }
17470                        if (removedFromList == null) {
17471                            removedFromList = new ArrayList<>();
17472                        }
17473                        removedFromList.add(oldPackage);
17474                    }
17475                }
17476                mKeepUninstalledPackages = new ArrayList<>(packageList);
17477                if (removedFromList != null) {
17478                    final int removedCount = removedFromList.size();
17479                    for (int i = 0; i < removedCount; i++) {
17480                        deletePackageIfUnusedLPr(removedFromList.get(i));
17481                    }
17482                }
17483            }
17484        }
17485
17486        @Override
17487        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17488            synchronized (mPackages) {
17489                // If we do not support permission review, done.
17490                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17491                    return false;
17492                }
17493
17494                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17495                if (packageSetting == null) {
17496                    return false;
17497                }
17498
17499                // Permission review applies only to apps not supporting the new permission model.
17500                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17501                    return false;
17502                }
17503
17504                // Legacy apps have the permission and get user consent on launch.
17505                PermissionsState permissionsState = packageSetting.getPermissionsState();
17506                return permissionsState.isPermissionReviewRequired(userId);
17507            }
17508        }
17509    }
17510
17511    @Override
17512    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17513        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17514        synchronized (mPackages) {
17515            final long identity = Binder.clearCallingIdentity();
17516            try {
17517                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17518                        packageNames, userId);
17519            } finally {
17520                Binder.restoreCallingIdentity(identity);
17521            }
17522        }
17523    }
17524
17525    private static void enforceSystemOrPhoneCaller(String tag) {
17526        int callingUid = Binder.getCallingUid();
17527        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17528            throw new SecurityException(
17529                    "Cannot call " + tag + " from UID " + callingUid);
17530        }
17531    }
17532}
17533