PackageManagerService.java revision 39a275b3980b5ea75e060da540229b95a47333f7
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_DEXOPT;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
64import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
65import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
66import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
67import static android.content.pm.PackageManager.PERMISSION_DENIED;
68import static android.content.pm.PackageManager.PERMISSION_GRANTED;
69import static android.content.pm.PackageParser.isApkFile;
70import static android.os.Process.PACKAGE_INFO_GID;
71import static android.os.Process.SYSTEM_UID;
72import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
73import static android.system.OsConstants.O_CREAT;
74import static android.system.OsConstants.O_RDWR;
75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
76import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
77import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
78import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
79import static com.android.internal.util.ArrayUtils.appendInt;
80import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
81import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
83import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
84import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
85import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
88import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
89
90import android.Manifest;
91import android.app.ActivityManager;
92import android.app.ActivityManagerNative;
93import android.app.AppGlobals;
94import android.app.IActivityManager;
95import android.app.admin.IDevicePolicyManager;
96import android.app.backup.IBackupManager;
97import android.app.usage.UsageStats;
98import android.app.usage.UsageStatsManager;
99import android.content.BroadcastReceiver;
100import android.content.ComponentName;
101import android.content.Context;
102import android.content.IIntentReceiver;
103import android.content.Intent;
104import android.content.IntentFilter;
105import android.content.IntentSender;
106import android.content.IntentSender.SendIntentException;
107import android.content.ServiceConnection;
108import android.content.pm.ActivityInfo;
109import android.content.pm.ApplicationInfo;
110import android.content.pm.AppsQueryHelper;
111import android.content.pm.FeatureInfo;
112import android.content.pm.IOnPermissionsChangeListener;
113import android.content.pm.IPackageDataObserver;
114import android.content.pm.IPackageDeleteObserver;
115import android.content.pm.IPackageDeleteObserver2;
116import android.content.pm.IPackageInstallObserver2;
117import android.content.pm.IPackageInstaller;
118import android.content.pm.IPackageManager;
119import android.content.pm.IPackageMoveObserver;
120import android.content.pm.IPackageStatsObserver;
121import android.content.pm.InstrumentationInfo;
122import android.content.pm.IntentFilterVerificationInfo;
123import android.content.pm.KeySet;
124import android.content.pm.ManifestDigest;
125import android.content.pm.PackageCleanItem;
126import android.content.pm.PackageInfo;
127import android.content.pm.PackageInfoLite;
128import android.content.pm.PackageInstaller;
129import android.content.pm.PackageManager;
130import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
131import android.content.pm.PackageManagerInternal;
132import android.content.pm.PackageParser;
133import android.content.pm.PackageParser.ActivityIntentInfo;
134import android.content.pm.PackageParser.PackageLite;
135import android.content.pm.PackageParser.PackageParserException;
136import android.content.pm.PackageStats;
137import android.content.pm.PackageUserState;
138import android.content.pm.ParceledListSlice;
139import android.content.pm.PermissionGroupInfo;
140import android.content.pm.PermissionInfo;
141import android.content.pm.ProviderInfo;
142import android.content.pm.ResolveInfo;
143import android.content.pm.ServiceInfo;
144import android.content.pm.Signature;
145import android.content.pm.UserInfo;
146import android.content.pm.VerificationParams;
147import android.content.pm.VerifierDeviceIdentity;
148import android.content.pm.VerifierInfo;
149import android.content.res.Resources;
150import android.hardware.display.DisplayManager;
151import android.net.Uri;
152import android.os.Debug;
153import android.os.Binder;
154import android.os.Build;
155import android.os.Bundle;
156import android.os.Environment;
157import android.os.Environment.UserEnvironment;
158import android.os.FileUtils;
159import android.os.Handler;
160import android.os.IBinder;
161import android.os.Looper;
162import android.os.Message;
163import android.os.Parcel;
164import android.os.ParcelFileDescriptor;
165import android.os.Process;
166import android.os.RemoteCallbackList;
167import android.os.RemoteException;
168import android.os.ResultReceiver;
169import android.os.SELinux;
170import android.os.ServiceManager;
171import android.os.SystemClock;
172import android.os.SystemProperties;
173import android.os.Trace;
174import android.os.UserHandle;
175import android.os.UserManager;
176import android.os.storage.IMountService;
177import android.os.storage.MountServiceInternal;
178import android.os.storage.StorageEventListener;
179import android.os.storage.StorageManager;
180import android.os.storage.VolumeInfo;
181import android.os.storage.VolumeRecord;
182import android.security.KeyStore;
183import android.security.SystemKeyStore;
184import android.system.ErrnoException;
185import android.system.Os;
186import android.system.StructStat;
187import android.text.TextUtils;
188import android.text.format.DateUtils;
189import android.util.ArrayMap;
190import android.util.ArraySet;
191import android.util.AtomicFile;
192import android.util.DisplayMetrics;
193import android.util.EventLog;
194import android.util.ExceptionUtils;
195import android.util.Log;
196import android.util.LogPrinter;
197import android.util.MathUtils;
198import android.util.PrintStreamPrinter;
199import android.util.Slog;
200import android.util.SparseArray;
201import android.util.SparseBooleanArray;
202import android.util.SparseIntArray;
203import android.util.Xml;
204import android.view.Display;
205
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.annotations.GuardedBy;
214import com.android.internal.app.EphemeralResolveInfo;
215import com.android.internal.app.IMediaContainerService;
216import com.android.internal.app.ResolverActivity;
217import com.android.internal.content.NativeLibraryHelper;
218import com.android.internal.content.PackageHelper;
219import com.android.internal.os.IParcelFileDescriptorFactory;
220import com.android.internal.os.SomeArgs;
221import com.android.internal.os.Zygote;
222import com.android.internal.util.ArrayUtils;
223import com.android.internal.util.FastPrintWriter;
224import com.android.internal.util.FastXmlSerializer;
225import com.android.internal.util.IndentingPrintWriter;
226import com.android.internal.util.Preconditions;
227import com.android.server.EventLogTags;
228import com.android.server.FgThread;
229import com.android.server.IntentResolver;
230import com.android.server.LocalServices;
231import com.android.server.ServiceThread;
232import com.android.server.SystemConfig;
233import com.android.server.Watchdog;
234import com.android.server.pm.PermissionsState.PermissionState;
235import com.android.server.pm.Settings.DatabaseVersion;
236import com.android.server.pm.Settings.VersionInfo;
237import com.android.server.storage.DeviceStorageMonitorInternal;
238
239import org.xmlpull.v1.XmlPullParser;
240import org.xmlpull.v1.XmlPullParserException;
241import org.xmlpull.v1.XmlSerializer;
242
243import java.io.BufferedInputStream;
244import java.io.BufferedOutputStream;
245import java.io.BufferedReader;
246import java.io.ByteArrayInputStream;
247import java.io.ByteArrayOutputStream;
248import java.io.File;
249import java.io.FileDescriptor;
250import java.io.FileNotFoundException;
251import java.io.FileOutputStream;
252import java.io.FileReader;
253import java.io.FilenameFilter;
254import java.io.IOException;
255import java.io.InputStream;
256import java.io.PrintWriter;
257import java.nio.charset.StandardCharsets;
258import java.security.MessageDigest;
259import java.security.NoSuchAlgorithmException;
260import java.security.PublicKey;
261import java.security.cert.CertificateEncodingException;
262import java.security.cert.CertificateException;
263import java.text.SimpleDateFormat;
264import java.util.ArrayList;
265import java.util.Arrays;
266import java.util.Collection;
267import java.util.Collections;
268import java.util.Comparator;
269import java.util.Date;
270import java.util.Iterator;
271import java.util.List;
272import java.util.Map;
273import java.util.Objects;
274import java.util.Set;
275import java.util.concurrent.CountDownLatch;
276import java.util.concurrent.TimeUnit;
277import java.util.concurrent.atomic.AtomicBoolean;
278import java.util.concurrent.atomic.AtomicInteger;
279import java.util.concurrent.atomic.AtomicLong;
280
281/**
282 * Keep track of all those .apks everywhere.
283 *
284 * This is very central to the platform's security; please run the unit
285 * tests whenever making modifications here:
286 *
287runtest -c android.content.pm.PackageManagerTests frameworks-core
288 *
289 * {@hide}
290 */
291public class PackageManagerService extends IPackageManager.Stub {
292    static final String TAG = "PackageManager";
293    static final boolean DEBUG_SETTINGS = false;
294    static final boolean DEBUG_PREFERRED = false;
295    static final boolean DEBUG_UPGRADE = false;
296    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
297    private static final boolean DEBUG_BACKUP = false;
298    private static final boolean DEBUG_INSTALL = false;
299    private static final boolean DEBUG_REMOVE = false;
300    private static final boolean DEBUG_BROADCASTS = false;
301    private static final boolean DEBUG_SHOW_INFO = false;
302    private static final boolean DEBUG_PACKAGE_INFO = false;
303    private static final boolean DEBUG_INTENT_MATCHING = false;
304    private static final boolean DEBUG_PACKAGE_SCANNING = false;
305    private static final boolean DEBUG_VERIFY = false;
306    private static final boolean DEBUG_DEXOPT = false;
307    private static final boolean DEBUG_ABI_SELECTION = false;
308    private static final boolean DEBUG_EPHEMERAL = false;
309
310    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
311
312    private static final int RADIO_UID = Process.PHONE_UID;
313    private static final int LOG_UID = Process.LOG_UID;
314    private static final int NFC_UID = Process.NFC_UID;
315    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
316    private static final int SHELL_UID = Process.SHELL_UID;
317
318    // Cap the size of permission trees that 3rd party apps can define
319    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
320
321    // Suffix used during package installation when copying/moving
322    // package apks to install directory.
323    private static final String INSTALL_PACKAGE_SUFFIX = "-";
324
325    static final int SCAN_NO_DEX = 1<<1;
326    static final int SCAN_FORCE_DEX = 1<<2;
327    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
328    static final int SCAN_NEW_INSTALL = 1<<4;
329    static final int SCAN_NO_PATHS = 1<<5;
330    static final int SCAN_UPDATE_TIME = 1<<6;
331    static final int SCAN_DEFER_DEX = 1<<7;
332    static final int SCAN_BOOTING = 1<<8;
333    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
334    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
335    static final int SCAN_REPLACING = 1<<11;
336    static final int SCAN_REQUIRE_KNOWN = 1<<12;
337    static final int SCAN_MOVE = 1<<13;
338    static final int SCAN_INITIAL = 1<<14;
339
340    static final int REMOVE_CHATTY = 1<<16;
341
342    private static final int[] EMPTY_INT_ARRAY = new int[0];
343
344    /**
345     * Timeout (in milliseconds) after which the watchdog should declare that
346     * our handler thread is wedged.  The usual default for such things is one
347     * minute but we sometimes do very lengthy I/O operations on this thread,
348     * such as installing multi-gigabyte applications, so ours needs to be longer.
349     */
350    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
351
352    /**
353     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
354     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
355     * settings entry if available, otherwise we use the hardcoded default.  If it's been
356     * more than this long since the last fstrim, we force one during the boot sequence.
357     *
358     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
359     * one gets run at the next available charging+idle time.  This final mandatory
360     * no-fstrim check kicks in only of the other scheduling criteria is never met.
361     */
362    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
363
364    /**
365     * Whether verification is enabled by default.
366     */
367    private static final boolean DEFAULT_VERIFY_ENABLE = true;
368
369    /**
370     * The default maximum time to wait for the verification agent to return in
371     * milliseconds.
372     */
373    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
374
375    /**
376     * The default response for package verification timeout.
377     *
378     * This can be either PackageManager.VERIFICATION_ALLOW or
379     * PackageManager.VERIFICATION_REJECT.
380     */
381    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
382
383    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
384
385    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
386            DEFAULT_CONTAINER_PACKAGE,
387            "com.android.defcontainer.DefaultContainerService");
388
389    private static final String KILL_APP_REASON_GIDS_CHANGED =
390            "permission grant or revoke changed gids";
391
392    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
393            "permissions revoked";
394
395    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
396
397    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
398
399    /** Permission grant: not grant the permission. */
400    private static final int GRANT_DENIED = 1;
401
402    /** Permission grant: grant the permission as an install permission. */
403    private static final int GRANT_INSTALL = 2;
404
405    /** Permission grant: grant the permission as a runtime one. */
406    private static final int GRANT_RUNTIME = 3;
407
408    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
409    private static final int GRANT_UPGRADE = 4;
410
411    /** Canonical intent used to identify what counts as a "web browser" app */
412    private static final Intent sBrowserIntent;
413    static {
414        sBrowserIntent = new Intent();
415        sBrowserIntent.setAction(Intent.ACTION_VIEW);
416        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
417        sBrowserIntent.setData(Uri.parse("http:"));
418    }
419
420    final ServiceThread mHandlerThread;
421
422    final PackageHandler mHandler;
423
424    /**
425     * Messages for {@link #mHandler} that need to wait for system ready before
426     * being dispatched.
427     */
428    private ArrayList<Message> mPostSystemReadyMessages;
429
430    final int mSdkVersion = Build.VERSION.SDK_INT;
431
432    final Context mContext;
433    final boolean mFactoryTest;
434    final boolean mOnlyCore;
435    final DisplayMetrics mMetrics;
436    final int mDefParseFlags;
437    final String[] mSeparateProcesses;
438    final boolean mIsUpgrade;
439
440    // This is where all application persistent data goes.
441    final File mAppDataDir;
442
443    // This is where all application persistent data goes for secondary users.
444    final File mUserAppDataDir;
445
446    /** The location for ASEC container files on internal storage. */
447    final String mAsecInternalPath;
448
449    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
450    // LOCK HELD.  Can be called with mInstallLock held.
451    @GuardedBy("mInstallLock")
452    final Installer mInstaller;
453
454    /** Directory where installed third-party apps stored */
455    final File mAppInstallDir;
456    final File mEphemeralInstallDir;
457
458    /**
459     * Directory to which applications installed internally have their
460     * 32 bit native libraries copied.
461     */
462    private File mAppLib32InstallDir;
463
464    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
465    // apps.
466    final File mDrmAppPrivateInstallDir;
467
468    // ----------------------------------------------------------------
469
470    // Lock for state used when installing and doing other long running
471    // operations.  Methods that must be called with this lock held have
472    // the suffix "LI".
473    final Object mInstallLock = new Object();
474
475    // ----------------------------------------------------------------
476
477    // Keys are String (package name), values are Package.  This also serves
478    // as the lock for the global state.  Methods that must be called with
479    // this lock held have the prefix "LP".
480    @GuardedBy("mPackages")
481    final ArrayMap<String, PackageParser.Package> mPackages =
482            new ArrayMap<String, PackageParser.Package>();
483
484    // Tracks available target package names -> overlay package paths.
485    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
486        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
487
488    /**
489     * Tracks new system packages [received in an OTA] that we expect to
490     * find updated user-installed versions. Keys are package name, values
491     * are package location.
492     */
493    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
494
495    /**
496     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
497     */
498    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
499    /**
500     * Whether or not system app permissions should be promoted from install to runtime.
501     */
502    boolean mPromoteSystemApps;
503
504    final Settings mSettings;
505    boolean mRestoredSettings;
506
507    // System configuration read by SystemConfig.
508    final int[] mGlobalGids;
509    final SparseArray<ArraySet<String>> mSystemPermissions;
510    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
511
512    // If mac_permissions.xml was found for seinfo labeling.
513    boolean mFoundPolicyFile;
514
515    // If a recursive restorecon of /data/data/<pkg> is needed.
516    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
517
518    public static final class SharedLibraryEntry {
519        public final String path;
520        public final String apk;
521
522        SharedLibraryEntry(String _path, String _apk) {
523            path = _path;
524            apk = _apk;
525        }
526    }
527
528    // Currently known shared libraries.
529    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
530            new ArrayMap<String, SharedLibraryEntry>();
531
532    // All available activities, for your resolving pleasure.
533    final ActivityIntentResolver mActivities =
534            new ActivityIntentResolver();
535
536    // All available receivers, for your resolving pleasure.
537    final ActivityIntentResolver mReceivers =
538            new ActivityIntentResolver();
539
540    // All available services, for your resolving pleasure.
541    final ServiceIntentResolver mServices = new ServiceIntentResolver();
542
543    // All available providers, for your resolving pleasure.
544    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
545
546    // Mapping from provider base names (first directory in content URI codePath)
547    // to the provider information.
548    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
549            new ArrayMap<String, PackageParser.Provider>();
550
551    // Mapping from instrumentation class names to info about them.
552    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
553            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
554
555    // Mapping from permission names to info about them.
556    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
557            new ArrayMap<String, PackageParser.PermissionGroup>();
558
559    // Packages whose data we have transfered into another package, thus
560    // should no longer exist.
561    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
562
563    // Broadcast actions that are only available to the system.
564    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
565
566    /** List of packages waiting for verification. */
567    final SparseArray<PackageVerificationState> mPendingVerification
568            = new SparseArray<PackageVerificationState>();
569
570    /** Set of packages associated with each app op permission. */
571    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
572
573    final PackageInstallerService mInstallerService;
574
575    private final PackageDexOptimizer mPackageDexOptimizer;
576
577    private AtomicInteger mNextMoveId = new AtomicInteger();
578    private final MoveCallbacks mMoveCallbacks;
579
580    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
581
582    // Cache of users who need badging.
583    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
584
585    /** Token for keys in mPendingVerification. */
586    private int mPendingVerificationToken = 0;
587
588    volatile boolean mSystemReady;
589    volatile boolean mSafeMode;
590    volatile boolean mHasSystemUidErrors;
591
592    ApplicationInfo mAndroidApplication;
593    final ActivityInfo mResolveActivity = new ActivityInfo();
594    final ResolveInfo mResolveInfo = new ResolveInfo();
595    ComponentName mResolveComponentName;
596    PackageParser.Package mPlatformPackage;
597    ComponentName mCustomResolverComponentName;
598
599    boolean mResolverReplaced = false;
600
601    private final ComponentName mIntentFilterVerifierComponent;
602    private int mIntentFilterVerificationToken = 0;
603
604    /** Component that knows whether or not an ephemeral application exists */
605    final ComponentName mEphemeralResolverComponent;
606    /** The service connection to the ephemeral resolver */
607    final EphemeralResolverConnection mEphemeralResolverConnection;
608
609    /** Component used to install ephemeral applications */
610    final ComponentName mEphemeralInstallerComponent;
611    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
612    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
613
614    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
615            = new SparseArray<IntentFilterVerificationState>();
616
617    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
618            new DefaultPermissionGrantPolicy(this);
619
620    // List of packages names to keep cached, even if they are uninstalled for all users
621    private List<String> mKeepUninstalledPackages;
622
623    private static class IFVerificationParams {
624        PackageParser.Package pkg;
625        boolean replacing;
626        int userId;
627        int verifierUid;
628
629        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
630                int _userId, int _verifierUid) {
631            pkg = _pkg;
632            replacing = _replacing;
633            userId = _userId;
634            replacing = _replacing;
635            verifierUid = _verifierUid;
636        }
637    }
638
639    private interface IntentFilterVerifier<T extends IntentFilter> {
640        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
641                                               T filter, String packageName);
642        void startVerifications(int userId);
643        void receiveVerificationResponse(int verificationId);
644    }
645
646    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
647        private Context mContext;
648        private ComponentName mIntentFilterVerifierComponent;
649        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
650
651        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
652            mContext = context;
653            mIntentFilterVerifierComponent = verifierComponent;
654        }
655
656        private String getDefaultScheme() {
657            return IntentFilter.SCHEME_HTTPS;
658        }
659
660        @Override
661        public void startVerifications(int userId) {
662            // Launch verifications requests
663            int count = mCurrentIntentFilterVerifications.size();
664            for (int n=0; n<count; n++) {
665                int verificationId = mCurrentIntentFilterVerifications.get(n);
666                final IntentFilterVerificationState ivs =
667                        mIntentFilterVerificationStates.get(verificationId);
668
669                String packageName = ivs.getPackageName();
670
671                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
672                final int filterCount = filters.size();
673                ArraySet<String> domainsSet = new ArraySet<>();
674                for (int m=0; m<filterCount; m++) {
675                    PackageParser.ActivityIntentInfo filter = filters.get(m);
676                    domainsSet.addAll(filter.getHostsList());
677                }
678                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
679                synchronized (mPackages) {
680                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
681                            packageName, domainsList) != null) {
682                        scheduleWriteSettingsLocked();
683                    }
684                }
685                sendVerificationRequest(userId, verificationId, ivs);
686            }
687            mCurrentIntentFilterVerifications.clear();
688        }
689
690        private void sendVerificationRequest(int userId, int verificationId,
691                IntentFilterVerificationState ivs) {
692
693            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
694            verificationIntent.putExtra(
695                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
696                    verificationId);
697            verificationIntent.putExtra(
698                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
699                    getDefaultScheme());
700            verificationIntent.putExtra(
701                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
702                    ivs.getHostsString());
703            verificationIntent.putExtra(
704                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
705                    ivs.getPackageName());
706            verificationIntent.setComponent(mIntentFilterVerifierComponent);
707            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
708
709            UserHandle user = new UserHandle(userId);
710            mContext.sendBroadcastAsUser(verificationIntent, user);
711            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
712                    "Sending IntentFilter verification broadcast");
713        }
714
715        public void receiveVerificationResponse(int verificationId) {
716            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
717
718            final boolean verified = ivs.isVerified();
719
720            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
721            final int count = filters.size();
722            if (DEBUG_DOMAIN_VERIFICATION) {
723                Slog.i(TAG, "Received verification response " + verificationId
724                        + " for " + count + " filters, verified=" + verified);
725            }
726            for (int n=0; n<count; n++) {
727                PackageParser.ActivityIntentInfo filter = filters.get(n);
728                filter.setVerified(verified);
729
730                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
731                        + " verified with result:" + verified + " and hosts:"
732                        + ivs.getHostsString());
733            }
734
735            mIntentFilterVerificationStates.remove(verificationId);
736
737            final String packageName = ivs.getPackageName();
738            IntentFilterVerificationInfo ivi = null;
739
740            synchronized (mPackages) {
741                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
742            }
743            if (ivi == null) {
744                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
745                        + verificationId + " packageName:" + packageName);
746                return;
747            }
748            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
749                    "Updating IntentFilterVerificationInfo for package " + packageName
750                            +" verificationId:" + verificationId);
751
752            synchronized (mPackages) {
753                if (verified) {
754                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
755                } else {
756                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
757                }
758                scheduleWriteSettingsLocked();
759
760                final int userId = ivs.getUserId();
761                if (userId != UserHandle.USER_ALL) {
762                    final int userStatus =
763                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
764
765                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
766                    boolean needUpdate = false;
767
768                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
769                    // already been set by the User thru the Disambiguation dialog
770                    switch (userStatus) {
771                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
772                            if (verified) {
773                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
774                            } else {
775                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
776                            }
777                            needUpdate = true;
778                            break;
779
780                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
781                            if (verified) {
782                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
783                                needUpdate = true;
784                            }
785                            break;
786
787                        default:
788                            // Nothing to do
789                    }
790
791                    if (needUpdate) {
792                        mSettings.updateIntentFilterVerificationStatusLPw(
793                                packageName, updatedStatus, userId);
794                        scheduleWritePackageRestrictionsLocked(userId);
795                    }
796                }
797            }
798        }
799
800        @Override
801        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
802                    ActivityIntentInfo filter, String packageName) {
803            if (!hasValidDomains(filter)) {
804                return false;
805            }
806            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
807            if (ivs == null) {
808                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
809                        packageName);
810            }
811            if (DEBUG_DOMAIN_VERIFICATION) {
812                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
813            }
814            ivs.addFilter(filter);
815            return true;
816        }
817
818        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
819                int userId, int verificationId, String packageName) {
820            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
821                    verifierUid, userId, packageName);
822            ivs.setPendingState();
823            synchronized (mPackages) {
824                mIntentFilterVerificationStates.append(verificationId, ivs);
825                mCurrentIntentFilterVerifications.add(verificationId);
826            }
827            return ivs;
828        }
829    }
830
831    private static boolean hasValidDomains(ActivityIntentInfo filter) {
832        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
833                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
834                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
835    }
836
837    private IntentFilterVerifier mIntentFilterVerifier;
838
839    // Set of pending broadcasts for aggregating enable/disable of components.
840    static class PendingPackageBroadcasts {
841        // for each user id, a map of <package name -> components within that package>
842        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
843
844        public PendingPackageBroadcasts() {
845            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
846        }
847
848        public ArrayList<String> get(int userId, String packageName) {
849            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
850            return packages.get(packageName);
851        }
852
853        public void put(int userId, String packageName, ArrayList<String> components) {
854            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
855            packages.put(packageName, components);
856        }
857
858        public void remove(int userId, String packageName) {
859            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
860            if (packages != null) {
861                packages.remove(packageName);
862            }
863        }
864
865        public void remove(int userId) {
866            mUidMap.remove(userId);
867        }
868
869        public int userIdCount() {
870            return mUidMap.size();
871        }
872
873        public int userIdAt(int n) {
874            return mUidMap.keyAt(n);
875        }
876
877        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
878            return mUidMap.get(userId);
879        }
880
881        public int size() {
882            // total number of pending broadcast entries across all userIds
883            int num = 0;
884            for (int i = 0; i< mUidMap.size(); i++) {
885                num += mUidMap.valueAt(i).size();
886            }
887            return num;
888        }
889
890        public void clear() {
891            mUidMap.clear();
892        }
893
894        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
895            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
896            if (map == null) {
897                map = new ArrayMap<String, ArrayList<String>>();
898                mUidMap.put(userId, map);
899            }
900            return map;
901        }
902    }
903    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
904
905    // Service Connection to remote media container service to copy
906    // package uri's from external media onto secure containers
907    // or internal storage.
908    private IMediaContainerService mContainerService = null;
909
910    static final int SEND_PENDING_BROADCAST = 1;
911    static final int MCS_BOUND = 3;
912    static final int END_COPY = 4;
913    static final int INIT_COPY = 5;
914    static final int MCS_UNBIND = 6;
915    static final int START_CLEANING_PACKAGE = 7;
916    static final int FIND_INSTALL_LOC = 8;
917    static final int POST_INSTALL = 9;
918    static final int MCS_RECONNECT = 10;
919    static final int MCS_GIVE_UP = 11;
920    static final int UPDATED_MEDIA_STATUS = 12;
921    static final int WRITE_SETTINGS = 13;
922    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
923    static final int PACKAGE_VERIFIED = 15;
924    static final int CHECK_PENDING_VERIFICATION = 16;
925    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
926    static final int INTENT_FILTER_VERIFIED = 18;
927
928    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
929
930    // Delay time in millisecs
931    static final int BROADCAST_DELAY = 10 * 1000;
932
933    static UserManagerService sUserManager;
934
935    // Stores a list of users whose package restrictions file needs to be updated
936    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
937
938    final private DefaultContainerConnection mDefContainerConn =
939            new DefaultContainerConnection();
940    class DefaultContainerConnection implements ServiceConnection {
941        public void onServiceConnected(ComponentName name, IBinder service) {
942            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
943            IMediaContainerService imcs =
944                IMediaContainerService.Stub.asInterface(service);
945            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
946        }
947
948        public void onServiceDisconnected(ComponentName name) {
949            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
950        }
951    }
952
953    // Recordkeeping of restore-after-install operations that are currently in flight
954    // between the Package Manager and the Backup Manager
955    class PostInstallData {
956        public InstallArgs args;
957        public PackageInstalledInfo res;
958
959        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
960            args = _a;
961            res = _r;
962        }
963    }
964
965    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
966    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
967
968    // XML tags for backup/restore of various bits of state
969    private static final String TAG_PREFERRED_BACKUP = "pa";
970    private static final String TAG_DEFAULT_APPS = "da";
971    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
972
973    final String mRequiredVerifierPackage;
974    final String mRequiredInstallerPackage;
975
976    private final PackageUsage mPackageUsage = new PackageUsage();
977
978    private class PackageUsage {
979        private static final int WRITE_INTERVAL
980            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
981
982        private final Object mFileLock = new Object();
983        private final AtomicLong mLastWritten = new AtomicLong(0);
984        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
985
986        private boolean mIsHistoricalPackageUsageAvailable = true;
987
988        boolean isHistoricalPackageUsageAvailable() {
989            return mIsHistoricalPackageUsageAvailable;
990        }
991
992        void write(boolean force) {
993            if (force) {
994                writeInternal();
995                return;
996            }
997            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
998                && !DEBUG_DEXOPT) {
999                return;
1000            }
1001            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1002                new Thread("PackageUsage_DiskWriter") {
1003                    @Override
1004                    public void run() {
1005                        try {
1006                            writeInternal();
1007                        } finally {
1008                            mBackgroundWriteRunning.set(false);
1009                        }
1010                    }
1011                }.start();
1012            }
1013        }
1014
1015        private void writeInternal() {
1016            synchronized (mPackages) {
1017                synchronized (mFileLock) {
1018                    AtomicFile file = getFile();
1019                    FileOutputStream f = null;
1020                    try {
1021                        f = file.startWrite();
1022                        BufferedOutputStream out = new BufferedOutputStream(f);
1023                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1024                        StringBuilder sb = new StringBuilder();
1025                        for (PackageParser.Package pkg : mPackages.values()) {
1026                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1027                                continue;
1028                            }
1029                            sb.setLength(0);
1030                            sb.append(pkg.packageName);
1031                            sb.append(' ');
1032                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1033                            sb.append('\n');
1034                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1035                        }
1036                        out.flush();
1037                        file.finishWrite(f);
1038                    } catch (IOException e) {
1039                        if (f != null) {
1040                            file.failWrite(f);
1041                        }
1042                        Log.e(TAG, "Failed to write package usage times", e);
1043                    }
1044                }
1045            }
1046            mLastWritten.set(SystemClock.elapsedRealtime());
1047        }
1048
1049        void readLP() {
1050            synchronized (mFileLock) {
1051                AtomicFile file = getFile();
1052                BufferedInputStream in = null;
1053                try {
1054                    in = new BufferedInputStream(file.openRead());
1055                    StringBuffer sb = new StringBuffer();
1056                    while (true) {
1057                        String packageName = readToken(in, sb, ' ');
1058                        if (packageName == null) {
1059                            break;
1060                        }
1061                        String timeInMillisString = readToken(in, sb, '\n');
1062                        if (timeInMillisString == null) {
1063                            throw new IOException("Failed to find last usage time for package "
1064                                                  + packageName);
1065                        }
1066                        PackageParser.Package pkg = mPackages.get(packageName);
1067                        if (pkg == null) {
1068                            continue;
1069                        }
1070                        long timeInMillis;
1071                        try {
1072                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1073                        } catch (NumberFormatException e) {
1074                            throw new IOException("Failed to parse " + timeInMillisString
1075                                                  + " as a long.", e);
1076                        }
1077                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1078                    }
1079                } catch (FileNotFoundException expected) {
1080                    mIsHistoricalPackageUsageAvailable = false;
1081                } catch (IOException e) {
1082                    Log.w(TAG, "Failed to read package usage times", e);
1083                } finally {
1084                    IoUtils.closeQuietly(in);
1085                }
1086            }
1087            mLastWritten.set(SystemClock.elapsedRealtime());
1088        }
1089
1090        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1091                throws IOException {
1092            sb.setLength(0);
1093            while (true) {
1094                int ch = in.read();
1095                if (ch == -1) {
1096                    if (sb.length() == 0) {
1097                        return null;
1098                    }
1099                    throw new IOException("Unexpected EOF");
1100                }
1101                if (ch == endOfToken) {
1102                    return sb.toString();
1103                }
1104                sb.append((char)ch);
1105            }
1106        }
1107
1108        private AtomicFile getFile() {
1109            File dataDir = Environment.getDataDirectory();
1110            File systemDir = new File(dataDir, "system");
1111            File fname = new File(systemDir, "package-usage.list");
1112            return new AtomicFile(fname);
1113        }
1114    }
1115
1116    class PackageHandler extends Handler {
1117        private boolean mBound = false;
1118        final ArrayList<HandlerParams> mPendingInstalls =
1119            new ArrayList<HandlerParams>();
1120
1121        private boolean connectToService() {
1122            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1123                    " DefaultContainerService");
1124            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1125            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1126            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1127                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1128                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1129                mBound = true;
1130                return true;
1131            }
1132            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1133            return false;
1134        }
1135
1136        private void disconnectService() {
1137            mContainerService = null;
1138            mBound = false;
1139            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1140            mContext.unbindService(mDefContainerConn);
1141            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1142        }
1143
1144        PackageHandler(Looper looper) {
1145            super(looper);
1146        }
1147
1148        public void handleMessage(Message msg) {
1149            try {
1150                doHandleMessage(msg);
1151            } finally {
1152                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1153            }
1154        }
1155
1156        void doHandleMessage(Message msg) {
1157            switch (msg.what) {
1158                case INIT_COPY: {
1159                    HandlerParams params = (HandlerParams) msg.obj;
1160                    int idx = mPendingInstalls.size();
1161                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1162                    // If a bind was already initiated we dont really
1163                    // need to do anything. The pending install
1164                    // will be processed later on.
1165                    if (!mBound) {
1166                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1167                                System.identityHashCode(mHandler));
1168                        // If this is the only one pending we might
1169                        // have to bind to the service again.
1170                        if (!connectToService()) {
1171                            Slog.e(TAG, "Failed to bind to media container service");
1172                            params.serviceError();
1173                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1174                                    System.identityHashCode(mHandler));
1175                            if (params.traceMethod != null) {
1176                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1177                                        params.traceCookie);
1178                            }
1179                            return;
1180                        } else {
1181                            // Once we bind to the service, the first
1182                            // pending request will be processed.
1183                            mPendingInstalls.add(idx, params);
1184                        }
1185                    } else {
1186                        mPendingInstalls.add(idx, params);
1187                        // Already bound to the service. Just make
1188                        // sure we trigger off processing the first request.
1189                        if (idx == 0) {
1190                            mHandler.sendEmptyMessage(MCS_BOUND);
1191                        }
1192                    }
1193                    break;
1194                }
1195                case MCS_BOUND: {
1196                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1197                    if (msg.obj != null) {
1198                        mContainerService = (IMediaContainerService) msg.obj;
1199                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1200                                System.identityHashCode(mHandler));
1201                    }
1202                    if (mContainerService == null) {
1203                        if (!mBound) {
1204                            // Something seriously wrong since we are not bound and we are not
1205                            // waiting for connection. Bail out.
1206                            Slog.e(TAG, "Cannot bind to media container service");
1207                            for (HandlerParams params : mPendingInstalls) {
1208                                // Indicate service bind error
1209                                params.serviceError();
1210                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1211                                        System.identityHashCode(params));
1212                                if (params.traceMethod != null) {
1213                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1214                                            params.traceMethod, params.traceCookie);
1215                                }
1216                                return;
1217                            }
1218                            mPendingInstalls.clear();
1219                        } else {
1220                            Slog.w(TAG, "Waiting to connect to media container service");
1221                        }
1222                    } else if (mPendingInstalls.size() > 0) {
1223                        HandlerParams params = mPendingInstalls.get(0);
1224                        if (params != null) {
1225                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1226                                    System.identityHashCode(params));
1227                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1228                            if (params.startCopy()) {
1229                                // We are done...  look for more work or to
1230                                // go idle.
1231                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1232                                        "Checking for more work or unbind...");
1233                                // Delete pending install
1234                                if (mPendingInstalls.size() > 0) {
1235                                    mPendingInstalls.remove(0);
1236                                }
1237                                if (mPendingInstalls.size() == 0) {
1238                                    if (mBound) {
1239                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1240                                                "Posting delayed MCS_UNBIND");
1241                                        removeMessages(MCS_UNBIND);
1242                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1243                                        // Unbind after a little delay, to avoid
1244                                        // continual thrashing.
1245                                        sendMessageDelayed(ubmsg, 10000);
1246                                    }
1247                                } else {
1248                                    // There are more pending requests in queue.
1249                                    // Just post MCS_BOUND message to trigger processing
1250                                    // of next pending install.
1251                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1252                                            "Posting MCS_BOUND for next work");
1253                                    mHandler.sendEmptyMessage(MCS_BOUND);
1254                                }
1255                            }
1256                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1257                        }
1258                    } else {
1259                        // Should never happen ideally.
1260                        Slog.w(TAG, "Empty queue");
1261                    }
1262                    break;
1263                }
1264                case MCS_RECONNECT: {
1265                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1266                    if (mPendingInstalls.size() > 0) {
1267                        if (mBound) {
1268                            disconnectService();
1269                        }
1270                        if (!connectToService()) {
1271                            Slog.e(TAG, "Failed to bind to media container service");
1272                            for (HandlerParams params : mPendingInstalls) {
1273                                // Indicate service bind error
1274                                params.serviceError();
1275                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1276                                        System.identityHashCode(params));
1277                            }
1278                            mPendingInstalls.clear();
1279                        }
1280                    }
1281                    break;
1282                }
1283                case MCS_UNBIND: {
1284                    // If there is no actual work left, then time to unbind.
1285                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1286
1287                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1288                        if (mBound) {
1289                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1290
1291                            disconnectService();
1292                        }
1293                    } else if (mPendingInstalls.size() > 0) {
1294                        // There are more pending requests in queue.
1295                        // Just post MCS_BOUND message to trigger processing
1296                        // of next pending install.
1297                        mHandler.sendEmptyMessage(MCS_BOUND);
1298                    }
1299
1300                    break;
1301                }
1302                case MCS_GIVE_UP: {
1303                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1304                    HandlerParams params = mPendingInstalls.remove(0);
1305                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1306                            System.identityHashCode(params));
1307                    break;
1308                }
1309                case SEND_PENDING_BROADCAST: {
1310                    String packages[];
1311                    ArrayList<String> components[];
1312                    int size = 0;
1313                    int uids[];
1314                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1315                    synchronized (mPackages) {
1316                        if (mPendingBroadcasts == null) {
1317                            return;
1318                        }
1319                        size = mPendingBroadcasts.size();
1320                        if (size <= 0) {
1321                            // Nothing to be done. Just return
1322                            return;
1323                        }
1324                        packages = new String[size];
1325                        components = new ArrayList[size];
1326                        uids = new int[size];
1327                        int i = 0;  // filling out the above arrays
1328
1329                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1330                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1331                            Iterator<Map.Entry<String, ArrayList<String>>> it
1332                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1333                                            .entrySet().iterator();
1334                            while (it.hasNext() && i < size) {
1335                                Map.Entry<String, ArrayList<String>> ent = it.next();
1336                                packages[i] = ent.getKey();
1337                                components[i] = ent.getValue();
1338                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1339                                uids[i] = (ps != null)
1340                                        ? UserHandle.getUid(packageUserId, ps.appId)
1341                                        : -1;
1342                                i++;
1343                            }
1344                        }
1345                        size = i;
1346                        mPendingBroadcasts.clear();
1347                    }
1348                    // Send broadcasts
1349                    for (int i = 0; i < size; i++) {
1350                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1351                    }
1352                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1353                    break;
1354                }
1355                case START_CLEANING_PACKAGE: {
1356                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1357                    final String packageName = (String)msg.obj;
1358                    final int userId = msg.arg1;
1359                    final boolean andCode = msg.arg2 != 0;
1360                    synchronized (mPackages) {
1361                        if (userId == UserHandle.USER_ALL) {
1362                            int[] users = sUserManager.getUserIds();
1363                            for (int user : users) {
1364                                mSettings.addPackageToCleanLPw(
1365                                        new PackageCleanItem(user, packageName, andCode));
1366                            }
1367                        } else {
1368                            mSettings.addPackageToCleanLPw(
1369                                    new PackageCleanItem(userId, packageName, andCode));
1370                        }
1371                    }
1372                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1373                    startCleaningPackages();
1374                } break;
1375                case POST_INSTALL: {
1376                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1377
1378                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1379                    mRunningInstalls.delete(msg.arg1);
1380                    boolean deleteOld = false;
1381
1382                    if (data != null) {
1383                        InstallArgs args = data.args;
1384                        PackageInstalledInfo res = data.res;
1385
1386                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1387                            final String packageName = res.pkg.applicationInfo.packageName;
1388                            res.removedInfo.sendBroadcast(false, true, false);
1389                            Bundle extras = new Bundle(1);
1390                            extras.putInt(Intent.EXTRA_UID, res.uid);
1391
1392                            // Now that we successfully installed the package, grant runtime
1393                            // permissions if requested before broadcasting the install.
1394                            if ((args.installFlags
1395                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1396                                    && res.pkg.applicationInfo.targetSdkVersion
1397                                            >= Build.VERSION_CODES.M) {
1398                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1399                                        args.installGrantPermissions);
1400                            }
1401
1402                            // Determine the set of users who are adding this
1403                            // package for the first time vs. those who are seeing
1404                            // an update.
1405                            int[] firstUsers;
1406                            int[] updateUsers = new int[0];
1407                            if (res.origUsers == null || res.origUsers.length == 0) {
1408                                firstUsers = res.newUsers;
1409                            } else {
1410                                firstUsers = new int[0];
1411                                for (int i=0; i<res.newUsers.length; i++) {
1412                                    int user = res.newUsers[i];
1413                                    boolean isNew = true;
1414                                    for (int j=0; j<res.origUsers.length; j++) {
1415                                        if (res.origUsers[j] == user) {
1416                                            isNew = false;
1417                                            break;
1418                                        }
1419                                    }
1420                                    if (isNew) {
1421                                        int[] newFirst = new int[firstUsers.length+1];
1422                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1423                                                firstUsers.length);
1424                                        newFirst[firstUsers.length] = user;
1425                                        firstUsers = newFirst;
1426                                    } else {
1427                                        int[] newUpdate = new int[updateUsers.length+1];
1428                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1429                                                updateUsers.length);
1430                                        newUpdate[updateUsers.length] = user;
1431                                        updateUsers = newUpdate;
1432                                    }
1433                                }
1434                            }
1435                            // don't broadcast for ephemeral installs/updates
1436                            final boolean isEphemeral = isEphemeral(res.pkg);
1437                            if (!isEphemeral) {
1438                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1439                                        extras, 0 /*flags*/, null /*targetPackage*/,
1440                                        null /*finishedReceiver*/, firstUsers);
1441                            }
1442                            final boolean update = res.removedInfo.removedPackage != null;
1443                            if (update) {
1444                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1445                            }
1446                            if (!isEphemeral) {
1447                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1448                                        extras, 0 /*flags*/, null /*targetPackage*/,
1449                                        null /*finishedReceiver*/, updateUsers);
1450                            }
1451                            if (update) {
1452                                if (!isEphemeral) {
1453                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1454                                            packageName, extras, 0 /*flags*/,
1455                                            null /*targetPackage*/, null /*finishedReceiver*/,
1456                                            updateUsers);
1457                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1458                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1459                                            packageName /*targetPackage*/,
1460                                            null /*finishedReceiver*/, updateUsers);
1461                                }
1462
1463                                // treat asec-hosted packages like removable media on upgrade
1464                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1465                                    if (DEBUG_INSTALL) {
1466                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1467                                                + " is ASEC-hosted -> AVAILABLE");
1468                                    }
1469                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1470                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1471                                    pkgList.add(packageName);
1472                                    sendResourcesChangedBroadcast(true, true,
1473                                            pkgList,uidArray, null);
1474                                }
1475                            }
1476                            if (res.removedInfo.args != null) {
1477                                // Remove the replaced package's older resources safely now
1478                                deleteOld = true;
1479                            }
1480
1481                            // If this app is a browser and it's newly-installed for some
1482                            // users, clear any default-browser state in those users
1483                            if (firstUsers.length > 0) {
1484                                // the app's nature doesn't depend on the user, so we can just
1485                                // check its browser nature in any user and generalize.
1486                                if (packageIsBrowser(packageName, firstUsers[0])) {
1487                                    synchronized (mPackages) {
1488                                        for (int userId : firstUsers) {
1489                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1490                                        }
1491                                    }
1492                                }
1493                            }
1494                            // Log current value of "unknown sources" setting
1495                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1496                                getUnknownSourcesSettings());
1497                        }
1498                        // Force a gc to clear up things
1499                        Runtime.getRuntime().gc();
1500                        // We delete after a gc for applications  on sdcard.
1501                        if (deleteOld) {
1502                            synchronized (mInstallLock) {
1503                                res.removedInfo.args.doPostDeleteLI(true);
1504                            }
1505                        }
1506                        if (args.observer != null) {
1507                            try {
1508                                Bundle extras = extrasForInstallResult(res);
1509                                args.observer.onPackageInstalled(res.name, res.returnCode,
1510                                        res.returnMsg, extras);
1511                            } catch (RemoteException e) {
1512                                Slog.i(TAG, "Observer no longer exists.");
1513                            }
1514                        }
1515                        if (args.traceMethod != null) {
1516                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1517                                    args.traceCookie);
1518                        }
1519                        return;
1520                    } else {
1521                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1522                    }
1523
1524                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1525                } break;
1526                case UPDATED_MEDIA_STATUS: {
1527                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1528                    boolean reportStatus = msg.arg1 == 1;
1529                    boolean doGc = msg.arg2 == 1;
1530                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1531                    if (doGc) {
1532                        // Force a gc to clear up stale containers.
1533                        Runtime.getRuntime().gc();
1534                    }
1535                    if (msg.obj != null) {
1536                        @SuppressWarnings("unchecked")
1537                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1538                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1539                        // Unload containers
1540                        unloadAllContainers(args);
1541                    }
1542                    if (reportStatus) {
1543                        try {
1544                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1545                            PackageHelper.getMountService().finishMediaUpdate();
1546                        } catch (RemoteException e) {
1547                            Log.e(TAG, "MountService not running?");
1548                        }
1549                    }
1550                } break;
1551                case WRITE_SETTINGS: {
1552                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1553                    synchronized (mPackages) {
1554                        removeMessages(WRITE_SETTINGS);
1555                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1556                        mSettings.writeLPr();
1557                        mDirtyUsers.clear();
1558                    }
1559                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1560                } break;
1561                case WRITE_PACKAGE_RESTRICTIONS: {
1562                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1563                    synchronized (mPackages) {
1564                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1565                        for (int userId : mDirtyUsers) {
1566                            mSettings.writePackageRestrictionsLPr(userId);
1567                        }
1568                        mDirtyUsers.clear();
1569                    }
1570                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1571                } break;
1572                case CHECK_PENDING_VERIFICATION: {
1573                    final int verificationId = msg.arg1;
1574                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1575
1576                    if ((state != null) && !state.timeoutExtended()) {
1577                        final InstallArgs args = state.getInstallArgs();
1578                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1579
1580                        Slog.i(TAG, "Verification timed out for " + originUri);
1581                        mPendingVerification.remove(verificationId);
1582
1583                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1584
1585                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1586                            Slog.i(TAG, "Continuing with installation of " + originUri);
1587                            state.setVerifierResponse(Binder.getCallingUid(),
1588                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1589                            broadcastPackageVerified(verificationId, originUri,
1590                                    PackageManager.VERIFICATION_ALLOW,
1591                                    state.getInstallArgs().getUser());
1592                            try {
1593                                ret = args.copyApk(mContainerService, true);
1594                            } catch (RemoteException e) {
1595                                Slog.e(TAG, "Could not contact the ContainerService");
1596                            }
1597                        } else {
1598                            broadcastPackageVerified(verificationId, originUri,
1599                                    PackageManager.VERIFICATION_REJECT,
1600                                    state.getInstallArgs().getUser());
1601                        }
1602
1603                        Trace.asyncTraceEnd(
1604                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1605
1606                        processPendingInstall(args, ret);
1607                        mHandler.sendEmptyMessage(MCS_UNBIND);
1608                    }
1609                    break;
1610                }
1611                case PACKAGE_VERIFIED: {
1612                    final int verificationId = msg.arg1;
1613
1614                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1615                    if (state == null) {
1616                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1617                        break;
1618                    }
1619
1620                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1621
1622                    state.setVerifierResponse(response.callerUid, response.code);
1623
1624                    if (state.isVerificationComplete()) {
1625                        mPendingVerification.remove(verificationId);
1626
1627                        final InstallArgs args = state.getInstallArgs();
1628                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1629
1630                        int ret;
1631                        if (state.isInstallAllowed()) {
1632                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1633                            broadcastPackageVerified(verificationId, originUri,
1634                                    response.code, state.getInstallArgs().getUser());
1635                            try {
1636                                ret = args.copyApk(mContainerService, true);
1637                            } catch (RemoteException e) {
1638                                Slog.e(TAG, "Could not contact the ContainerService");
1639                            }
1640                        } else {
1641                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1642                        }
1643
1644                        Trace.asyncTraceEnd(
1645                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1646
1647                        processPendingInstall(args, ret);
1648                        mHandler.sendEmptyMessage(MCS_UNBIND);
1649                    }
1650
1651                    break;
1652                }
1653                case START_INTENT_FILTER_VERIFICATIONS: {
1654                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1655                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1656                            params.replacing, params.pkg);
1657                    break;
1658                }
1659                case INTENT_FILTER_VERIFIED: {
1660                    final int verificationId = msg.arg1;
1661
1662                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1663                            verificationId);
1664                    if (state == null) {
1665                        Slog.w(TAG, "Invalid IntentFilter verification token "
1666                                + verificationId + " received");
1667                        break;
1668                    }
1669
1670                    final int userId = state.getUserId();
1671
1672                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1673                            "Processing IntentFilter verification with token:"
1674                            + verificationId + " and userId:" + userId);
1675
1676                    final IntentFilterVerificationResponse response =
1677                            (IntentFilterVerificationResponse) msg.obj;
1678
1679                    state.setVerifierResponse(response.callerUid, response.code);
1680
1681                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1682                            "IntentFilter verification with token:" + verificationId
1683                            + " and userId:" + userId
1684                            + " is settings verifier response with response code:"
1685                            + response.code);
1686
1687                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1688                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1689                                + response.getFailedDomainsString());
1690                    }
1691
1692                    if (state.isVerificationComplete()) {
1693                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1694                    } else {
1695                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1696                                "IntentFilter verification with token:" + verificationId
1697                                + " was not said to be complete");
1698                    }
1699
1700                    break;
1701                }
1702            }
1703        }
1704    }
1705
1706    private StorageEventListener mStorageListener = new StorageEventListener() {
1707        @Override
1708        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1709            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1710                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1711                    final String volumeUuid = vol.getFsUuid();
1712
1713                    // Clean up any users or apps that were removed or recreated
1714                    // while this volume was missing
1715                    reconcileUsers(volumeUuid);
1716                    reconcileApps(volumeUuid);
1717
1718                    // Clean up any install sessions that expired or were
1719                    // cancelled while this volume was missing
1720                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1721
1722                    loadPrivatePackages(vol);
1723
1724                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1725                    unloadPrivatePackages(vol);
1726                }
1727            }
1728
1729            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1730                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1731                    updateExternalMediaStatus(true, false);
1732                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1733                    updateExternalMediaStatus(false, false);
1734                }
1735            }
1736        }
1737
1738        @Override
1739        public void onVolumeForgotten(String fsUuid) {
1740            if (TextUtils.isEmpty(fsUuid)) {
1741                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1742                return;
1743            }
1744
1745            // Remove any apps installed on the forgotten volume
1746            synchronized (mPackages) {
1747                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1748                for (PackageSetting ps : packages) {
1749                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1750                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1751                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1752                }
1753
1754                mSettings.onVolumeForgotten(fsUuid);
1755                mSettings.writeLPr();
1756            }
1757        }
1758    };
1759
1760    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1761            String[] grantedPermissions) {
1762        if (userId >= UserHandle.USER_SYSTEM) {
1763            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1764        } else if (userId == UserHandle.USER_ALL) {
1765            final int[] userIds;
1766            synchronized (mPackages) {
1767                userIds = UserManagerService.getInstance().getUserIds();
1768            }
1769            for (int someUserId : userIds) {
1770                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1771            }
1772        }
1773
1774        // We could have touched GID membership, so flush out packages.list
1775        synchronized (mPackages) {
1776            mSettings.writePackageListLPr();
1777        }
1778    }
1779
1780    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1781            String[] grantedPermissions) {
1782        SettingBase sb = (SettingBase) pkg.mExtras;
1783        if (sb == null) {
1784            return;
1785        }
1786
1787        PermissionsState permissionsState = sb.getPermissionsState();
1788
1789        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1790                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1791
1792        synchronized (mPackages) {
1793            for (String permission : pkg.requestedPermissions) {
1794                BasePermission bp = mSettings.mPermissions.get(permission);
1795                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1796                        && (grantedPermissions == null
1797                               || ArrayUtils.contains(grantedPermissions, permission))) {
1798                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1799                    // Installer cannot change immutable permissions.
1800                    if ((flags & immutableFlags) == 0) {
1801                        grantRuntimePermission(pkg.packageName, permission, userId);
1802                    }
1803                }
1804            }
1805        }
1806    }
1807
1808    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1809        Bundle extras = null;
1810        switch (res.returnCode) {
1811            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1812                extras = new Bundle();
1813                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1814                        res.origPermission);
1815                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1816                        res.origPackage);
1817                break;
1818            }
1819            case PackageManager.INSTALL_SUCCEEDED: {
1820                extras = new Bundle();
1821                extras.putBoolean(Intent.EXTRA_REPLACING,
1822                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1823                break;
1824            }
1825        }
1826        return extras;
1827    }
1828
1829    void scheduleWriteSettingsLocked() {
1830        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1831            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1832        }
1833    }
1834
1835    void scheduleWritePackageRestrictionsLocked(int userId) {
1836        if (!sUserManager.exists(userId)) return;
1837        mDirtyUsers.add(userId);
1838        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1839            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1840        }
1841    }
1842
1843    public static PackageManagerService main(Context context, Installer installer,
1844            boolean factoryTest, boolean onlyCore) {
1845        PackageManagerService m = new PackageManagerService(context, installer,
1846                factoryTest, onlyCore);
1847        m.enableSystemUserApps();
1848        ServiceManager.addService("package", m);
1849        return m;
1850    }
1851
1852    private void enableSystemUserApps() {
1853        if (!UserManager.isSplitSystemUser()) {
1854            return;
1855        }
1856        // For system user, enable apps based on the following conditions:
1857        // - app is whitelisted or belong to one of these groups:
1858        //   -- system app which has no launcher icons
1859        //   -- system app which has INTERACT_ACROSS_USERS permission
1860        //   -- system IME app
1861        // - app is not in the blacklist
1862        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1863        Set<String> enableApps = new ArraySet<>();
1864        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1865                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1866                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1867        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1868        enableApps.addAll(wlApps);
1869        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1870        enableApps.removeAll(blApps);
1871
1872        List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true,
1873                UserHandle.SYSTEM);
1874        final int systemAppsSize = systemApps.size();
1875        synchronized (mPackages) {
1876            for (int i = 0; i < systemAppsSize; i++) {
1877                String pName = systemApps.get(i);
1878                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1879                // Should not happen, but we shouldn't be failing if it does
1880                if (pkgSetting == null) {
1881                    continue;
1882                }
1883                boolean installed = enableApps.contains(pName);
1884                pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM);
1885            }
1886        }
1887    }
1888
1889    static String[] splitString(String str, char sep) {
1890        int count = 1;
1891        int i = 0;
1892        while ((i=str.indexOf(sep, i)) >= 0) {
1893            count++;
1894            i++;
1895        }
1896
1897        String[] res = new String[count];
1898        i=0;
1899        count = 0;
1900        int lastI=0;
1901        while ((i=str.indexOf(sep, i)) >= 0) {
1902            res[count] = str.substring(lastI, i);
1903            count++;
1904            i++;
1905            lastI = i;
1906        }
1907        res[count] = str.substring(lastI, str.length());
1908        return res;
1909    }
1910
1911    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1912        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1913                Context.DISPLAY_SERVICE);
1914        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1915    }
1916
1917    public PackageManagerService(Context context, Installer installer,
1918            boolean factoryTest, boolean onlyCore) {
1919        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1920                SystemClock.uptimeMillis());
1921
1922        if (mSdkVersion <= 0) {
1923            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1924        }
1925
1926        mContext = context;
1927        mFactoryTest = factoryTest;
1928        mOnlyCore = onlyCore;
1929        mMetrics = new DisplayMetrics();
1930        mSettings = new Settings(mPackages);
1931        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1932                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1933        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1934                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1935        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1936                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1937        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1938                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1939        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1940                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1941        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1942                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1943
1944        String separateProcesses = SystemProperties.get("debug.separate_processes");
1945        if (separateProcesses != null && separateProcesses.length() > 0) {
1946            if ("*".equals(separateProcesses)) {
1947                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1948                mSeparateProcesses = null;
1949                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1950            } else {
1951                mDefParseFlags = 0;
1952                mSeparateProcesses = separateProcesses.split(",");
1953                Slog.w(TAG, "Running with debug.separate_processes: "
1954                        + separateProcesses);
1955            }
1956        } else {
1957            mDefParseFlags = 0;
1958            mSeparateProcesses = null;
1959        }
1960
1961        mInstaller = installer;
1962        mPackageDexOptimizer = new PackageDexOptimizer(this);
1963        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1964
1965        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1966                FgThread.get().getLooper());
1967
1968        getDefaultDisplayMetrics(context, mMetrics);
1969
1970        SystemConfig systemConfig = SystemConfig.getInstance();
1971        mGlobalGids = systemConfig.getGlobalGids();
1972        mSystemPermissions = systemConfig.getSystemPermissions();
1973        mAvailableFeatures = systemConfig.getAvailableFeatures();
1974
1975        synchronized (mInstallLock) {
1976        // writer
1977        synchronized (mPackages) {
1978            mHandlerThread = new ServiceThread(TAG,
1979                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1980            mHandlerThread.start();
1981            mHandler = new PackageHandler(mHandlerThread.getLooper());
1982            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1983
1984            File dataDir = Environment.getDataDirectory();
1985            mAppDataDir = new File(dataDir, "data");
1986            mAppInstallDir = new File(dataDir, "app");
1987            mAppLib32InstallDir = new File(dataDir, "app-lib");
1988            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1989            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1990            mUserAppDataDir = new File(dataDir, "user");
1991            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1992
1993            sUserManager = new UserManagerService(context, this, mPackages);
1994
1995            // Propagate permission configuration in to package manager.
1996            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1997                    = systemConfig.getPermissions();
1998            for (int i=0; i<permConfig.size(); i++) {
1999                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2000                BasePermission bp = mSettings.mPermissions.get(perm.name);
2001                if (bp == null) {
2002                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2003                    mSettings.mPermissions.put(perm.name, bp);
2004                }
2005                if (perm.gids != null) {
2006                    bp.setGids(perm.gids, perm.perUser);
2007                }
2008            }
2009
2010            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2011            for (int i=0; i<libConfig.size(); i++) {
2012                mSharedLibraries.put(libConfig.keyAt(i),
2013                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2014            }
2015
2016            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2017
2018            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2019
2020            String customResolverActivity = Resources.getSystem().getString(
2021                    R.string.config_customResolverActivity);
2022            if (TextUtils.isEmpty(customResolverActivity)) {
2023                customResolverActivity = null;
2024            } else {
2025                mCustomResolverComponentName = ComponentName.unflattenFromString(
2026                        customResolverActivity);
2027            }
2028
2029            long startTime = SystemClock.uptimeMillis();
2030
2031            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2032                    startTime);
2033
2034            // Set flag to monitor and not change apk file paths when
2035            // scanning install directories.
2036            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2037
2038            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2039            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2040
2041            if (bootClassPath == null) {
2042                Slog.w(TAG, "No BOOTCLASSPATH found!");
2043            }
2044
2045            if (systemServerClassPath == null) {
2046                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2047            }
2048
2049            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2050            final String[] dexCodeInstructionSets =
2051                    getDexCodeInstructionSets(
2052                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2053
2054            /**
2055             * Ensure all external libraries have had dexopt run on them.
2056             */
2057            if (mSharedLibraries.size() > 0) {
2058                // NOTE: For now, we're compiling these system "shared libraries"
2059                // (and framework jars) into all available architectures. It's possible
2060                // to compile them only when we come across an app that uses them (there's
2061                // already logic for that in scanPackageLI) but that adds some complexity.
2062                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2063                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2064                        final String lib = libEntry.path;
2065                        if (lib == null) {
2066                            continue;
2067                        }
2068
2069                        try {
2070                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2071                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2072                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2073                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2074                            }
2075                        } catch (FileNotFoundException e) {
2076                            Slog.w(TAG, "Library not found: " + lib);
2077                        } catch (IOException e) {
2078                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2079                                    + e.getMessage());
2080                        }
2081                    }
2082                }
2083            }
2084
2085            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2086
2087            final VersionInfo ver = mSettings.getInternalVersion();
2088            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2089            // when upgrading from pre-M, promote system app permissions from install to runtime
2090            mPromoteSystemApps =
2091                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2092
2093            // save off the names of pre-existing system packages prior to scanning; we don't
2094            // want to automatically grant runtime permissions for new system apps
2095            if (mPromoteSystemApps) {
2096                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2097                while (pkgSettingIter.hasNext()) {
2098                    PackageSetting ps = pkgSettingIter.next();
2099                    if (isSystemApp(ps)) {
2100                        mExistingSystemPackages.add(ps.name);
2101                    }
2102                }
2103            }
2104
2105            // Collect vendor overlay packages.
2106            // (Do this before scanning any apps.)
2107            // For security and version matching reason, only consider
2108            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2109            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2110            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2111                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2112
2113            // Find base frameworks (resource packages without code).
2114            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2115                    | PackageParser.PARSE_IS_SYSTEM_DIR
2116                    | PackageParser.PARSE_IS_PRIVILEGED,
2117                    scanFlags | SCAN_NO_DEX, 0);
2118
2119            // Collected privileged system packages.
2120            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2121            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2122                    | PackageParser.PARSE_IS_SYSTEM_DIR
2123                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2124
2125            // Collect ordinary system packages.
2126            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2127            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2128                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2129
2130            // Collect all vendor packages.
2131            File vendorAppDir = new File("/vendor/app");
2132            try {
2133                vendorAppDir = vendorAppDir.getCanonicalFile();
2134            } catch (IOException e) {
2135                // failed to look up canonical path, continue with original one
2136            }
2137            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2138                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2139
2140            // Collect all OEM packages.
2141            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2142            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2143                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2144
2145            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2146            mInstaller.moveFiles();
2147
2148            // Prune any system packages that no longer exist.
2149            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2150            if (!mOnlyCore) {
2151                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2152                while (psit.hasNext()) {
2153                    PackageSetting ps = psit.next();
2154
2155                    /*
2156                     * If this is not a system app, it can't be a
2157                     * disable system app.
2158                     */
2159                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2160                        continue;
2161                    }
2162
2163                    /*
2164                     * If the package is scanned, it's not erased.
2165                     */
2166                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2167                    if (scannedPkg != null) {
2168                        /*
2169                         * If the system app is both scanned and in the
2170                         * disabled packages list, then it must have been
2171                         * added via OTA. Remove it from the currently
2172                         * scanned package so the previously user-installed
2173                         * application can be scanned.
2174                         */
2175                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2176                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2177                                    + ps.name + "; removing system app.  Last known codePath="
2178                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2179                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2180                                    + scannedPkg.mVersionCode);
2181                            removePackageLI(ps, true);
2182                            mExpectingBetter.put(ps.name, ps.codePath);
2183                        }
2184
2185                        continue;
2186                    }
2187
2188                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2189                        psit.remove();
2190                        logCriticalInfo(Log.WARN, "System package " + ps.name
2191                                + " no longer exists; wiping its data");
2192                        removeDataDirsLI(null, ps.name);
2193                    } else {
2194                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2195                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2196                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2197                        }
2198                    }
2199                }
2200            }
2201
2202            //look for any incomplete package installations
2203            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2204            //clean up list
2205            for(int i = 0; i < deletePkgsList.size(); i++) {
2206                //clean up here
2207                cleanupInstallFailedPackage(deletePkgsList.get(i));
2208            }
2209            //delete tmp files
2210            deleteTempPackageFiles();
2211
2212            // Remove any shared userIDs that have no associated packages
2213            mSettings.pruneSharedUsersLPw();
2214
2215            if (!mOnlyCore) {
2216                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2217                        SystemClock.uptimeMillis());
2218                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2219
2220                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2221                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2222
2223                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2224                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2225
2226                /**
2227                 * Remove disable package settings for any updated system
2228                 * apps that were removed via an OTA. If they're not a
2229                 * previously-updated app, remove them completely.
2230                 * Otherwise, just revoke their system-level permissions.
2231                 */
2232                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2233                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2234                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2235
2236                    String msg;
2237                    if (deletedPkg == null) {
2238                        msg = "Updated system package " + deletedAppName
2239                                + " no longer exists; wiping its data";
2240                        removeDataDirsLI(null, deletedAppName);
2241                    } else {
2242                        msg = "Updated system app + " + deletedAppName
2243                                + " no longer present; removing system privileges for "
2244                                + deletedAppName;
2245
2246                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2247
2248                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2249                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2250                    }
2251                    logCriticalInfo(Log.WARN, msg);
2252                }
2253
2254                /**
2255                 * Make sure all system apps that we expected to appear on
2256                 * the userdata partition actually showed up. If they never
2257                 * appeared, crawl back and revive the system version.
2258                 */
2259                for (int i = 0; i < mExpectingBetter.size(); i++) {
2260                    final String packageName = mExpectingBetter.keyAt(i);
2261                    if (!mPackages.containsKey(packageName)) {
2262                        final File scanFile = mExpectingBetter.valueAt(i);
2263
2264                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2265                                + " but never showed up; reverting to system");
2266
2267                        final int reparseFlags;
2268                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2269                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2270                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2271                                    | PackageParser.PARSE_IS_PRIVILEGED;
2272                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2273                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2274                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2275                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2276                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2277                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2278                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2279                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2280                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2281                        } else {
2282                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2283                            continue;
2284                        }
2285
2286                        mSettings.enableSystemPackageLPw(packageName);
2287
2288                        try {
2289                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2290                        } catch (PackageManagerException e) {
2291                            Slog.e(TAG, "Failed to parse original system package: "
2292                                    + e.getMessage());
2293                        }
2294                    }
2295                }
2296            }
2297            mExpectingBetter.clear();
2298
2299            // Now that we know all of the shared libraries, update all clients to have
2300            // the correct library paths.
2301            updateAllSharedLibrariesLPw();
2302
2303            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2304                // NOTE: We ignore potential failures here during a system scan (like
2305                // the rest of the commands above) because there's precious little we
2306                // can do about it. A settings error is reported, though.
2307                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2308                        false /* boot complete */);
2309            }
2310
2311            // Now that we know all the packages we are keeping,
2312            // read and update their last usage times.
2313            mPackageUsage.readLP();
2314
2315            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2316                    SystemClock.uptimeMillis());
2317            Slog.i(TAG, "Time to scan packages: "
2318                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2319                    + " seconds");
2320
2321            // If the platform SDK has changed since the last time we booted,
2322            // we need to re-grant app permission to catch any new ones that
2323            // appear.  This is really a hack, and means that apps can in some
2324            // cases get permissions that the user didn't initially explicitly
2325            // allow...  it would be nice to have some better way to handle
2326            // this situation.
2327            int updateFlags = UPDATE_PERMISSIONS_ALL;
2328            if (ver.sdkVersion != mSdkVersion) {
2329                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2330                        + mSdkVersion + "; regranting permissions for internal storage");
2331                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2332            }
2333            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2334            ver.sdkVersion = mSdkVersion;
2335
2336            // If this is the first boot or an update from pre-M, and it is a normal
2337            // boot, then we need to initialize the default preferred apps across
2338            // all defined users.
2339            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2340                for (UserInfo user : sUserManager.getUsers(true)) {
2341                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2342                    applyFactoryDefaultBrowserLPw(user.id);
2343                    primeDomainVerificationsLPw(user.id);
2344                }
2345            }
2346
2347            // If this is first boot after an OTA, and a normal boot, then
2348            // we need to clear code cache directories.
2349            if (mIsUpgrade && !onlyCore) {
2350                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2351                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2352                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2353                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2354                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2355                    }
2356                }
2357                ver.fingerprint = Build.FINGERPRINT;
2358            }
2359
2360            checkDefaultBrowser();
2361
2362            // clear only after permissions and other defaults have been updated
2363            mExistingSystemPackages.clear();
2364            mPromoteSystemApps = false;
2365
2366            // All the changes are done during package scanning.
2367            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2368
2369            // can downgrade to reader
2370            mSettings.writeLPr();
2371
2372            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2373                    SystemClock.uptimeMillis());
2374
2375            mRequiredVerifierPackage = getRequiredVerifierLPr();
2376            mRequiredInstallerPackage = getRequiredInstallerLPr();
2377
2378            mInstallerService = new PackageInstallerService(context, this);
2379
2380            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2381            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2382                    mIntentFilterVerifierComponent);
2383
2384            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2385            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2386            // both the installer and resolver must be present to enable ephemeral
2387            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2388                if (DEBUG_EPHEMERAL) {
2389                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2390                            + " installer:" + ephemeralInstallerComponent);
2391                }
2392                mEphemeralResolverComponent = ephemeralResolverComponent;
2393                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2394                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2395                mEphemeralResolverConnection =
2396                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2397            } else {
2398                if (DEBUG_EPHEMERAL) {
2399                    final String missingComponent =
2400                            (ephemeralResolverComponent == null)
2401                            ? (ephemeralInstallerComponent == null)
2402                                    ? "resolver and installer"
2403                                    : "resolver"
2404                            : "installer";
2405                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2406                }
2407                mEphemeralResolverComponent = null;
2408                mEphemeralInstallerComponent = null;
2409                mEphemeralResolverConnection = null;
2410            }
2411        } // synchronized (mPackages)
2412        } // synchronized (mInstallLock)
2413
2414        // Now after opening every single application zip, make sure they
2415        // are all flushed.  Not really needed, but keeps things nice and
2416        // tidy.
2417        Runtime.getRuntime().gc();
2418
2419        // The initial scanning above does many calls into installd while
2420        // holding the mPackages lock, but we're mostly interested in yelling
2421        // once we have a booted system.
2422        mInstaller.setWarnIfHeld(mPackages);
2423
2424        // Expose private service for system components to use.
2425        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2426    }
2427
2428    @Override
2429    public boolean isFirstBoot() {
2430        return !mRestoredSettings;
2431    }
2432
2433    @Override
2434    public boolean isOnlyCoreApps() {
2435        return mOnlyCore;
2436    }
2437
2438    @Override
2439    public boolean isUpgrade() {
2440        return mIsUpgrade;
2441    }
2442
2443    private String getRequiredVerifierLPr() {
2444        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2445        // We only care about verifier that's installed under system user.
2446        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2447                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2448
2449        String requiredVerifier = null;
2450
2451        final int N = receivers.size();
2452        for (int i = 0; i < N; i++) {
2453            final ResolveInfo info = receivers.get(i);
2454
2455            if (info.activityInfo == null) {
2456                continue;
2457            }
2458
2459            final String packageName = info.activityInfo.packageName;
2460
2461            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2462                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2463                continue;
2464            }
2465
2466            if (requiredVerifier != null) {
2467                throw new RuntimeException("There can be only one required verifier");
2468            }
2469
2470            requiredVerifier = packageName;
2471        }
2472
2473        return requiredVerifier;
2474    }
2475
2476    private String getRequiredInstallerLPr() {
2477        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2478        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2479        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2480
2481        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2482                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2483
2484        String requiredInstaller = null;
2485
2486        final int N = installers.size();
2487        for (int i = 0; i < N; i++) {
2488            final ResolveInfo info = installers.get(i);
2489            final String packageName = info.activityInfo.packageName;
2490
2491            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2492                continue;
2493            }
2494
2495            if (requiredInstaller != null) {
2496                throw new RuntimeException("There must be one required installer");
2497            }
2498
2499            requiredInstaller = packageName;
2500        }
2501
2502        if (requiredInstaller == null) {
2503            throw new RuntimeException("There must be one required installer");
2504        }
2505
2506        return requiredInstaller;
2507    }
2508
2509    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2510        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2511        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2512                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2513
2514        ComponentName verifierComponentName = null;
2515
2516        int priority = -1000;
2517        final int N = receivers.size();
2518        for (int i = 0; i < N; i++) {
2519            final ResolveInfo info = receivers.get(i);
2520
2521            if (info.activityInfo == null) {
2522                continue;
2523            }
2524
2525            final String packageName = info.activityInfo.packageName;
2526
2527            final PackageSetting ps = mSettings.mPackages.get(packageName);
2528            if (ps == null) {
2529                continue;
2530            }
2531
2532            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2533                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2534                continue;
2535            }
2536
2537            // Select the IntentFilterVerifier with the highest priority
2538            if (priority < info.priority) {
2539                priority = info.priority;
2540                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2541                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2542                        + verifierComponentName + " with priority: " + info.priority);
2543            }
2544        }
2545
2546        return verifierComponentName;
2547    }
2548
2549    private ComponentName getEphemeralResolverLPr() {
2550        final String[] packageArray =
2551                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2552        if (packageArray.length == 0) {
2553            if (DEBUG_EPHEMERAL) {
2554                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2555            }
2556            return null;
2557        }
2558
2559        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2560        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2561                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2562
2563        final int N = resolvers.size();
2564        if (N == 0) {
2565            if (DEBUG_EPHEMERAL) {
2566                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2567            }
2568            return null;
2569        }
2570
2571        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2572        for (int i = 0; i < N; i++) {
2573            final ResolveInfo info = resolvers.get(i);
2574
2575            if (info.serviceInfo == null) {
2576                continue;
2577            }
2578
2579            final String packageName = info.serviceInfo.packageName;
2580            if (!possiblePackages.contains(packageName)) {
2581                if (DEBUG_EPHEMERAL) {
2582                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2583                            + " pkg: " + packageName + ", info:" + info);
2584                }
2585                continue;
2586            }
2587
2588            if (DEBUG_EPHEMERAL) {
2589                Slog.v(TAG, "Ephemeral resolver found;"
2590                        + " pkg: " + packageName + ", info:" + info);
2591            }
2592            return new ComponentName(packageName, info.serviceInfo.name);
2593        }
2594        if (DEBUG_EPHEMERAL) {
2595            Slog.v(TAG, "Ephemeral resolver NOT found");
2596        }
2597        return null;
2598    }
2599
2600    private ComponentName getEphemeralInstallerLPr() {
2601        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2602        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2603        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2604        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2605                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2606
2607        ComponentName ephemeralInstaller = null;
2608
2609        final int N = installers.size();
2610        for (int i = 0; i < N; i++) {
2611            final ResolveInfo info = installers.get(i);
2612            final String packageName = info.activityInfo.packageName;
2613
2614            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2615                if (DEBUG_EPHEMERAL) {
2616                    Slog.d(TAG, "Ephemeral installer is not system app;"
2617                            + " pkg: " + packageName + ", info:" + info);
2618                }
2619                continue;
2620            }
2621
2622            if (ephemeralInstaller != null) {
2623                throw new RuntimeException("There must only be one ephemeral installer");
2624            }
2625
2626            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2627        }
2628
2629        return ephemeralInstaller;
2630    }
2631
2632    private void primeDomainVerificationsLPw(int userId) {
2633        if (DEBUG_DOMAIN_VERIFICATION) {
2634            Slog.d(TAG, "Priming domain verifications in user " + userId);
2635        }
2636
2637        SystemConfig systemConfig = SystemConfig.getInstance();
2638        ArraySet<String> packages = systemConfig.getLinkedApps();
2639        ArraySet<String> domains = new ArraySet<String>();
2640
2641        for (String packageName : packages) {
2642            PackageParser.Package pkg = mPackages.get(packageName);
2643            if (pkg != null) {
2644                if (!pkg.isSystemApp()) {
2645                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2646                    continue;
2647                }
2648
2649                domains.clear();
2650                for (PackageParser.Activity a : pkg.activities) {
2651                    for (ActivityIntentInfo filter : a.intents) {
2652                        if (hasValidDomains(filter)) {
2653                            domains.addAll(filter.getHostsList());
2654                        }
2655                    }
2656                }
2657
2658                if (domains.size() > 0) {
2659                    if (DEBUG_DOMAIN_VERIFICATION) {
2660                        Slog.v(TAG, "      + " + packageName);
2661                    }
2662                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2663                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2664                    // and then 'always' in the per-user state actually used for intent resolution.
2665                    final IntentFilterVerificationInfo ivi;
2666                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2667                            new ArrayList<String>(domains));
2668                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2669                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2670                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2671                } else {
2672                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2673                            + "' does not handle web links");
2674                }
2675            } else {
2676                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2677            }
2678        }
2679
2680        scheduleWritePackageRestrictionsLocked(userId);
2681        scheduleWriteSettingsLocked();
2682    }
2683
2684    private void applyFactoryDefaultBrowserLPw(int userId) {
2685        // The default browser app's package name is stored in a string resource,
2686        // with a product-specific overlay used for vendor customization.
2687        String browserPkg = mContext.getResources().getString(
2688                com.android.internal.R.string.default_browser);
2689        if (!TextUtils.isEmpty(browserPkg)) {
2690            // non-empty string => required to be a known package
2691            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2692            if (ps == null) {
2693                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2694                browserPkg = null;
2695            } else {
2696                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2697            }
2698        }
2699
2700        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2701        // default.  If there's more than one, just leave everything alone.
2702        if (browserPkg == null) {
2703            calculateDefaultBrowserLPw(userId);
2704        }
2705    }
2706
2707    private void calculateDefaultBrowserLPw(int userId) {
2708        List<String> allBrowsers = resolveAllBrowserApps(userId);
2709        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2710        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2711    }
2712
2713    private List<String> resolveAllBrowserApps(int userId) {
2714        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2715        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2716                PackageManager.MATCH_ALL, userId);
2717
2718        final int count = list.size();
2719        List<String> result = new ArrayList<String>(count);
2720        for (int i=0; i<count; i++) {
2721            ResolveInfo info = list.get(i);
2722            if (info.activityInfo == null
2723                    || !info.handleAllWebDataURI
2724                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2725                    || result.contains(info.activityInfo.packageName)) {
2726                continue;
2727            }
2728            result.add(info.activityInfo.packageName);
2729        }
2730
2731        return result;
2732    }
2733
2734    private boolean packageIsBrowser(String packageName, int userId) {
2735        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2736                PackageManager.MATCH_ALL, userId);
2737        final int N = list.size();
2738        for (int i = 0; i < N; i++) {
2739            ResolveInfo info = list.get(i);
2740            if (packageName.equals(info.activityInfo.packageName)) {
2741                return true;
2742            }
2743        }
2744        return false;
2745    }
2746
2747    private void checkDefaultBrowser() {
2748        final int myUserId = UserHandle.myUserId();
2749        final String packageName = getDefaultBrowserPackageName(myUserId);
2750        if (packageName != null) {
2751            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2752            if (info == null) {
2753                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2754                synchronized (mPackages) {
2755                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2756                }
2757            }
2758        }
2759    }
2760
2761    @Override
2762    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2763            throws RemoteException {
2764        try {
2765            return super.onTransact(code, data, reply, flags);
2766        } catch (RuntimeException e) {
2767            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2768                Slog.wtf(TAG, "Package Manager Crash", e);
2769            }
2770            throw e;
2771        }
2772    }
2773
2774    void cleanupInstallFailedPackage(PackageSetting ps) {
2775        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2776
2777        removeDataDirsLI(ps.volumeUuid, ps.name);
2778        if (ps.codePath != null) {
2779            if (ps.codePath.isDirectory()) {
2780                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2781            } else {
2782                ps.codePath.delete();
2783            }
2784        }
2785        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2786            if (ps.resourcePath.isDirectory()) {
2787                FileUtils.deleteContents(ps.resourcePath);
2788            }
2789            ps.resourcePath.delete();
2790        }
2791        mSettings.removePackageLPw(ps.name);
2792    }
2793
2794    static int[] appendInts(int[] cur, int[] add) {
2795        if (add == null) return cur;
2796        if (cur == null) return add;
2797        final int N = add.length;
2798        for (int i=0; i<N; i++) {
2799            cur = appendInt(cur, add[i]);
2800        }
2801        return cur;
2802    }
2803
2804    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2805        if (!sUserManager.exists(userId)) return null;
2806        final PackageSetting ps = (PackageSetting) p.mExtras;
2807        if (ps == null) {
2808            return null;
2809        }
2810
2811        final PermissionsState permissionsState = ps.getPermissionsState();
2812
2813        final int[] gids = permissionsState.computeGids(userId);
2814        final Set<String> permissions = permissionsState.getPermissions(userId);
2815        final PackageUserState state = ps.readUserState(userId);
2816
2817        return PackageParser.generatePackageInfo(p, gids, flags,
2818                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2819    }
2820
2821    @Override
2822    public void checkPackageStartable(String packageName, int userId) {
2823        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2824
2825        synchronized (mPackages) {
2826            final PackageSetting ps = mSettings.mPackages.get(packageName);
2827            if (ps == null) {
2828                throw new SecurityException("Package " + packageName + " was not found!");
2829            }
2830
2831            if (ps.frozen) {
2832                throw new SecurityException("Package " + packageName + " is currently frozen!");
2833            }
2834
2835            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2836                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2837                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2838            }
2839        }
2840    }
2841
2842    @Override
2843    public boolean isPackageAvailable(String packageName, int userId) {
2844        if (!sUserManager.exists(userId)) return false;
2845        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2846        synchronized (mPackages) {
2847            PackageParser.Package p = mPackages.get(packageName);
2848            if (p != null) {
2849                final PackageSetting ps = (PackageSetting) p.mExtras;
2850                if (ps != null) {
2851                    final PackageUserState state = ps.readUserState(userId);
2852                    if (state != null) {
2853                        return PackageParser.isAvailable(state);
2854                    }
2855                }
2856            }
2857        }
2858        return false;
2859    }
2860
2861    @Override
2862    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2863        if (!sUserManager.exists(userId)) return null;
2864        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2865        // reader
2866        synchronized (mPackages) {
2867            PackageParser.Package p = mPackages.get(packageName);
2868            if (DEBUG_PACKAGE_INFO)
2869                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2870            if (p != null) {
2871                return generatePackageInfo(p, flags, userId);
2872            }
2873            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2874                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2875            }
2876        }
2877        return null;
2878    }
2879
2880    @Override
2881    public String[] currentToCanonicalPackageNames(String[] names) {
2882        String[] out = new String[names.length];
2883        // reader
2884        synchronized (mPackages) {
2885            for (int i=names.length-1; i>=0; i--) {
2886                PackageSetting ps = mSettings.mPackages.get(names[i]);
2887                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2888            }
2889        }
2890        return out;
2891    }
2892
2893    @Override
2894    public String[] canonicalToCurrentPackageNames(String[] names) {
2895        String[] out = new String[names.length];
2896        // reader
2897        synchronized (mPackages) {
2898            for (int i=names.length-1; i>=0; i--) {
2899                String cur = mSettings.mRenamedPackages.get(names[i]);
2900                out[i] = cur != null ? cur : names[i];
2901            }
2902        }
2903        return out;
2904    }
2905
2906    @Override
2907    public int getPackageUid(String packageName, int userId) {
2908        return getPackageUidEtc(packageName, 0, userId);
2909    }
2910
2911    @Override
2912    public int getPackageUidEtc(String packageName, int flags, int userId) {
2913        if (!sUserManager.exists(userId)) return -1;
2914        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2915
2916        // reader
2917        synchronized (mPackages) {
2918            final PackageParser.Package p = mPackages.get(packageName);
2919            if (p != null) {
2920                return UserHandle.getUid(userId, p.applicationInfo.uid);
2921            }
2922            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2923                final PackageSetting ps = mSettings.mPackages.get(packageName);
2924                if (ps != null) {
2925                    return UserHandle.getUid(userId, ps.appId);
2926                }
2927            }
2928        }
2929
2930        return -1;
2931    }
2932
2933    @Override
2934    public int[] getPackageGids(String packageName, int userId) {
2935        return getPackageGidsEtc(packageName, 0, userId);
2936    }
2937
2938    @Override
2939    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2940        if (!sUserManager.exists(userId)) {
2941            return null;
2942        }
2943
2944        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2945                "getPackageGids");
2946
2947        // reader
2948        synchronized (mPackages) {
2949            final PackageParser.Package p = mPackages.get(packageName);
2950            if (p != null) {
2951                PackageSetting ps = (PackageSetting) p.mExtras;
2952                return ps.getPermissionsState().computeGids(userId);
2953            }
2954            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2955                final PackageSetting ps = mSettings.mPackages.get(packageName);
2956                if (ps != null) {
2957                    return ps.getPermissionsState().computeGids(userId);
2958                }
2959            }
2960        }
2961
2962        return null;
2963    }
2964
2965    static PermissionInfo generatePermissionInfo(
2966            BasePermission bp, int flags) {
2967        if (bp.perm != null) {
2968            return PackageParser.generatePermissionInfo(bp.perm, flags);
2969        }
2970        PermissionInfo pi = new PermissionInfo();
2971        pi.name = bp.name;
2972        pi.packageName = bp.sourcePackage;
2973        pi.nonLocalizedLabel = bp.name;
2974        pi.protectionLevel = bp.protectionLevel;
2975        return pi;
2976    }
2977
2978    @Override
2979    public PermissionInfo getPermissionInfo(String name, int flags) {
2980        // reader
2981        synchronized (mPackages) {
2982            final BasePermission p = mSettings.mPermissions.get(name);
2983            if (p != null) {
2984                return generatePermissionInfo(p, flags);
2985            }
2986            return null;
2987        }
2988    }
2989
2990    @Override
2991    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2992        // reader
2993        synchronized (mPackages) {
2994            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2995            for (BasePermission p : mSettings.mPermissions.values()) {
2996                if (group == null) {
2997                    if (p.perm == null || p.perm.info.group == null) {
2998                        out.add(generatePermissionInfo(p, flags));
2999                    }
3000                } else {
3001                    if (p.perm != null && group.equals(p.perm.info.group)) {
3002                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3003                    }
3004                }
3005            }
3006
3007            if (out.size() > 0) {
3008                return out;
3009            }
3010            return mPermissionGroups.containsKey(group) ? out : null;
3011        }
3012    }
3013
3014    @Override
3015    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3016        // reader
3017        synchronized (mPackages) {
3018            return PackageParser.generatePermissionGroupInfo(
3019                    mPermissionGroups.get(name), flags);
3020        }
3021    }
3022
3023    @Override
3024    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3025        // reader
3026        synchronized (mPackages) {
3027            final int N = mPermissionGroups.size();
3028            ArrayList<PermissionGroupInfo> out
3029                    = new ArrayList<PermissionGroupInfo>(N);
3030            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3031                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3032            }
3033            return out;
3034        }
3035    }
3036
3037    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3038            int userId) {
3039        if (!sUserManager.exists(userId)) return null;
3040        PackageSetting ps = mSettings.mPackages.get(packageName);
3041        if (ps != null) {
3042            if (ps.pkg == null) {
3043                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3044                        flags, userId);
3045                if (pInfo != null) {
3046                    return pInfo.applicationInfo;
3047                }
3048                return null;
3049            }
3050            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3051                    ps.readUserState(userId), userId);
3052        }
3053        return null;
3054    }
3055
3056    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3057            int userId) {
3058        if (!sUserManager.exists(userId)) return null;
3059        PackageSetting ps = mSettings.mPackages.get(packageName);
3060        if (ps != null) {
3061            PackageParser.Package pkg = ps.pkg;
3062            if (pkg == null) {
3063                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3064                    return null;
3065                }
3066                // Only data remains, so we aren't worried about code paths
3067                pkg = new PackageParser.Package(packageName);
3068                pkg.applicationInfo.packageName = packageName;
3069                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3070                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3071                pkg.applicationInfo.uid = ps.appId;
3072                pkg.applicationInfo.initForUser(userId);
3073                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3074                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3075            }
3076            return generatePackageInfo(pkg, flags, userId);
3077        }
3078        return null;
3079    }
3080
3081    @Override
3082    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3083        if (!sUserManager.exists(userId)) return null;
3084        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3085        // writer
3086        synchronized (mPackages) {
3087            PackageParser.Package p = mPackages.get(packageName);
3088            if (DEBUG_PACKAGE_INFO) Log.v(
3089                    TAG, "getApplicationInfo " + packageName
3090                    + ": " + p);
3091            if (p != null) {
3092                PackageSetting ps = mSettings.mPackages.get(packageName);
3093                if (ps == null) return null;
3094                // Note: isEnabledLP() does not apply here - always return info
3095                return PackageParser.generateApplicationInfo(
3096                        p, flags, ps.readUserState(userId), userId);
3097            }
3098            if ("android".equals(packageName)||"system".equals(packageName)) {
3099                return mAndroidApplication;
3100            }
3101            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3102                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3103            }
3104        }
3105        return null;
3106    }
3107
3108    @Override
3109    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3110            final IPackageDataObserver observer) {
3111        mContext.enforceCallingOrSelfPermission(
3112                android.Manifest.permission.CLEAR_APP_CACHE, null);
3113        // Queue up an async operation since clearing cache may take a little while.
3114        mHandler.post(new Runnable() {
3115            public void run() {
3116                mHandler.removeCallbacks(this);
3117                int retCode = -1;
3118                synchronized (mInstallLock) {
3119                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3120                    if (retCode < 0) {
3121                        Slog.w(TAG, "Couldn't clear application caches");
3122                    }
3123                }
3124                if (observer != null) {
3125                    try {
3126                        observer.onRemoveCompleted(null, (retCode >= 0));
3127                    } catch (RemoteException e) {
3128                        Slog.w(TAG, "RemoveException when invoking call back");
3129                    }
3130                }
3131            }
3132        });
3133    }
3134
3135    @Override
3136    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3137            final IntentSender pi) {
3138        mContext.enforceCallingOrSelfPermission(
3139                android.Manifest.permission.CLEAR_APP_CACHE, null);
3140        // Queue up an async operation since clearing cache may take a little while.
3141        mHandler.post(new Runnable() {
3142            public void run() {
3143                mHandler.removeCallbacks(this);
3144                int retCode = -1;
3145                synchronized (mInstallLock) {
3146                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3147                    if (retCode < 0) {
3148                        Slog.w(TAG, "Couldn't clear application caches");
3149                    }
3150                }
3151                if(pi != null) {
3152                    try {
3153                        // Callback via pending intent
3154                        int code = (retCode >= 0) ? 1 : 0;
3155                        pi.sendIntent(null, code, null,
3156                                null, null);
3157                    } catch (SendIntentException e1) {
3158                        Slog.i(TAG, "Failed to send pending intent");
3159                    }
3160                }
3161            }
3162        });
3163    }
3164
3165    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3166        synchronized (mInstallLock) {
3167            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3168                throw new IOException("Failed to free enough space");
3169            }
3170        }
3171    }
3172
3173    /**
3174     * Return if the user key is currently unlocked.
3175     */
3176    private boolean isUserKeyUnlocked(int userId) {
3177        if (StorageManager.isFileBasedEncryptionEnabled()) {
3178            final IMountService mount = IMountService.Stub
3179                    .asInterface(ServiceManager.getService("mount"));
3180            if (mount == null) {
3181                Slog.w(TAG, "Early during boot, assuming locked");
3182                return false;
3183            }
3184            final long token = Binder.clearCallingIdentity();
3185            try {
3186                return mount.isUserKeyUnlocked(userId);
3187            } catch (RemoteException e) {
3188                throw e.rethrowAsRuntimeException();
3189            } finally {
3190                Binder.restoreCallingIdentity(token);
3191            }
3192        } else {
3193            return true;
3194        }
3195    }
3196
3197    /**
3198     * Augment the given flags depending on current user running state. This is
3199     * purposefully done before acquiring {@link #mPackages} lock.
3200     */
3201    private int augmentFlagsForUser(int flags, int userId) {
3202        if (!isUserKeyUnlocked(userId)) {
3203            flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3204        }
3205        return flags;
3206    }
3207
3208    @Override
3209    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3210        if (!sUserManager.exists(userId)) return null;
3211        flags = augmentFlagsForUser(flags, userId);
3212        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3213        synchronized (mPackages) {
3214            PackageParser.Activity a = mActivities.mActivities.get(component);
3215
3216            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3217            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3218                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3219                if (ps == null) return null;
3220                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3221                        userId);
3222            }
3223            if (mResolveComponentName.equals(component)) {
3224                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3225                        new PackageUserState(), userId);
3226            }
3227        }
3228        return null;
3229    }
3230
3231    @Override
3232    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3233            String resolvedType) {
3234        synchronized (mPackages) {
3235            if (component.equals(mResolveComponentName)) {
3236                // The resolver supports EVERYTHING!
3237                return true;
3238            }
3239            PackageParser.Activity a = mActivities.mActivities.get(component);
3240            if (a == null) {
3241                return false;
3242            }
3243            for (int i=0; i<a.intents.size(); i++) {
3244                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3245                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3246                    return true;
3247                }
3248            }
3249            return false;
3250        }
3251    }
3252
3253    @Override
3254    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3255        if (!sUserManager.exists(userId)) return null;
3256        flags = augmentFlagsForUser(flags, userId);
3257        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3258        synchronized (mPackages) {
3259            PackageParser.Activity a = mReceivers.mActivities.get(component);
3260            if (DEBUG_PACKAGE_INFO) Log.v(
3261                TAG, "getReceiverInfo " + component + ": " + a);
3262            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3263                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3264                if (ps == null) return null;
3265                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3266                        userId);
3267            }
3268        }
3269        return null;
3270    }
3271
3272    @Override
3273    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3274        if (!sUserManager.exists(userId)) return null;
3275        flags = augmentFlagsForUser(flags, userId);
3276        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3277        synchronized (mPackages) {
3278            PackageParser.Service s = mServices.mServices.get(component);
3279            if (DEBUG_PACKAGE_INFO) Log.v(
3280                TAG, "getServiceInfo " + component + ": " + s);
3281            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3282                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3283                if (ps == null) return null;
3284                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3285                        userId);
3286            }
3287        }
3288        return null;
3289    }
3290
3291    @Override
3292    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3293        if (!sUserManager.exists(userId)) return null;
3294        flags = augmentFlagsForUser(flags, userId);
3295        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3296        synchronized (mPackages) {
3297            PackageParser.Provider p = mProviders.mProviders.get(component);
3298            if (DEBUG_PACKAGE_INFO) Log.v(
3299                TAG, "getProviderInfo " + component + ": " + p);
3300            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3301                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3302                if (ps == null) return null;
3303                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3304                        userId);
3305            }
3306        }
3307        return null;
3308    }
3309
3310    @Override
3311    public String[] getSystemSharedLibraryNames() {
3312        Set<String> libSet;
3313        synchronized (mPackages) {
3314            libSet = mSharedLibraries.keySet();
3315            int size = libSet.size();
3316            if (size > 0) {
3317                String[] libs = new String[size];
3318                libSet.toArray(libs);
3319                return libs;
3320            }
3321        }
3322        return null;
3323    }
3324
3325    /**
3326     * @hide
3327     */
3328    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3329        synchronized (mPackages) {
3330            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3331            if (lib != null && lib.apk != null) {
3332                return mPackages.get(lib.apk);
3333            }
3334        }
3335        return null;
3336    }
3337
3338    @Override
3339    public FeatureInfo[] getSystemAvailableFeatures() {
3340        Collection<FeatureInfo> featSet;
3341        synchronized (mPackages) {
3342            featSet = mAvailableFeatures.values();
3343            int size = featSet.size();
3344            if (size > 0) {
3345                FeatureInfo[] features = new FeatureInfo[size+1];
3346                featSet.toArray(features);
3347                FeatureInfo fi = new FeatureInfo();
3348                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3349                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3350                features[size] = fi;
3351                return features;
3352            }
3353        }
3354        return null;
3355    }
3356
3357    @Override
3358    public boolean hasSystemFeature(String name) {
3359        synchronized (mPackages) {
3360            return mAvailableFeatures.containsKey(name);
3361        }
3362    }
3363
3364    private void checkValidCaller(int uid, int userId) {
3365        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3366            return;
3367
3368        throw new SecurityException("Caller uid=" + uid
3369                + " is not privileged to communicate with user=" + userId);
3370    }
3371
3372    @Override
3373    public int checkPermission(String permName, String pkgName, int userId) {
3374        if (!sUserManager.exists(userId)) {
3375            return PackageManager.PERMISSION_DENIED;
3376        }
3377
3378        synchronized (mPackages) {
3379            final PackageParser.Package p = mPackages.get(pkgName);
3380            if (p != null && p.mExtras != null) {
3381                final PackageSetting ps = (PackageSetting) p.mExtras;
3382                final PermissionsState permissionsState = ps.getPermissionsState();
3383                if (permissionsState.hasPermission(permName, userId)) {
3384                    return PackageManager.PERMISSION_GRANTED;
3385                }
3386                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3387                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3388                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3389                    return PackageManager.PERMISSION_GRANTED;
3390                }
3391            }
3392        }
3393
3394        return PackageManager.PERMISSION_DENIED;
3395    }
3396
3397    @Override
3398    public int checkUidPermission(String permName, int uid) {
3399        final int userId = UserHandle.getUserId(uid);
3400
3401        if (!sUserManager.exists(userId)) {
3402            return PackageManager.PERMISSION_DENIED;
3403        }
3404
3405        synchronized (mPackages) {
3406            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3407            if (obj != null) {
3408                final SettingBase ps = (SettingBase) obj;
3409                final PermissionsState permissionsState = ps.getPermissionsState();
3410                if (permissionsState.hasPermission(permName, userId)) {
3411                    return PackageManager.PERMISSION_GRANTED;
3412                }
3413                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3414                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3415                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3416                    return PackageManager.PERMISSION_GRANTED;
3417                }
3418            } else {
3419                ArraySet<String> perms = mSystemPermissions.get(uid);
3420                if (perms != null) {
3421                    if (perms.contains(permName)) {
3422                        return PackageManager.PERMISSION_GRANTED;
3423                    }
3424                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3425                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3426                        return PackageManager.PERMISSION_GRANTED;
3427                    }
3428                }
3429            }
3430        }
3431
3432        return PackageManager.PERMISSION_DENIED;
3433    }
3434
3435    @Override
3436    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3437        if (UserHandle.getCallingUserId() != userId) {
3438            mContext.enforceCallingPermission(
3439                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3440                    "isPermissionRevokedByPolicy for user " + userId);
3441        }
3442
3443        if (checkPermission(permission, packageName, userId)
3444                == PackageManager.PERMISSION_GRANTED) {
3445            return false;
3446        }
3447
3448        final long identity = Binder.clearCallingIdentity();
3449        try {
3450            final int flags = getPermissionFlags(permission, packageName, userId);
3451            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3452        } finally {
3453            Binder.restoreCallingIdentity(identity);
3454        }
3455    }
3456
3457    @Override
3458    public String getPermissionControllerPackageName() {
3459        synchronized (mPackages) {
3460            return mRequiredInstallerPackage;
3461        }
3462    }
3463
3464    /**
3465     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3466     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3467     * @param checkShell TODO(yamasani):
3468     * @param message the message to log on security exception
3469     */
3470    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3471            boolean checkShell, String message) {
3472        if (userId < 0) {
3473            throw new IllegalArgumentException("Invalid userId " + userId);
3474        }
3475        if (checkShell) {
3476            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3477        }
3478        if (userId == UserHandle.getUserId(callingUid)) return;
3479        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3480            if (requireFullPermission) {
3481                mContext.enforceCallingOrSelfPermission(
3482                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3483            } else {
3484                try {
3485                    mContext.enforceCallingOrSelfPermission(
3486                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3487                } catch (SecurityException se) {
3488                    mContext.enforceCallingOrSelfPermission(
3489                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3490                }
3491            }
3492        }
3493    }
3494
3495    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3496        if (callingUid == Process.SHELL_UID) {
3497            if (userHandle >= 0
3498                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3499                throw new SecurityException("Shell does not have permission to access user "
3500                        + userHandle);
3501            } else if (userHandle < 0) {
3502                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3503                        + Debug.getCallers(3));
3504            }
3505        }
3506    }
3507
3508    private BasePermission findPermissionTreeLP(String permName) {
3509        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3510            if (permName.startsWith(bp.name) &&
3511                    permName.length() > bp.name.length() &&
3512                    permName.charAt(bp.name.length()) == '.') {
3513                return bp;
3514            }
3515        }
3516        return null;
3517    }
3518
3519    private BasePermission checkPermissionTreeLP(String permName) {
3520        if (permName != null) {
3521            BasePermission bp = findPermissionTreeLP(permName);
3522            if (bp != null) {
3523                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3524                    return bp;
3525                }
3526                throw new SecurityException("Calling uid "
3527                        + Binder.getCallingUid()
3528                        + " is not allowed to add to permission tree "
3529                        + bp.name + " owned by uid " + bp.uid);
3530            }
3531        }
3532        throw new SecurityException("No permission tree found for " + permName);
3533    }
3534
3535    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3536        if (s1 == null) {
3537            return s2 == null;
3538        }
3539        if (s2 == null) {
3540            return false;
3541        }
3542        if (s1.getClass() != s2.getClass()) {
3543            return false;
3544        }
3545        return s1.equals(s2);
3546    }
3547
3548    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3549        if (pi1.icon != pi2.icon) return false;
3550        if (pi1.logo != pi2.logo) return false;
3551        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3552        if (!compareStrings(pi1.name, pi2.name)) return false;
3553        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3554        // We'll take care of setting this one.
3555        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3556        // These are not currently stored in settings.
3557        //if (!compareStrings(pi1.group, pi2.group)) return false;
3558        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3559        //if (pi1.labelRes != pi2.labelRes) return false;
3560        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3561        return true;
3562    }
3563
3564    int permissionInfoFootprint(PermissionInfo info) {
3565        int size = info.name.length();
3566        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3567        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3568        return size;
3569    }
3570
3571    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3572        int size = 0;
3573        for (BasePermission perm : mSettings.mPermissions.values()) {
3574            if (perm.uid == tree.uid) {
3575                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3576            }
3577        }
3578        return size;
3579    }
3580
3581    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3582        // We calculate the max size of permissions defined by this uid and throw
3583        // if that plus the size of 'info' would exceed our stated maximum.
3584        if (tree.uid != Process.SYSTEM_UID) {
3585            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3586            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3587                throw new SecurityException("Permission tree size cap exceeded");
3588            }
3589        }
3590    }
3591
3592    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3593        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3594            throw new SecurityException("Label must be specified in permission");
3595        }
3596        BasePermission tree = checkPermissionTreeLP(info.name);
3597        BasePermission bp = mSettings.mPermissions.get(info.name);
3598        boolean added = bp == null;
3599        boolean changed = true;
3600        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3601        if (added) {
3602            enforcePermissionCapLocked(info, tree);
3603            bp = new BasePermission(info.name, tree.sourcePackage,
3604                    BasePermission.TYPE_DYNAMIC);
3605        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3606            throw new SecurityException(
3607                    "Not allowed to modify non-dynamic permission "
3608                    + info.name);
3609        } else {
3610            if (bp.protectionLevel == fixedLevel
3611                    && bp.perm.owner.equals(tree.perm.owner)
3612                    && bp.uid == tree.uid
3613                    && comparePermissionInfos(bp.perm.info, info)) {
3614                changed = false;
3615            }
3616        }
3617        bp.protectionLevel = fixedLevel;
3618        info = new PermissionInfo(info);
3619        info.protectionLevel = fixedLevel;
3620        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3621        bp.perm.info.packageName = tree.perm.info.packageName;
3622        bp.uid = tree.uid;
3623        if (added) {
3624            mSettings.mPermissions.put(info.name, bp);
3625        }
3626        if (changed) {
3627            if (!async) {
3628                mSettings.writeLPr();
3629            } else {
3630                scheduleWriteSettingsLocked();
3631            }
3632        }
3633        return added;
3634    }
3635
3636    @Override
3637    public boolean addPermission(PermissionInfo info) {
3638        synchronized (mPackages) {
3639            return addPermissionLocked(info, false);
3640        }
3641    }
3642
3643    @Override
3644    public boolean addPermissionAsync(PermissionInfo info) {
3645        synchronized (mPackages) {
3646            return addPermissionLocked(info, true);
3647        }
3648    }
3649
3650    @Override
3651    public void removePermission(String name) {
3652        synchronized (mPackages) {
3653            checkPermissionTreeLP(name);
3654            BasePermission bp = mSettings.mPermissions.get(name);
3655            if (bp != null) {
3656                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3657                    throw new SecurityException(
3658                            "Not allowed to modify non-dynamic permission "
3659                            + name);
3660                }
3661                mSettings.mPermissions.remove(name);
3662                mSettings.writeLPr();
3663            }
3664        }
3665    }
3666
3667    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3668            BasePermission bp) {
3669        int index = pkg.requestedPermissions.indexOf(bp.name);
3670        if (index == -1) {
3671            throw new SecurityException("Package " + pkg.packageName
3672                    + " has not requested permission " + bp.name);
3673        }
3674        if (!bp.isRuntime() && !bp.isDevelopment()) {
3675            throw new SecurityException("Permission " + bp.name
3676                    + " is not a changeable permission type");
3677        }
3678    }
3679
3680    @Override
3681    public void grantRuntimePermission(String packageName, String name, final int userId) {
3682        if (!sUserManager.exists(userId)) {
3683            Log.e(TAG, "No such user:" + userId);
3684            return;
3685        }
3686
3687        mContext.enforceCallingOrSelfPermission(
3688                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3689                "grantRuntimePermission");
3690
3691        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3692                "grantRuntimePermission");
3693
3694        final int uid;
3695        final SettingBase sb;
3696
3697        synchronized (mPackages) {
3698            final PackageParser.Package pkg = mPackages.get(packageName);
3699            if (pkg == null) {
3700                throw new IllegalArgumentException("Unknown package: " + packageName);
3701            }
3702
3703            final BasePermission bp = mSettings.mPermissions.get(name);
3704            if (bp == null) {
3705                throw new IllegalArgumentException("Unknown permission: " + name);
3706            }
3707
3708            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3709
3710            // If a permission review is required for legacy apps we represent
3711            // their permissions as always granted runtime ones since we need
3712            // to keep the review required permission flag per user while an
3713            // install permission's state is shared across all users.
3714            if (Build.PERMISSIONS_REVIEW_REQUIRED
3715                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3716                    && bp.isRuntime()) {
3717                return;
3718            }
3719
3720            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3721            sb = (SettingBase) pkg.mExtras;
3722            if (sb == null) {
3723                throw new IllegalArgumentException("Unknown package: " + packageName);
3724            }
3725
3726            final PermissionsState permissionsState = sb.getPermissionsState();
3727
3728            final int flags = permissionsState.getPermissionFlags(name, userId);
3729            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3730                throw new SecurityException("Cannot grant system fixed permission: "
3731                        + name + " for package: " + packageName);
3732            }
3733
3734            if (bp.isDevelopment()) {
3735                // Development permissions must be handled specially, since they are not
3736                // normal runtime permissions.  For now they apply to all users.
3737                if (permissionsState.grantInstallPermission(bp) !=
3738                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3739                    scheduleWriteSettingsLocked();
3740                }
3741                return;
3742            }
3743
3744            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3745                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3746                return;
3747            }
3748
3749            final int result = permissionsState.grantRuntimePermission(bp, userId);
3750            switch (result) {
3751                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3752                    return;
3753                }
3754
3755                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3756                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3757                    mHandler.post(new Runnable() {
3758                        @Override
3759                        public void run() {
3760                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3761                        }
3762                    });
3763                }
3764                break;
3765            }
3766
3767            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3768
3769            // Not critical if that is lost - app has to request again.
3770            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3771        }
3772
3773        // Only need to do this if user is initialized. Otherwise it's a new user
3774        // and there are no processes running as the user yet and there's no need
3775        // to make an expensive call to remount processes for the changed permissions.
3776        if (READ_EXTERNAL_STORAGE.equals(name)
3777                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3778            final long token = Binder.clearCallingIdentity();
3779            try {
3780                if (sUserManager.isInitialized(userId)) {
3781                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3782                            MountServiceInternal.class);
3783                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3784                }
3785            } finally {
3786                Binder.restoreCallingIdentity(token);
3787            }
3788        }
3789    }
3790
3791    @Override
3792    public void revokeRuntimePermission(String packageName, String name, int userId) {
3793        if (!sUserManager.exists(userId)) {
3794            Log.e(TAG, "No such user:" + userId);
3795            return;
3796        }
3797
3798        mContext.enforceCallingOrSelfPermission(
3799                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3800                "revokeRuntimePermission");
3801
3802        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3803                "revokeRuntimePermission");
3804
3805        final int appId;
3806
3807        synchronized (mPackages) {
3808            final PackageParser.Package pkg = mPackages.get(packageName);
3809            if (pkg == null) {
3810                throw new IllegalArgumentException("Unknown package: " + packageName);
3811            }
3812
3813            final BasePermission bp = mSettings.mPermissions.get(name);
3814            if (bp == null) {
3815                throw new IllegalArgumentException("Unknown permission: " + name);
3816            }
3817
3818            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3819
3820            // If a permission review is required for legacy apps we represent
3821            // their permissions as always granted runtime ones since we need
3822            // to keep the review required permission flag per user while an
3823            // install permission's state is shared across all users.
3824            if (Build.PERMISSIONS_REVIEW_REQUIRED
3825                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3826                    && bp.isRuntime()) {
3827                return;
3828            }
3829
3830            SettingBase sb = (SettingBase) pkg.mExtras;
3831            if (sb == null) {
3832                throw new IllegalArgumentException("Unknown package: " + packageName);
3833            }
3834
3835            final PermissionsState permissionsState = sb.getPermissionsState();
3836
3837            final int flags = permissionsState.getPermissionFlags(name, userId);
3838            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3839                throw new SecurityException("Cannot revoke system fixed permission: "
3840                        + name + " for package: " + packageName);
3841            }
3842
3843            if (bp.isDevelopment()) {
3844                // Development permissions must be handled specially, since they are not
3845                // normal runtime permissions.  For now they apply to all users.
3846                if (permissionsState.revokeInstallPermission(bp) !=
3847                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3848                    scheduleWriteSettingsLocked();
3849                }
3850                return;
3851            }
3852
3853            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3854                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3855                return;
3856            }
3857
3858            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3859
3860            // Critical, after this call app should never have the permission.
3861            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3862
3863            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3864        }
3865
3866        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3867    }
3868
3869    @Override
3870    public void resetRuntimePermissions() {
3871        mContext.enforceCallingOrSelfPermission(
3872                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3873                "revokeRuntimePermission");
3874
3875        int callingUid = Binder.getCallingUid();
3876        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3877            mContext.enforceCallingOrSelfPermission(
3878                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3879                    "resetRuntimePermissions");
3880        }
3881
3882        synchronized (mPackages) {
3883            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3884            for (int userId : UserManagerService.getInstance().getUserIds()) {
3885                final int packageCount = mPackages.size();
3886                for (int i = 0; i < packageCount; i++) {
3887                    PackageParser.Package pkg = mPackages.valueAt(i);
3888                    if (!(pkg.mExtras instanceof PackageSetting)) {
3889                        continue;
3890                    }
3891                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3892                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3893                }
3894            }
3895        }
3896    }
3897
3898    @Override
3899    public int getPermissionFlags(String name, String packageName, int userId) {
3900        if (!sUserManager.exists(userId)) {
3901            return 0;
3902        }
3903
3904        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3905
3906        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3907                "getPermissionFlags");
3908
3909        synchronized (mPackages) {
3910            final PackageParser.Package pkg = mPackages.get(packageName);
3911            if (pkg == null) {
3912                throw new IllegalArgumentException("Unknown package: " + packageName);
3913            }
3914
3915            final BasePermission bp = mSettings.mPermissions.get(name);
3916            if (bp == null) {
3917                throw new IllegalArgumentException("Unknown permission: " + name);
3918            }
3919
3920            SettingBase sb = (SettingBase) pkg.mExtras;
3921            if (sb == null) {
3922                throw new IllegalArgumentException("Unknown package: " + packageName);
3923            }
3924
3925            PermissionsState permissionsState = sb.getPermissionsState();
3926            return permissionsState.getPermissionFlags(name, userId);
3927        }
3928    }
3929
3930    @Override
3931    public void updatePermissionFlags(String name, String packageName, int flagMask,
3932            int flagValues, int userId) {
3933        if (!sUserManager.exists(userId)) {
3934            return;
3935        }
3936
3937        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3938
3939        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3940                "updatePermissionFlags");
3941
3942        // Only the system can change these flags and nothing else.
3943        if (getCallingUid() != Process.SYSTEM_UID) {
3944            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3945            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3946            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3947            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3948            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3949        }
3950
3951        synchronized (mPackages) {
3952            final PackageParser.Package pkg = mPackages.get(packageName);
3953            if (pkg == null) {
3954                throw new IllegalArgumentException("Unknown package: " + packageName);
3955            }
3956
3957            final BasePermission bp = mSettings.mPermissions.get(name);
3958            if (bp == null) {
3959                throw new IllegalArgumentException("Unknown permission: " + name);
3960            }
3961
3962            SettingBase sb = (SettingBase) pkg.mExtras;
3963            if (sb == null) {
3964                throw new IllegalArgumentException("Unknown package: " + packageName);
3965            }
3966
3967            PermissionsState permissionsState = sb.getPermissionsState();
3968
3969            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3970
3971            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3972                // Install and runtime permissions are stored in different places,
3973                // so figure out what permission changed and persist the change.
3974                if (permissionsState.getInstallPermissionState(name) != null) {
3975                    scheduleWriteSettingsLocked();
3976                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3977                        || hadState) {
3978                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3979                }
3980            }
3981        }
3982    }
3983
3984    /**
3985     * Update the permission flags for all packages and runtime permissions of a user in order
3986     * to allow device or profile owner to remove POLICY_FIXED.
3987     */
3988    @Override
3989    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3990        if (!sUserManager.exists(userId)) {
3991            return;
3992        }
3993
3994        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3995
3996        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3997                "updatePermissionFlagsForAllApps");
3998
3999        // Only the system can change system fixed flags.
4000        if (getCallingUid() != Process.SYSTEM_UID) {
4001            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4002            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4003        }
4004
4005        synchronized (mPackages) {
4006            boolean changed = false;
4007            final int packageCount = mPackages.size();
4008            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4009                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4010                SettingBase sb = (SettingBase) pkg.mExtras;
4011                if (sb == null) {
4012                    continue;
4013                }
4014                PermissionsState permissionsState = sb.getPermissionsState();
4015                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4016                        userId, flagMask, flagValues);
4017            }
4018            if (changed) {
4019                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4020            }
4021        }
4022    }
4023
4024    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4025        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4026                != PackageManager.PERMISSION_GRANTED
4027            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4028                != PackageManager.PERMISSION_GRANTED) {
4029            throw new SecurityException(message + " requires "
4030                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4031                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4032        }
4033    }
4034
4035    @Override
4036    public boolean shouldShowRequestPermissionRationale(String permissionName,
4037            String packageName, int userId) {
4038        if (UserHandle.getCallingUserId() != userId) {
4039            mContext.enforceCallingPermission(
4040                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4041                    "canShowRequestPermissionRationale for user " + userId);
4042        }
4043
4044        final int uid = getPackageUid(packageName, userId);
4045        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4046            return false;
4047        }
4048
4049        if (checkPermission(permissionName, packageName, userId)
4050                == PackageManager.PERMISSION_GRANTED) {
4051            return false;
4052        }
4053
4054        final int flags;
4055
4056        final long identity = Binder.clearCallingIdentity();
4057        try {
4058            flags = getPermissionFlags(permissionName,
4059                    packageName, userId);
4060        } finally {
4061            Binder.restoreCallingIdentity(identity);
4062        }
4063
4064        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4065                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4066                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4067
4068        if ((flags & fixedFlags) != 0) {
4069            return false;
4070        }
4071
4072        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4073    }
4074
4075    @Override
4076    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4077        mContext.enforceCallingOrSelfPermission(
4078                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4079                "addOnPermissionsChangeListener");
4080
4081        synchronized (mPackages) {
4082            mOnPermissionChangeListeners.addListenerLocked(listener);
4083        }
4084    }
4085
4086    @Override
4087    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4088        synchronized (mPackages) {
4089            mOnPermissionChangeListeners.removeListenerLocked(listener);
4090        }
4091    }
4092
4093    @Override
4094    public boolean isProtectedBroadcast(String actionName) {
4095        synchronized (mPackages) {
4096            if (mProtectedBroadcasts.contains(actionName)) {
4097                return true;
4098            } else if (actionName != null
4099                    && actionName.startsWith("android.net.netmon.lingerExpired")) {
4100                // TODO: remove this terrible hack
4101                return true;
4102            }
4103        }
4104        return false;
4105    }
4106
4107    @Override
4108    public int checkSignatures(String pkg1, String pkg2) {
4109        synchronized (mPackages) {
4110            final PackageParser.Package p1 = mPackages.get(pkg1);
4111            final PackageParser.Package p2 = mPackages.get(pkg2);
4112            if (p1 == null || p1.mExtras == null
4113                    || p2 == null || p2.mExtras == null) {
4114                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4115            }
4116            return compareSignatures(p1.mSignatures, p2.mSignatures);
4117        }
4118    }
4119
4120    @Override
4121    public int checkUidSignatures(int uid1, int uid2) {
4122        // Map to base uids.
4123        uid1 = UserHandle.getAppId(uid1);
4124        uid2 = UserHandle.getAppId(uid2);
4125        // reader
4126        synchronized (mPackages) {
4127            Signature[] s1;
4128            Signature[] s2;
4129            Object obj = mSettings.getUserIdLPr(uid1);
4130            if (obj != null) {
4131                if (obj instanceof SharedUserSetting) {
4132                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4133                } else if (obj instanceof PackageSetting) {
4134                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4135                } else {
4136                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4137                }
4138            } else {
4139                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4140            }
4141            obj = mSettings.getUserIdLPr(uid2);
4142            if (obj != null) {
4143                if (obj instanceof SharedUserSetting) {
4144                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4145                } else if (obj instanceof PackageSetting) {
4146                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4147                } else {
4148                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4149                }
4150            } else {
4151                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4152            }
4153            return compareSignatures(s1, s2);
4154        }
4155    }
4156
4157    private void killUid(int appId, int userId, String reason) {
4158        final long identity = Binder.clearCallingIdentity();
4159        try {
4160            IActivityManager am = ActivityManagerNative.getDefault();
4161            if (am != null) {
4162                try {
4163                    am.killUid(appId, userId, reason);
4164                } catch (RemoteException e) {
4165                    /* ignore - same process */
4166                }
4167            }
4168        } finally {
4169            Binder.restoreCallingIdentity(identity);
4170        }
4171    }
4172
4173    /**
4174     * Compares two sets of signatures. Returns:
4175     * <br />
4176     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4177     * <br />
4178     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4179     * <br />
4180     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4181     * <br />
4182     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4183     * <br />
4184     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4185     */
4186    static int compareSignatures(Signature[] s1, Signature[] s2) {
4187        if (s1 == null) {
4188            return s2 == null
4189                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4190                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4191        }
4192
4193        if (s2 == null) {
4194            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4195        }
4196
4197        if (s1.length != s2.length) {
4198            return PackageManager.SIGNATURE_NO_MATCH;
4199        }
4200
4201        // Since both signature sets are of size 1, we can compare without HashSets.
4202        if (s1.length == 1) {
4203            return s1[0].equals(s2[0]) ?
4204                    PackageManager.SIGNATURE_MATCH :
4205                    PackageManager.SIGNATURE_NO_MATCH;
4206        }
4207
4208        ArraySet<Signature> set1 = new ArraySet<Signature>();
4209        for (Signature sig : s1) {
4210            set1.add(sig);
4211        }
4212        ArraySet<Signature> set2 = new ArraySet<Signature>();
4213        for (Signature sig : s2) {
4214            set2.add(sig);
4215        }
4216        // Make sure s2 contains all signatures in s1.
4217        if (set1.equals(set2)) {
4218            return PackageManager.SIGNATURE_MATCH;
4219        }
4220        return PackageManager.SIGNATURE_NO_MATCH;
4221    }
4222
4223    /**
4224     * If the database version for this type of package (internal storage or
4225     * external storage) is less than the version where package signatures
4226     * were updated, return true.
4227     */
4228    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4229        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4230        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4231    }
4232
4233    /**
4234     * Used for backward compatibility to make sure any packages with
4235     * certificate chains get upgraded to the new style. {@code existingSigs}
4236     * will be in the old format (since they were stored on disk from before the
4237     * system upgrade) and {@code scannedSigs} will be in the newer format.
4238     */
4239    private int compareSignaturesCompat(PackageSignatures existingSigs,
4240            PackageParser.Package scannedPkg) {
4241        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4242            return PackageManager.SIGNATURE_NO_MATCH;
4243        }
4244
4245        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4246        for (Signature sig : existingSigs.mSignatures) {
4247            existingSet.add(sig);
4248        }
4249        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4250        for (Signature sig : scannedPkg.mSignatures) {
4251            try {
4252                Signature[] chainSignatures = sig.getChainSignatures();
4253                for (Signature chainSig : chainSignatures) {
4254                    scannedCompatSet.add(chainSig);
4255                }
4256            } catch (CertificateEncodingException e) {
4257                scannedCompatSet.add(sig);
4258            }
4259        }
4260        /*
4261         * Make sure the expanded scanned set contains all signatures in the
4262         * existing one.
4263         */
4264        if (scannedCompatSet.equals(existingSet)) {
4265            // Migrate the old signatures to the new scheme.
4266            existingSigs.assignSignatures(scannedPkg.mSignatures);
4267            // The new KeySets will be re-added later in the scanning process.
4268            synchronized (mPackages) {
4269                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4270            }
4271            return PackageManager.SIGNATURE_MATCH;
4272        }
4273        return PackageManager.SIGNATURE_NO_MATCH;
4274    }
4275
4276    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4277        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4278        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4279    }
4280
4281    private int compareSignaturesRecover(PackageSignatures existingSigs,
4282            PackageParser.Package scannedPkg) {
4283        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4284            return PackageManager.SIGNATURE_NO_MATCH;
4285        }
4286
4287        String msg = null;
4288        try {
4289            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4290                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4291                        + scannedPkg.packageName);
4292                return PackageManager.SIGNATURE_MATCH;
4293            }
4294        } catch (CertificateException e) {
4295            msg = e.getMessage();
4296        }
4297
4298        logCriticalInfo(Log.INFO,
4299                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4300        return PackageManager.SIGNATURE_NO_MATCH;
4301    }
4302
4303    @Override
4304    public String[] getPackagesForUid(int uid) {
4305        uid = UserHandle.getAppId(uid);
4306        // reader
4307        synchronized (mPackages) {
4308            Object obj = mSettings.getUserIdLPr(uid);
4309            if (obj instanceof SharedUserSetting) {
4310                final SharedUserSetting sus = (SharedUserSetting) obj;
4311                final int N = sus.packages.size();
4312                final String[] res = new String[N];
4313                final Iterator<PackageSetting> it = sus.packages.iterator();
4314                int i = 0;
4315                while (it.hasNext()) {
4316                    res[i++] = it.next().name;
4317                }
4318                return res;
4319            } else if (obj instanceof PackageSetting) {
4320                final PackageSetting ps = (PackageSetting) obj;
4321                return new String[] { ps.name };
4322            }
4323        }
4324        return null;
4325    }
4326
4327    @Override
4328    public String getNameForUid(int uid) {
4329        // reader
4330        synchronized (mPackages) {
4331            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4332            if (obj instanceof SharedUserSetting) {
4333                final SharedUserSetting sus = (SharedUserSetting) obj;
4334                return sus.name + ":" + sus.userId;
4335            } else if (obj instanceof PackageSetting) {
4336                final PackageSetting ps = (PackageSetting) obj;
4337                return ps.name;
4338            }
4339        }
4340        return null;
4341    }
4342
4343    @Override
4344    public int getUidForSharedUser(String sharedUserName) {
4345        if(sharedUserName == null) {
4346            return -1;
4347        }
4348        // reader
4349        synchronized (mPackages) {
4350            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4351            if (suid == null) {
4352                return -1;
4353            }
4354            return suid.userId;
4355        }
4356    }
4357
4358    @Override
4359    public int getFlagsForUid(int uid) {
4360        synchronized (mPackages) {
4361            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4362            if (obj instanceof SharedUserSetting) {
4363                final SharedUserSetting sus = (SharedUserSetting) obj;
4364                return sus.pkgFlags;
4365            } else if (obj instanceof PackageSetting) {
4366                final PackageSetting ps = (PackageSetting) obj;
4367                return ps.pkgFlags;
4368            }
4369        }
4370        return 0;
4371    }
4372
4373    @Override
4374    public int getPrivateFlagsForUid(int uid) {
4375        synchronized (mPackages) {
4376            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4377            if (obj instanceof SharedUserSetting) {
4378                final SharedUserSetting sus = (SharedUserSetting) obj;
4379                return sus.pkgPrivateFlags;
4380            } else if (obj instanceof PackageSetting) {
4381                final PackageSetting ps = (PackageSetting) obj;
4382                return ps.pkgPrivateFlags;
4383            }
4384        }
4385        return 0;
4386    }
4387
4388    @Override
4389    public boolean isUidPrivileged(int uid) {
4390        uid = UserHandle.getAppId(uid);
4391        // reader
4392        synchronized (mPackages) {
4393            Object obj = mSettings.getUserIdLPr(uid);
4394            if (obj instanceof SharedUserSetting) {
4395                final SharedUserSetting sus = (SharedUserSetting) obj;
4396                final Iterator<PackageSetting> it = sus.packages.iterator();
4397                while (it.hasNext()) {
4398                    if (it.next().isPrivileged()) {
4399                        return true;
4400                    }
4401                }
4402            } else if (obj instanceof PackageSetting) {
4403                final PackageSetting ps = (PackageSetting) obj;
4404                return ps.isPrivileged();
4405            }
4406        }
4407        return false;
4408    }
4409
4410    @Override
4411    public String[] getAppOpPermissionPackages(String permissionName) {
4412        synchronized (mPackages) {
4413            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4414            if (pkgs == null) {
4415                return null;
4416            }
4417            return pkgs.toArray(new String[pkgs.size()]);
4418        }
4419    }
4420
4421    @Override
4422    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4423            int flags, int userId) {
4424        if (!sUserManager.exists(userId)) return null;
4425        flags = augmentFlagsForUser(flags, userId);
4426        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4427        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4428        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4429    }
4430
4431    @Override
4432    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4433            IntentFilter filter, int match, ComponentName activity) {
4434        final int userId = UserHandle.getCallingUserId();
4435        if (DEBUG_PREFERRED) {
4436            Log.v(TAG, "setLastChosenActivity intent=" + intent
4437                + " resolvedType=" + resolvedType
4438                + " flags=" + flags
4439                + " filter=" + filter
4440                + " match=" + match
4441                + " activity=" + activity);
4442            filter.dump(new PrintStreamPrinter(System.out), "    ");
4443        }
4444        intent.setComponent(null);
4445        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4446        // Find any earlier preferred or last chosen entries and nuke them
4447        findPreferredActivity(intent, resolvedType,
4448                flags, query, 0, false, true, false, userId);
4449        // Add the new activity as the last chosen for this filter
4450        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4451                "Setting last chosen");
4452    }
4453
4454    @Override
4455    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4456        final int userId = UserHandle.getCallingUserId();
4457        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4458        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4459        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4460                false, false, false, userId);
4461    }
4462
4463    private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) {
4464        MessageDigest digest = null;
4465        try {
4466            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4467        } catch (NoSuchAlgorithmException e) {
4468            // If we can't create a digest, ignore ephemeral apps.
4469            return false;
4470        }
4471
4472        final byte[] hostBytes = intent.getData().getHost().getBytes();
4473        final byte[] digestBytes = digest.digest(hostBytes);
4474        int shaPrefix =
4475                digestBytes[0] << 24
4476                | digestBytes[1] << 16
4477                | digestBytes[2] << 8
4478                | digestBytes[3] << 0;
4479        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4480                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4481        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4482            // No hash prefix match; there are no ephemeral apps for this domain.
4483            return false;
4484        }
4485        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4486            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4487            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4488                continue;
4489            }
4490            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4491            // No filters; this should never happen.
4492            if (filters.isEmpty()) {
4493                continue;
4494            }
4495            // We have a domain match; resolve the filters to see if anything matches.
4496            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4497            for (int j = filters.size() - 1; j >= 0; --j) {
4498                ephemeralResolver.addFilter(filters.get(j));
4499            }
4500            List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent(
4501                    intent, resolvedType, false /*defaultOnly*/, userId);
4502            return !ephemeralResolveList.isEmpty();
4503        }
4504        // Hash or filter mis-match; no ephemeral apps for this domain.
4505        return false;
4506    }
4507
4508    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4509            int flags, List<ResolveInfo> query, int userId) {
4510        final boolean isWebUri = hasWebURI(intent);
4511        // Check whether or not an ephemeral app exists to handle the URI.
4512        if (isWebUri && mEphemeralResolverConnection != null) {
4513            // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution.
4514            boolean hasAlwaysHandler = false;
4515            synchronized (mPackages) {
4516                final int count = query.size();
4517                for (int n=0; n<count; n++) {
4518                    ResolveInfo info = query.get(n);
4519                    String packageName = info.activityInfo.packageName;
4520                    PackageSetting ps = mSettings.mPackages.get(packageName);
4521                    if (ps != null) {
4522                        // Try to get the status from User settings first
4523                        long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4524                        int status = (int) (packedStatus >> 32);
4525                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4526                                || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4527                            hasAlwaysHandler = true;
4528                            break;
4529                        }
4530                    }
4531                }
4532            }
4533
4534            // Only consider installing an ephemeral app if there isn't already a verified handler.
4535            // We've determined that there's an ephemeral app available for the URI, ignore any
4536            // ResolveInfo's and just return the ephemeral installer
4537            if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) {
4538                if (DEBUG_EPHEMERAL) {
4539                    Slog.v(TAG, "Resolving to the ephemeral installer");
4540                }
4541                // ditch the result and return a ResolveInfo to launch the ephemeral installer
4542                ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo);
4543                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4544                // make a deep copy of the applicationInfo
4545                ri.activityInfo.applicationInfo = new ApplicationInfo(
4546                        ri.activityInfo.applicationInfo);
4547                if (userId != 0) {
4548                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4549                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4550                }
4551                return ri;
4552            }
4553        }
4554        if (query != null) {
4555            final int N = query.size();
4556            if (N == 1) {
4557                return query.get(0);
4558            } else if (N > 1) {
4559                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4560                // If there is more than one activity with the same priority,
4561                // then let the user decide between them.
4562                ResolveInfo r0 = query.get(0);
4563                ResolveInfo r1 = query.get(1);
4564                if (DEBUG_INTENT_MATCHING || debug) {
4565                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4566                            + r1.activityInfo.name + "=" + r1.priority);
4567                }
4568                // If the first activity has a higher priority, or a different
4569                // default, then it is always desireable to pick it.
4570                if (r0.priority != r1.priority
4571                        || r0.preferredOrder != r1.preferredOrder
4572                        || r0.isDefault != r1.isDefault) {
4573                    return query.get(0);
4574                }
4575                // If we have saved a preference for a preferred activity for
4576                // this Intent, use that.
4577                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4578                        flags, query, r0.priority, true, false, debug, userId);
4579                if (ri != null) {
4580                    return ri;
4581                }
4582                ri = new ResolveInfo(mResolveInfo);
4583                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4584                ri.activityInfo.applicationInfo = new ApplicationInfo(
4585                        ri.activityInfo.applicationInfo);
4586                if (userId != 0) {
4587                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4588                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4589                }
4590                // Make sure that the resolver is displayable in car mode
4591                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4592                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4593                return ri;
4594            }
4595        }
4596        return null;
4597    }
4598
4599    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4600            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4601        final int N = query.size();
4602        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4603                .get(userId);
4604        // Get the list of persistent preferred activities that handle the intent
4605        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4606        List<PersistentPreferredActivity> pprefs = ppir != null
4607                ? ppir.queryIntent(intent, resolvedType,
4608                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4609                : null;
4610        if (pprefs != null && pprefs.size() > 0) {
4611            final int M = pprefs.size();
4612            for (int i=0; i<M; i++) {
4613                final PersistentPreferredActivity ppa = pprefs.get(i);
4614                if (DEBUG_PREFERRED || debug) {
4615                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4616                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4617                            + "\n  component=" + ppa.mComponent);
4618                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4619                }
4620                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4621                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4622                if (DEBUG_PREFERRED || debug) {
4623                    Slog.v(TAG, "Found persistent preferred activity:");
4624                    if (ai != null) {
4625                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4626                    } else {
4627                        Slog.v(TAG, "  null");
4628                    }
4629                }
4630                if (ai == null) {
4631                    // This previously registered persistent preferred activity
4632                    // component is no longer known. Ignore it and do NOT remove it.
4633                    continue;
4634                }
4635                for (int j=0; j<N; j++) {
4636                    final ResolveInfo ri = query.get(j);
4637                    if (!ri.activityInfo.applicationInfo.packageName
4638                            .equals(ai.applicationInfo.packageName)) {
4639                        continue;
4640                    }
4641                    if (!ri.activityInfo.name.equals(ai.name)) {
4642                        continue;
4643                    }
4644                    //  Found a persistent preference that can handle the intent.
4645                    if (DEBUG_PREFERRED || debug) {
4646                        Slog.v(TAG, "Returning persistent preferred activity: " +
4647                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4648                    }
4649                    return ri;
4650                }
4651            }
4652        }
4653        return null;
4654    }
4655
4656    // TODO: handle preferred activities missing while user has amnesia
4657    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4658            List<ResolveInfo> query, int priority, boolean always,
4659            boolean removeMatches, boolean debug, int userId) {
4660        if (!sUserManager.exists(userId)) return null;
4661        flags = augmentFlagsForUser(flags, userId);
4662        // writer
4663        synchronized (mPackages) {
4664            if (intent.getSelector() != null) {
4665                intent = intent.getSelector();
4666            }
4667            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4668
4669            // Try to find a matching persistent preferred activity.
4670            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4671                    debug, userId);
4672
4673            // If a persistent preferred activity matched, use it.
4674            if (pri != null) {
4675                return pri;
4676            }
4677
4678            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4679            // Get the list of preferred activities that handle the intent
4680            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4681            List<PreferredActivity> prefs = pir != null
4682                    ? pir.queryIntent(intent, resolvedType,
4683                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4684                    : null;
4685            if (prefs != null && prefs.size() > 0) {
4686                boolean changed = false;
4687                try {
4688                    // First figure out how good the original match set is.
4689                    // We will only allow preferred activities that came
4690                    // from the same match quality.
4691                    int match = 0;
4692
4693                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4694
4695                    final int N = query.size();
4696                    for (int j=0; j<N; j++) {
4697                        final ResolveInfo ri = query.get(j);
4698                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4699                                + ": 0x" + Integer.toHexString(match));
4700                        if (ri.match > match) {
4701                            match = ri.match;
4702                        }
4703                    }
4704
4705                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4706                            + Integer.toHexString(match));
4707
4708                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4709                    final int M = prefs.size();
4710                    for (int i=0; i<M; i++) {
4711                        final PreferredActivity pa = prefs.get(i);
4712                        if (DEBUG_PREFERRED || debug) {
4713                            Slog.v(TAG, "Checking PreferredActivity ds="
4714                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4715                                    + "\n  component=" + pa.mPref.mComponent);
4716                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4717                        }
4718                        if (pa.mPref.mMatch != match) {
4719                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4720                                    + Integer.toHexString(pa.mPref.mMatch));
4721                            continue;
4722                        }
4723                        // If it's not an "always" type preferred activity and that's what we're
4724                        // looking for, skip it.
4725                        if (always && !pa.mPref.mAlways) {
4726                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4727                            continue;
4728                        }
4729                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4730                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4731                        if (DEBUG_PREFERRED || debug) {
4732                            Slog.v(TAG, "Found preferred activity:");
4733                            if (ai != null) {
4734                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4735                            } else {
4736                                Slog.v(TAG, "  null");
4737                            }
4738                        }
4739                        if (ai == null) {
4740                            // This previously registered preferred activity
4741                            // component is no longer known.  Most likely an update
4742                            // to the app was installed and in the new version this
4743                            // component no longer exists.  Clean it up by removing
4744                            // it from the preferred activities list, and skip it.
4745                            Slog.w(TAG, "Removing dangling preferred activity: "
4746                                    + pa.mPref.mComponent);
4747                            pir.removeFilter(pa);
4748                            changed = true;
4749                            continue;
4750                        }
4751                        for (int j=0; j<N; j++) {
4752                            final ResolveInfo ri = query.get(j);
4753                            if (!ri.activityInfo.applicationInfo.packageName
4754                                    .equals(ai.applicationInfo.packageName)) {
4755                                continue;
4756                            }
4757                            if (!ri.activityInfo.name.equals(ai.name)) {
4758                                continue;
4759                            }
4760
4761                            if (removeMatches) {
4762                                pir.removeFilter(pa);
4763                                changed = true;
4764                                if (DEBUG_PREFERRED) {
4765                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4766                                }
4767                                break;
4768                            }
4769
4770                            // Okay we found a previously set preferred or last chosen app.
4771                            // If the result set is different from when this
4772                            // was created, we need to clear it and re-ask the
4773                            // user their preference, if we're looking for an "always" type entry.
4774                            if (always && !pa.mPref.sameSet(query)) {
4775                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4776                                        + intent + " type " + resolvedType);
4777                                if (DEBUG_PREFERRED) {
4778                                    Slog.v(TAG, "Removing preferred activity since set changed "
4779                                            + pa.mPref.mComponent);
4780                                }
4781                                pir.removeFilter(pa);
4782                                // Re-add the filter as a "last chosen" entry (!always)
4783                                PreferredActivity lastChosen = new PreferredActivity(
4784                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4785                                pir.addFilter(lastChosen);
4786                                changed = true;
4787                                return null;
4788                            }
4789
4790                            // Yay! Either the set matched or we're looking for the last chosen
4791                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4792                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4793                            return ri;
4794                        }
4795                    }
4796                } finally {
4797                    if (changed) {
4798                        if (DEBUG_PREFERRED) {
4799                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4800                        }
4801                        scheduleWritePackageRestrictionsLocked(userId);
4802                    }
4803                }
4804            }
4805        }
4806        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4807        return null;
4808    }
4809
4810    /*
4811     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4812     */
4813    @Override
4814    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4815            int targetUserId) {
4816        mContext.enforceCallingOrSelfPermission(
4817                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4818        List<CrossProfileIntentFilter> matches =
4819                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4820        if (matches != null) {
4821            int size = matches.size();
4822            for (int i = 0; i < size; i++) {
4823                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4824            }
4825        }
4826        if (hasWebURI(intent)) {
4827            // cross-profile app linking works only towards the parent.
4828            final UserInfo parent = getProfileParent(sourceUserId);
4829            synchronized(mPackages) {
4830                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4831                        intent, resolvedType, 0, sourceUserId, parent.id);
4832                return xpDomainInfo != null;
4833            }
4834        }
4835        return false;
4836    }
4837
4838    private UserInfo getProfileParent(int userId) {
4839        final long identity = Binder.clearCallingIdentity();
4840        try {
4841            return sUserManager.getProfileParent(userId);
4842        } finally {
4843            Binder.restoreCallingIdentity(identity);
4844        }
4845    }
4846
4847    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4848            String resolvedType, int userId) {
4849        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4850        if (resolver != null) {
4851            return resolver.queryIntent(intent, resolvedType, false, userId);
4852        }
4853        return null;
4854    }
4855
4856    @Override
4857    public List<ResolveInfo> queryIntentActivities(Intent intent,
4858            String resolvedType, int flags, int userId) {
4859        if (!sUserManager.exists(userId)) return Collections.emptyList();
4860        flags = augmentFlagsForUser(flags, userId);
4861        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4862        ComponentName comp = intent.getComponent();
4863        if (comp == null) {
4864            if (intent.getSelector() != null) {
4865                intent = intent.getSelector();
4866                comp = intent.getComponent();
4867            }
4868        }
4869
4870        if (comp != null) {
4871            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4872            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4873            if (ai != null) {
4874                final ResolveInfo ri = new ResolveInfo();
4875                ri.activityInfo = ai;
4876                list.add(ri);
4877            }
4878            return list;
4879        }
4880
4881        // reader
4882        synchronized (mPackages) {
4883            final String pkgName = intent.getPackage();
4884            if (pkgName == null) {
4885                List<CrossProfileIntentFilter> matchingFilters =
4886                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4887                // Check for results that need to skip the current profile.
4888                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4889                        resolvedType, flags, userId);
4890                if (xpResolveInfo != null) {
4891                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4892                    result.add(xpResolveInfo);
4893                    return filterIfNotSystemUser(result, userId);
4894                }
4895
4896                // Check for results in the current profile.
4897                List<ResolveInfo> result = mActivities.queryIntent(
4898                        intent, resolvedType, flags, userId);
4899                result = filterIfNotSystemUser(result, userId);
4900
4901                // Check for cross profile results.
4902                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4903                xpResolveInfo = queryCrossProfileIntents(
4904                        matchingFilters, intent, resolvedType, flags, userId,
4905                        hasNonNegativePriorityResult);
4906                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4907                    boolean isVisibleToUser = filterIfNotSystemUser(
4908                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4909                    if (isVisibleToUser) {
4910                        result.add(xpResolveInfo);
4911                        Collections.sort(result, mResolvePrioritySorter);
4912                    }
4913                }
4914                if (hasWebURI(intent)) {
4915                    CrossProfileDomainInfo xpDomainInfo = null;
4916                    final UserInfo parent = getProfileParent(userId);
4917                    if (parent != null) {
4918                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4919                                flags, userId, parent.id);
4920                    }
4921                    if (xpDomainInfo != null) {
4922                        if (xpResolveInfo != null) {
4923                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4924                            // in the result.
4925                            result.remove(xpResolveInfo);
4926                        }
4927                        if (result.size() == 0) {
4928                            result.add(xpDomainInfo.resolveInfo);
4929                            return result;
4930                        }
4931                    } else if (result.size() <= 1) {
4932                        return result;
4933                    }
4934                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4935                            xpDomainInfo, userId);
4936                    Collections.sort(result, mResolvePrioritySorter);
4937                }
4938                return result;
4939            }
4940            final PackageParser.Package pkg = mPackages.get(pkgName);
4941            if (pkg != null) {
4942                return filterIfNotSystemUser(
4943                        mActivities.queryIntentForPackage(
4944                                intent, resolvedType, flags, pkg.activities, userId),
4945                        userId);
4946            }
4947            return new ArrayList<ResolveInfo>();
4948        }
4949    }
4950
4951    private static class CrossProfileDomainInfo {
4952        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4953        ResolveInfo resolveInfo;
4954        /* Best domain verification status of the activities found in the other profile */
4955        int bestDomainVerificationStatus;
4956    }
4957
4958    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4959            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4960        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4961                sourceUserId)) {
4962            return null;
4963        }
4964        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4965                resolvedType, flags, parentUserId);
4966
4967        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4968            return null;
4969        }
4970        CrossProfileDomainInfo result = null;
4971        int size = resultTargetUser.size();
4972        for (int i = 0; i < size; i++) {
4973            ResolveInfo riTargetUser = resultTargetUser.get(i);
4974            // Intent filter verification is only for filters that specify a host. So don't return
4975            // those that handle all web uris.
4976            if (riTargetUser.handleAllWebDataURI) {
4977                continue;
4978            }
4979            String packageName = riTargetUser.activityInfo.packageName;
4980            PackageSetting ps = mSettings.mPackages.get(packageName);
4981            if (ps == null) {
4982                continue;
4983            }
4984            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4985            int status = (int)(verificationState >> 32);
4986            if (result == null) {
4987                result = new CrossProfileDomainInfo();
4988                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4989                        sourceUserId, parentUserId);
4990                result.bestDomainVerificationStatus = status;
4991            } else {
4992                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4993                        result.bestDomainVerificationStatus);
4994            }
4995        }
4996        // Don't consider matches with status NEVER across profiles.
4997        if (result != null && result.bestDomainVerificationStatus
4998                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4999            return null;
5000        }
5001        return result;
5002    }
5003
5004    /**
5005     * Verification statuses are ordered from the worse to the best, except for
5006     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5007     */
5008    private int bestDomainVerificationStatus(int status1, int status2) {
5009        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5010            return status2;
5011        }
5012        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5013            return status1;
5014        }
5015        return (int) MathUtils.max(status1, status2);
5016    }
5017
5018    private boolean isUserEnabled(int userId) {
5019        long callingId = Binder.clearCallingIdentity();
5020        try {
5021            UserInfo userInfo = sUserManager.getUserInfo(userId);
5022            return userInfo != null && userInfo.isEnabled();
5023        } finally {
5024            Binder.restoreCallingIdentity(callingId);
5025        }
5026    }
5027
5028    /**
5029     * Filter out activities with systemUserOnly flag set, when current user is not System.
5030     *
5031     * @return filtered list
5032     */
5033    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5034        if (userId == UserHandle.USER_SYSTEM) {
5035            return resolveInfos;
5036        }
5037        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5038            ResolveInfo info = resolveInfos.get(i);
5039            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5040                resolveInfos.remove(i);
5041            }
5042        }
5043        return resolveInfos;
5044    }
5045
5046    /**
5047     * @param resolveInfos list of resolve infos in descending priority order
5048     * @return if the list contains a resolve info with non-negative priority
5049     */
5050    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5051        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5052    }
5053
5054    private static boolean hasWebURI(Intent intent) {
5055        if (intent.getData() == null) {
5056            return false;
5057        }
5058        final String scheme = intent.getScheme();
5059        if (TextUtils.isEmpty(scheme)) {
5060            return false;
5061        }
5062        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5063    }
5064
5065    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5066            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5067            int userId) {
5068        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5069
5070        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5071            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5072                    candidates.size());
5073        }
5074
5075        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5076        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5077        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5078        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5079        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5080        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5081
5082        synchronized (mPackages) {
5083            final int count = candidates.size();
5084            // First, try to use linked apps. Partition the candidates into four lists:
5085            // one for the final results, one for the "do not use ever", one for "undefined status"
5086            // and finally one for "browser app type".
5087            for (int n=0; n<count; n++) {
5088                ResolveInfo info = candidates.get(n);
5089                String packageName = info.activityInfo.packageName;
5090                PackageSetting ps = mSettings.mPackages.get(packageName);
5091                if (ps != null) {
5092                    // Add to the special match all list (Browser use case)
5093                    if (info.handleAllWebDataURI) {
5094                        matchAllList.add(info);
5095                        continue;
5096                    }
5097                    // Try to get the status from User settings first
5098                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5099                    int status = (int)(packedStatus >> 32);
5100                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5101                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5102                        if (DEBUG_DOMAIN_VERIFICATION) {
5103                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5104                                    + " : linkgen=" + linkGeneration);
5105                        }
5106                        // Use link-enabled generation as preferredOrder, i.e.
5107                        // prefer newly-enabled over earlier-enabled.
5108                        info.preferredOrder = linkGeneration;
5109                        alwaysList.add(info);
5110                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5111                        if (DEBUG_DOMAIN_VERIFICATION) {
5112                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5113                        }
5114                        neverList.add(info);
5115                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5116                        if (DEBUG_DOMAIN_VERIFICATION) {
5117                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5118                        }
5119                        alwaysAskList.add(info);
5120                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5121                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5122                        if (DEBUG_DOMAIN_VERIFICATION) {
5123                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5124                        }
5125                        undefinedList.add(info);
5126                    }
5127                }
5128            }
5129
5130            // We'll want to include browser possibilities in a few cases
5131            boolean includeBrowser = false;
5132
5133            // First try to add the "always" resolution(s) for the current user, if any
5134            if (alwaysList.size() > 0) {
5135                result.addAll(alwaysList);
5136            } else {
5137                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5138                result.addAll(undefinedList);
5139                // Maybe add one for the other profile.
5140                if (xpDomainInfo != null && (
5141                        xpDomainInfo.bestDomainVerificationStatus
5142                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5143                    result.add(xpDomainInfo.resolveInfo);
5144                }
5145                includeBrowser = true;
5146            }
5147
5148            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5149            // If there were 'always' entries their preferred order has been set, so we also
5150            // back that off to make the alternatives equivalent
5151            if (alwaysAskList.size() > 0) {
5152                for (ResolveInfo i : result) {
5153                    i.preferredOrder = 0;
5154                }
5155                result.addAll(alwaysAskList);
5156                includeBrowser = true;
5157            }
5158
5159            if (includeBrowser) {
5160                // Also add browsers (all of them or only the default one)
5161                if (DEBUG_DOMAIN_VERIFICATION) {
5162                    Slog.v(TAG, "   ...including browsers in candidate set");
5163                }
5164                if ((matchFlags & MATCH_ALL) != 0) {
5165                    result.addAll(matchAllList);
5166                } else {
5167                    // Browser/generic handling case.  If there's a default browser, go straight
5168                    // to that (but only if there is no other higher-priority match).
5169                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5170                    int maxMatchPrio = 0;
5171                    ResolveInfo defaultBrowserMatch = null;
5172                    final int numCandidates = matchAllList.size();
5173                    for (int n = 0; n < numCandidates; n++) {
5174                        ResolveInfo info = matchAllList.get(n);
5175                        // track the highest overall match priority...
5176                        if (info.priority > maxMatchPrio) {
5177                            maxMatchPrio = info.priority;
5178                        }
5179                        // ...and the highest-priority default browser match
5180                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5181                            if (defaultBrowserMatch == null
5182                                    || (defaultBrowserMatch.priority < info.priority)) {
5183                                if (debug) {
5184                                    Slog.v(TAG, "Considering default browser match " + info);
5185                                }
5186                                defaultBrowserMatch = info;
5187                            }
5188                        }
5189                    }
5190                    if (defaultBrowserMatch != null
5191                            && defaultBrowserMatch.priority >= maxMatchPrio
5192                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5193                    {
5194                        if (debug) {
5195                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5196                        }
5197                        result.add(defaultBrowserMatch);
5198                    } else {
5199                        result.addAll(matchAllList);
5200                    }
5201                }
5202
5203                // If there is nothing selected, add all candidates and remove the ones that the user
5204                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5205                if (result.size() == 0) {
5206                    result.addAll(candidates);
5207                    result.removeAll(neverList);
5208                }
5209            }
5210        }
5211        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5212            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5213                    result.size());
5214            for (ResolveInfo info : result) {
5215                Slog.v(TAG, "  + " + info.activityInfo);
5216            }
5217        }
5218        return result;
5219    }
5220
5221    // Returns a packed value as a long:
5222    //
5223    // high 'int'-sized word: link status: undefined/ask/never/always.
5224    // low 'int'-sized word: relative priority among 'always' results.
5225    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5226        long result = ps.getDomainVerificationStatusForUser(userId);
5227        // if none available, get the master status
5228        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5229            if (ps.getIntentFilterVerificationInfo() != null) {
5230                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5231            }
5232        }
5233        return result;
5234    }
5235
5236    private ResolveInfo querySkipCurrentProfileIntents(
5237            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5238            int flags, int sourceUserId) {
5239        if (matchingFilters != null) {
5240            int size = matchingFilters.size();
5241            for (int i = 0; i < size; i ++) {
5242                CrossProfileIntentFilter filter = matchingFilters.get(i);
5243                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5244                    // Checking if there are activities in the target user that can handle the
5245                    // intent.
5246                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5247                            resolvedType, flags, sourceUserId);
5248                    if (resolveInfo != null) {
5249                        return resolveInfo;
5250                    }
5251                }
5252            }
5253        }
5254        return null;
5255    }
5256
5257    // Return matching ResolveInfo in target user if any.
5258    private ResolveInfo queryCrossProfileIntents(
5259            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5260            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5261        if (matchingFilters != null) {
5262            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5263            // match the same intent. For performance reasons, it is better not to
5264            // run queryIntent twice for the same userId
5265            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5266            int size = matchingFilters.size();
5267            for (int i = 0; i < size; i++) {
5268                CrossProfileIntentFilter filter = matchingFilters.get(i);
5269                int targetUserId = filter.getTargetUserId();
5270                boolean skipCurrentProfile =
5271                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5272                boolean skipCurrentProfileIfNoMatchFound =
5273                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5274                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5275                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5276                    // Checking if there are activities in the target user that can handle the
5277                    // intent.
5278                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5279                            resolvedType, flags, sourceUserId);
5280                    if (resolveInfo != null) return resolveInfo;
5281                    alreadyTriedUserIds.put(targetUserId, true);
5282                }
5283            }
5284        }
5285        return null;
5286    }
5287
5288    /**
5289     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5290     * will forward the intent to the filter's target user.
5291     * Otherwise, returns null.
5292     */
5293    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5294            String resolvedType, int flags, int sourceUserId) {
5295        int targetUserId = filter.getTargetUserId();
5296        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5297                resolvedType, flags, targetUserId);
5298        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5299                && isUserEnabled(targetUserId)) {
5300            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5301        }
5302        return null;
5303    }
5304
5305    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5306            int sourceUserId, int targetUserId) {
5307        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5308        long ident = Binder.clearCallingIdentity();
5309        boolean targetIsProfile;
5310        try {
5311            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5312        } finally {
5313            Binder.restoreCallingIdentity(ident);
5314        }
5315        String className;
5316        if (targetIsProfile) {
5317            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5318        } else {
5319            className = FORWARD_INTENT_TO_PARENT;
5320        }
5321        ComponentName forwardingActivityComponentName = new ComponentName(
5322                mAndroidApplication.packageName, className);
5323        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5324                sourceUserId);
5325        if (!targetIsProfile) {
5326            forwardingActivityInfo.showUserIcon = targetUserId;
5327            forwardingResolveInfo.noResourceId = true;
5328        }
5329        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5330        forwardingResolveInfo.priority = 0;
5331        forwardingResolveInfo.preferredOrder = 0;
5332        forwardingResolveInfo.match = 0;
5333        forwardingResolveInfo.isDefault = true;
5334        forwardingResolveInfo.filter = filter;
5335        forwardingResolveInfo.targetUserId = targetUserId;
5336        return forwardingResolveInfo;
5337    }
5338
5339    @Override
5340    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5341            Intent[] specifics, String[] specificTypes, Intent intent,
5342            String resolvedType, int flags, int userId) {
5343        if (!sUserManager.exists(userId)) return Collections.emptyList();
5344        flags = augmentFlagsForUser(flags, userId);
5345        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5346                false, "query intent activity options");
5347        final String resultsAction = intent.getAction();
5348
5349        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5350                | PackageManager.GET_RESOLVED_FILTER, userId);
5351
5352        if (DEBUG_INTENT_MATCHING) {
5353            Log.v(TAG, "Query " + intent + ": " + results);
5354        }
5355
5356        int specificsPos = 0;
5357        int N;
5358
5359        // todo: note that the algorithm used here is O(N^2).  This
5360        // isn't a problem in our current environment, but if we start running
5361        // into situations where we have more than 5 or 10 matches then this
5362        // should probably be changed to something smarter...
5363
5364        // First we go through and resolve each of the specific items
5365        // that were supplied, taking care of removing any corresponding
5366        // duplicate items in the generic resolve list.
5367        if (specifics != null) {
5368            for (int i=0; i<specifics.length; i++) {
5369                final Intent sintent = specifics[i];
5370                if (sintent == null) {
5371                    continue;
5372                }
5373
5374                if (DEBUG_INTENT_MATCHING) {
5375                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5376                }
5377
5378                String action = sintent.getAction();
5379                if (resultsAction != null && resultsAction.equals(action)) {
5380                    // If this action was explicitly requested, then don't
5381                    // remove things that have it.
5382                    action = null;
5383                }
5384
5385                ResolveInfo ri = null;
5386                ActivityInfo ai = null;
5387
5388                ComponentName comp = sintent.getComponent();
5389                if (comp == null) {
5390                    ri = resolveIntent(
5391                        sintent,
5392                        specificTypes != null ? specificTypes[i] : null,
5393                            flags, userId);
5394                    if (ri == null) {
5395                        continue;
5396                    }
5397                    if (ri == mResolveInfo) {
5398                        // ACK!  Must do something better with this.
5399                    }
5400                    ai = ri.activityInfo;
5401                    comp = new ComponentName(ai.applicationInfo.packageName,
5402                            ai.name);
5403                } else {
5404                    ai = getActivityInfo(comp, flags, userId);
5405                    if (ai == null) {
5406                        continue;
5407                    }
5408                }
5409
5410                // Look for any generic query activities that are duplicates
5411                // of this specific one, and remove them from the results.
5412                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5413                N = results.size();
5414                int j;
5415                for (j=specificsPos; j<N; j++) {
5416                    ResolveInfo sri = results.get(j);
5417                    if ((sri.activityInfo.name.equals(comp.getClassName())
5418                            && sri.activityInfo.applicationInfo.packageName.equals(
5419                                    comp.getPackageName()))
5420                        || (action != null && sri.filter.matchAction(action))) {
5421                        results.remove(j);
5422                        if (DEBUG_INTENT_MATCHING) Log.v(
5423                            TAG, "Removing duplicate item from " + j
5424                            + " due to specific " + specificsPos);
5425                        if (ri == null) {
5426                            ri = sri;
5427                        }
5428                        j--;
5429                        N--;
5430                    }
5431                }
5432
5433                // Add this specific item to its proper place.
5434                if (ri == null) {
5435                    ri = new ResolveInfo();
5436                    ri.activityInfo = ai;
5437                }
5438                results.add(specificsPos, ri);
5439                ri.specificIndex = i;
5440                specificsPos++;
5441            }
5442        }
5443
5444        // Now we go through the remaining generic results and remove any
5445        // duplicate actions that are found here.
5446        N = results.size();
5447        for (int i=specificsPos; i<N-1; i++) {
5448            final ResolveInfo rii = results.get(i);
5449            if (rii.filter == null) {
5450                continue;
5451            }
5452
5453            // Iterate over all of the actions of this result's intent
5454            // filter...  typically this should be just one.
5455            final Iterator<String> it = rii.filter.actionsIterator();
5456            if (it == null) {
5457                continue;
5458            }
5459            while (it.hasNext()) {
5460                final String action = it.next();
5461                if (resultsAction != null && resultsAction.equals(action)) {
5462                    // If this action was explicitly requested, then don't
5463                    // remove things that have it.
5464                    continue;
5465                }
5466                for (int j=i+1; j<N; j++) {
5467                    final ResolveInfo rij = results.get(j);
5468                    if (rij.filter != null && rij.filter.hasAction(action)) {
5469                        results.remove(j);
5470                        if (DEBUG_INTENT_MATCHING) Log.v(
5471                            TAG, "Removing duplicate item from " + j
5472                            + " due to action " + action + " at " + i);
5473                        j--;
5474                        N--;
5475                    }
5476                }
5477            }
5478
5479            // If the caller didn't request filter information, drop it now
5480            // so we don't have to marshall/unmarshall it.
5481            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5482                rii.filter = null;
5483            }
5484        }
5485
5486        // Filter out the caller activity if so requested.
5487        if (caller != null) {
5488            N = results.size();
5489            for (int i=0; i<N; i++) {
5490                ActivityInfo ainfo = results.get(i).activityInfo;
5491                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5492                        && caller.getClassName().equals(ainfo.name)) {
5493                    results.remove(i);
5494                    break;
5495                }
5496            }
5497        }
5498
5499        // If the caller didn't request filter information,
5500        // drop them now so we don't have to
5501        // marshall/unmarshall it.
5502        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5503            N = results.size();
5504            for (int i=0; i<N; i++) {
5505                results.get(i).filter = null;
5506            }
5507        }
5508
5509        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5510        return results;
5511    }
5512
5513    @Override
5514    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5515            int userId) {
5516        if (!sUserManager.exists(userId)) return Collections.emptyList();
5517        flags = augmentFlagsForUser(flags, userId);
5518        ComponentName comp = intent.getComponent();
5519        if (comp == null) {
5520            if (intent.getSelector() != null) {
5521                intent = intent.getSelector();
5522                comp = intent.getComponent();
5523            }
5524        }
5525        if (comp != null) {
5526            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5527            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5528            if (ai != null) {
5529                ResolveInfo ri = new ResolveInfo();
5530                ri.activityInfo = ai;
5531                list.add(ri);
5532            }
5533            return list;
5534        }
5535
5536        // reader
5537        synchronized (mPackages) {
5538            String pkgName = intent.getPackage();
5539            if (pkgName == null) {
5540                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5541            }
5542            final PackageParser.Package pkg = mPackages.get(pkgName);
5543            if (pkg != null) {
5544                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5545                        userId);
5546            }
5547            return null;
5548        }
5549    }
5550
5551    @Override
5552    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5553        if (!sUserManager.exists(userId)) return null;
5554        flags = augmentFlagsForUser(flags, userId);
5555        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5556        if (query != null) {
5557            if (query.size() >= 1) {
5558                // If there is more than one service with the same priority,
5559                // just arbitrarily pick the first one.
5560                return query.get(0);
5561            }
5562        }
5563        return null;
5564    }
5565
5566    @Override
5567    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5568            int userId) {
5569        if (!sUserManager.exists(userId)) return Collections.emptyList();
5570        flags = augmentFlagsForUser(flags, userId);
5571        ComponentName comp = intent.getComponent();
5572        if (comp == null) {
5573            if (intent.getSelector() != null) {
5574                intent = intent.getSelector();
5575                comp = intent.getComponent();
5576            }
5577        }
5578        if (comp != null) {
5579            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5580            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5581            if (si != null) {
5582                final ResolveInfo ri = new ResolveInfo();
5583                ri.serviceInfo = si;
5584                list.add(ri);
5585            }
5586            return list;
5587        }
5588
5589        // reader
5590        synchronized (mPackages) {
5591            String pkgName = intent.getPackage();
5592            if (pkgName == null) {
5593                return mServices.queryIntent(intent, resolvedType, flags, userId);
5594            }
5595            final PackageParser.Package pkg = mPackages.get(pkgName);
5596            if (pkg != null) {
5597                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5598                        userId);
5599            }
5600            return null;
5601        }
5602    }
5603
5604    @Override
5605    public List<ResolveInfo> queryIntentContentProviders(
5606            Intent intent, String resolvedType, int flags, int userId) {
5607        if (!sUserManager.exists(userId)) return Collections.emptyList();
5608        flags = augmentFlagsForUser(flags, userId);
5609        ComponentName comp = intent.getComponent();
5610        if (comp == null) {
5611            if (intent.getSelector() != null) {
5612                intent = intent.getSelector();
5613                comp = intent.getComponent();
5614            }
5615        }
5616        if (comp != null) {
5617            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5618            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5619            if (pi != null) {
5620                final ResolveInfo ri = new ResolveInfo();
5621                ri.providerInfo = pi;
5622                list.add(ri);
5623            }
5624            return list;
5625        }
5626
5627        // reader
5628        synchronized (mPackages) {
5629            String pkgName = intent.getPackage();
5630            if (pkgName == null) {
5631                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5632            }
5633            final PackageParser.Package pkg = mPackages.get(pkgName);
5634            if (pkg != null) {
5635                return mProviders.queryIntentForPackage(
5636                        intent, resolvedType, flags, pkg.providers, userId);
5637            }
5638            return null;
5639        }
5640    }
5641
5642    @Override
5643    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5644        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5645
5646        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5647
5648        // writer
5649        synchronized (mPackages) {
5650            ArrayList<PackageInfo> list;
5651            if (listUninstalled) {
5652                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5653                for (PackageSetting ps : mSettings.mPackages.values()) {
5654                    PackageInfo pi;
5655                    if (ps.pkg != null) {
5656                        pi = generatePackageInfo(ps.pkg, flags, userId);
5657                    } else {
5658                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5659                    }
5660                    if (pi != null) {
5661                        list.add(pi);
5662                    }
5663                }
5664            } else {
5665                list = new ArrayList<PackageInfo>(mPackages.size());
5666                for (PackageParser.Package p : mPackages.values()) {
5667                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5668                    if (pi != null) {
5669                        list.add(pi);
5670                    }
5671                }
5672            }
5673
5674            return new ParceledListSlice<PackageInfo>(list);
5675        }
5676    }
5677
5678    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5679            String[] permissions, boolean[] tmp, int flags, int userId) {
5680        int numMatch = 0;
5681        final PermissionsState permissionsState = ps.getPermissionsState();
5682        for (int i=0; i<permissions.length; i++) {
5683            final String permission = permissions[i];
5684            if (permissionsState.hasPermission(permission, userId)) {
5685                tmp[i] = true;
5686                numMatch++;
5687            } else {
5688                tmp[i] = false;
5689            }
5690        }
5691        if (numMatch == 0) {
5692            return;
5693        }
5694        PackageInfo pi;
5695        if (ps.pkg != null) {
5696            pi = generatePackageInfo(ps.pkg, flags, userId);
5697        } else {
5698            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5699        }
5700        // The above might return null in cases of uninstalled apps or install-state
5701        // skew across users/profiles.
5702        if (pi != null) {
5703            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5704                if (numMatch == permissions.length) {
5705                    pi.requestedPermissions = permissions;
5706                } else {
5707                    pi.requestedPermissions = new String[numMatch];
5708                    numMatch = 0;
5709                    for (int i=0; i<permissions.length; i++) {
5710                        if (tmp[i]) {
5711                            pi.requestedPermissions[numMatch] = permissions[i];
5712                            numMatch++;
5713                        }
5714                    }
5715                }
5716            }
5717            list.add(pi);
5718        }
5719    }
5720
5721    @Override
5722    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5723            String[] permissions, int flags, int userId) {
5724        if (!sUserManager.exists(userId)) return null;
5725        flags = augmentFlagsForUser(flags, userId);
5726        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5727
5728        // writer
5729        synchronized (mPackages) {
5730            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5731            boolean[] tmpBools = new boolean[permissions.length];
5732            if (listUninstalled) {
5733                for (PackageSetting ps : mSettings.mPackages.values()) {
5734                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5735                }
5736            } else {
5737                for (PackageParser.Package pkg : mPackages.values()) {
5738                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5739                    if (ps != null) {
5740                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5741                                userId);
5742                    }
5743                }
5744            }
5745
5746            return new ParceledListSlice<PackageInfo>(list);
5747        }
5748    }
5749
5750    @Override
5751    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5752        if (!sUserManager.exists(userId)) return null;
5753        flags = augmentFlagsForUser(flags, userId);
5754        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5755
5756        // writer
5757        synchronized (mPackages) {
5758            ArrayList<ApplicationInfo> list;
5759            if (listUninstalled) {
5760                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5761                for (PackageSetting ps : mSettings.mPackages.values()) {
5762                    ApplicationInfo ai;
5763                    if (ps.pkg != null) {
5764                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5765                                ps.readUserState(userId), userId);
5766                    } else {
5767                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5768                    }
5769                    if (ai != null) {
5770                        list.add(ai);
5771                    }
5772                }
5773            } else {
5774                list = new ArrayList<ApplicationInfo>(mPackages.size());
5775                for (PackageParser.Package p : mPackages.values()) {
5776                    if (p.mExtras != null) {
5777                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5778                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5779                        if (ai != null) {
5780                            list.add(ai);
5781                        }
5782                    }
5783                }
5784            }
5785
5786            return new ParceledListSlice<ApplicationInfo>(list);
5787        }
5788    }
5789
5790    public List<ApplicationInfo> getPersistentApplications(int flags) {
5791        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5792
5793        // reader
5794        synchronized (mPackages) {
5795            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5796            final int userId = UserHandle.getCallingUserId();
5797            while (i.hasNext()) {
5798                final PackageParser.Package p = i.next();
5799                if (p.applicationInfo != null
5800                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5801                        && (!mSafeMode || isSystemApp(p))) {
5802                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5803                    if (ps != null) {
5804                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5805                                ps.readUserState(userId), userId);
5806                        if (ai != null) {
5807                            finalList.add(ai);
5808                        }
5809                    }
5810                }
5811            }
5812        }
5813
5814        return finalList;
5815    }
5816
5817    @Override
5818    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5819        if (!sUserManager.exists(userId)) return null;
5820        flags = augmentFlagsForUser(flags, userId);
5821        // reader
5822        synchronized (mPackages) {
5823            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5824            PackageSetting ps = provider != null
5825                    ? mSettings.mPackages.get(provider.owner.packageName)
5826                    : null;
5827            return ps != null
5828                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5829                    && (!mSafeMode || (provider.info.applicationInfo.flags
5830                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5831                    ? PackageParser.generateProviderInfo(provider, flags,
5832                            ps.readUserState(userId), userId)
5833                    : null;
5834        }
5835    }
5836
5837    /**
5838     * @deprecated
5839     */
5840    @Deprecated
5841    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5842        // reader
5843        synchronized (mPackages) {
5844            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5845                    .entrySet().iterator();
5846            final int userId = UserHandle.getCallingUserId();
5847            while (i.hasNext()) {
5848                Map.Entry<String, PackageParser.Provider> entry = i.next();
5849                PackageParser.Provider p = entry.getValue();
5850                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5851
5852                if (ps != null && p.syncable
5853                        && (!mSafeMode || (p.info.applicationInfo.flags
5854                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5855                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5856                            ps.readUserState(userId), userId);
5857                    if (info != null) {
5858                        outNames.add(entry.getKey());
5859                        outInfo.add(info);
5860                    }
5861                }
5862            }
5863        }
5864    }
5865
5866    @Override
5867    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5868            int uid, int flags) {
5869        final int userId = processName != null ? UserHandle.getUserId(uid)
5870                : UserHandle.getCallingUserId();
5871        if (!sUserManager.exists(userId)) return null;
5872        flags = augmentFlagsForUser(flags, userId);
5873
5874        ArrayList<ProviderInfo> finalList = null;
5875        // reader
5876        synchronized (mPackages) {
5877            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5878            while (i.hasNext()) {
5879                final PackageParser.Provider p = i.next();
5880                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5881                if (ps != null && p.info.authority != null
5882                        && (processName == null
5883                                || (p.info.processName.equals(processName)
5884                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5885                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5886                        && (!mSafeMode
5887                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5888                    if (finalList == null) {
5889                        finalList = new ArrayList<ProviderInfo>(3);
5890                    }
5891                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5892                            ps.readUserState(userId), userId);
5893                    if (info != null) {
5894                        finalList.add(info);
5895                    }
5896                }
5897            }
5898        }
5899
5900        if (finalList != null) {
5901            Collections.sort(finalList, mProviderInitOrderSorter);
5902            return new ParceledListSlice<ProviderInfo>(finalList);
5903        }
5904
5905        return null;
5906    }
5907
5908    @Override
5909    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5910            int flags) {
5911        // reader
5912        synchronized (mPackages) {
5913            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5914            return PackageParser.generateInstrumentationInfo(i, flags);
5915        }
5916    }
5917
5918    @Override
5919    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5920            int flags) {
5921        ArrayList<InstrumentationInfo> finalList =
5922            new ArrayList<InstrumentationInfo>();
5923
5924        // reader
5925        synchronized (mPackages) {
5926            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5927            while (i.hasNext()) {
5928                final PackageParser.Instrumentation p = i.next();
5929                if (targetPackage == null
5930                        || targetPackage.equals(p.info.targetPackage)) {
5931                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5932                            flags);
5933                    if (ii != null) {
5934                        finalList.add(ii);
5935                    }
5936                }
5937            }
5938        }
5939
5940        return finalList;
5941    }
5942
5943    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5944        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5945        if (overlays == null) {
5946            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5947            return;
5948        }
5949        for (PackageParser.Package opkg : overlays.values()) {
5950            // Not much to do if idmap fails: we already logged the error
5951            // and we certainly don't want to abort installation of pkg simply
5952            // because an overlay didn't fit properly. For these reasons,
5953            // ignore the return value of createIdmapForPackagePairLI.
5954            createIdmapForPackagePairLI(pkg, opkg);
5955        }
5956    }
5957
5958    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5959            PackageParser.Package opkg) {
5960        if (!opkg.mTrustedOverlay) {
5961            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5962                    opkg.baseCodePath + ": overlay not trusted");
5963            return false;
5964        }
5965        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5966        if (overlaySet == null) {
5967            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5968                    opkg.baseCodePath + " but target package has no known overlays");
5969            return false;
5970        }
5971        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5972        // TODO: generate idmap for split APKs
5973        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5974            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5975                    + opkg.baseCodePath);
5976            return false;
5977        }
5978        PackageParser.Package[] overlayArray =
5979            overlaySet.values().toArray(new PackageParser.Package[0]);
5980        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5981            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5982                return p1.mOverlayPriority - p2.mOverlayPriority;
5983            }
5984        };
5985        Arrays.sort(overlayArray, cmp);
5986
5987        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5988        int i = 0;
5989        for (PackageParser.Package p : overlayArray) {
5990            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5991        }
5992        return true;
5993    }
5994
5995    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5996        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5997        try {
5998            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5999        } finally {
6000            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6001        }
6002    }
6003
6004    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6005        final File[] files = dir.listFiles();
6006        if (ArrayUtils.isEmpty(files)) {
6007            Log.d(TAG, "No files in app dir " + dir);
6008            return;
6009        }
6010
6011        if (DEBUG_PACKAGE_SCANNING) {
6012            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6013                    + " flags=0x" + Integer.toHexString(parseFlags));
6014        }
6015
6016        for (File file : files) {
6017            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6018                    && !PackageInstallerService.isStageName(file.getName());
6019            if (!isPackage) {
6020                // Ignore entries which are not packages
6021                continue;
6022            }
6023            try {
6024                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6025                        scanFlags, currentTime, null);
6026            } catch (PackageManagerException e) {
6027                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6028
6029                // Delete invalid userdata apps
6030                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6031                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6032                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6033                    if (file.isDirectory()) {
6034                        mInstaller.rmPackageDir(file.getAbsolutePath());
6035                    } else {
6036                        file.delete();
6037                    }
6038                }
6039            }
6040        }
6041    }
6042
6043    private static File getSettingsProblemFile() {
6044        File dataDir = Environment.getDataDirectory();
6045        File systemDir = new File(dataDir, "system");
6046        File fname = new File(systemDir, "uiderrors.txt");
6047        return fname;
6048    }
6049
6050    static void reportSettingsProblem(int priority, String msg) {
6051        logCriticalInfo(priority, msg);
6052    }
6053
6054    static void logCriticalInfo(int priority, String msg) {
6055        Slog.println(priority, TAG, msg);
6056        EventLogTags.writePmCriticalInfo(msg);
6057        try {
6058            File fname = getSettingsProblemFile();
6059            FileOutputStream out = new FileOutputStream(fname, true);
6060            PrintWriter pw = new FastPrintWriter(out);
6061            SimpleDateFormat formatter = new SimpleDateFormat();
6062            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6063            pw.println(dateString + ": " + msg);
6064            pw.close();
6065            FileUtils.setPermissions(
6066                    fname.toString(),
6067                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6068                    -1, -1);
6069        } catch (java.io.IOException e) {
6070        }
6071    }
6072
6073    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6074            PackageParser.Package pkg, File srcFile, int parseFlags)
6075            throws PackageManagerException {
6076        if (ps != null
6077                && ps.codePath.equals(srcFile)
6078                && ps.timeStamp == srcFile.lastModified()
6079                && !isCompatSignatureUpdateNeeded(pkg)
6080                && !isRecoverSignatureUpdateNeeded(pkg)) {
6081            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6082            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6083            ArraySet<PublicKey> signingKs;
6084            synchronized (mPackages) {
6085                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6086            }
6087            if (ps.signatures.mSignatures != null
6088                    && ps.signatures.mSignatures.length != 0
6089                    && signingKs != null) {
6090                // Optimization: reuse the existing cached certificates
6091                // if the package appears to be unchanged.
6092                pkg.mSignatures = ps.signatures.mSignatures;
6093                pkg.mSigningKeys = signingKs;
6094                return;
6095            }
6096
6097            Slog.w(TAG, "PackageSetting for " + ps.name
6098                    + " is missing signatures.  Collecting certs again to recover them.");
6099        } else {
6100            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6101        }
6102
6103        try {
6104            pp.collectCertificates(pkg, parseFlags);
6105            pp.collectManifestDigest(pkg);
6106        } catch (PackageParserException e) {
6107            throw PackageManagerException.from(e);
6108        }
6109    }
6110
6111    /**
6112     *  Traces a package scan.
6113     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6114     */
6115    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6116            long currentTime, UserHandle user) throws PackageManagerException {
6117        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6118        try {
6119            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6120        } finally {
6121            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6122        }
6123    }
6124
6125    /**
6126     *  Scans a package and returns the newly parsed package.
6127     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6128     */
6129    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6130            long currentTime, UserHandle user) throws PackageManagerException {
6131        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6132        parseFlags |= mDefParseFlags;
6133        PackageParser pp = new PackageParser();
6134        pp.setSeparateProcesses(mSeparateProcesses);
6135        pp.setOnlyCoreApps(mOnlyCore);
6136        pp.setDisplayMetrics(mMetrics);
6137
6138        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6139            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6140        }
6141
6142        final PackageParser.Package pkg;
6143        try {
6144            pkg = pp.parsePackage(scanFile, parseFlags);
6145        } catch (PackageParserException e) {
6146            throw PackageManagerException.from(e);
6147        }
6148
6149        PackageSetting ps = null;
6150        PackageSetting updatedPkg;
6151        // reader
6152        synchronized (mPackages) {
6153            // Look to see if we already know about this package.
6154            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6155            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6156                // This package has been renamed to its original name.  Let's
6157                // use that.
6158                ps = mSettings.peekPackageLPr(oldName);
6159            }
6160            // If there was no original package, see one for the real package name.
6161            if (ps == null) {
6162                ps = mSettings.peekPackageLPr(pkg.packageName);
6163            }
6164            // Check to see if this package could be hiding/updating a system
6165            // package.  Must look for it either under the original or real
6166            // package name depending on our state.
6167            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6168            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6169        }
6170        boolean updatedPkgBetter = false;
6171        // First check if this is a system package that may involve an update
6172        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6173            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6174            // it needs to drop FLAG_PRIVILEGED.
6175            if (locationIsPrivileged(scanFile)) {
6176                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6177            } else {
6178                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6179            }
6180
6181            if (ps != null && !ps.codePath.equals(scanFile)) {
6182                // The path has changed from what was last scanned...  check the
6183                // version of the new path against what we have stored to determine
6184                // what to do.
6185                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6186                if (pkg.mVersionCode <= ps.versionCode) {
6187                    // The system package has been updated and the code path does not match
6188                    // Ignore entry. Skip it.
6189                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6190                            + " ignored: updated version " + ps.versionCode
6191                            + " better than this " + pkg.mVersionCode);
6192                    if (!updatedPkg.codePath.equals(scanFile)) {
6193                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6194                                + ps.name + " changing from " + updatedPkg.codePathString
6195                                + " to " + scanFile);
6196                        updatedPkg.codePath = scanFile;
6197                        updatedPkg.codePathString = scanFile.toString();
6198                        updatedPkg.resourcePath = scanFile;
6199                        updatedPkg.resourcePathString = scanFile.toString();
6200                    }
6201                    updatedPkg.pkg = pkg;
6202                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6203                            "Package " + ps.name + " at " + scanFile
6204                                    + " ignored: updated version " + ps.versionCode
6205                                    + " better than this " + pkg.mVersionCode);
6206                } else {
6207                    // The current app on the system partition is better than
6208                    // what we have updated to on the data partition; switch
6209                    // back to the system partition version.
6210                    // At this point, its safely assumed that package installation for
6211                    // apps in system partition will go through. If not there won't be a working
6212                    // version of the app
6213                    // writer
6214                    synchronized (mPackages) {
6215                        // Just remove the loaded entries from package lists.
6216                        mPackages.remove(ps.name);
6217                    }
6218
6219                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6220                            + " reverting from " + ps.codePathString
6221                            + ": new version " + pkg.mVersionCode
6222                            + " better than installed " + ps.versionCode);
6223
6224                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6225                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6226                    synchronized (mInstallLock) {
6227                        args.cleanUpResourcesLI();
6228                    }
6229                    synchronized (mPackages) {
6230                        mSettings.enableSystemPackageLPw(ps.name);
6231                    }
6232                    updatedPkgBetter = true;
6233                }
6234            }
6235        }
6236
6237        if (updatedPkg != null) {
6238            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6239            // initially
6240            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6241
6242            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6243            // flag set initially
6244            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6245                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6246            }
6247        }
6248
6249        // Verify certificates against what was last scanned
6250        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6251
6252        /*
6253         * A new system app appeared, but we already had a non-system one of the
6254         * same name installed earlier.
6255         */
6256        boolean shouldHideSystemApp = false;
6257        if (updatedPkg == null && ps != null
6258                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6259            /*
6260             * Check to make sure the signatures match first. If they don't,
6261             * wipe the installed application and its data.
6262             */
6263            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6264                    != PackageManager.SIGNATURE_MATCH) {
6265                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6266                        + " signatures don't match existing userdata copy; removing");
6267                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6268                ps = null;
6269            } else {
6270                /*
6271                 * If the newly-added system app is an older version than the
6272                 * already installed version, hide it. It will be scanned later
6273                 * and re-added like an update.
6274                 */
6275                if (pkg.mVersionCode <= ps.versionCode) {
6276                    shouldHideSystemApp = true;
6277                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6278                            + " but new version " + pkg.mVersionCode + " better than installed "
6279                            + ps.versionCode + "; hiding system");
6280                } else {
6281                    /*
6282                     * The newly found system app is a newer version that the
6283                     * one previously installed. Simply remove the
6284                     * already-installed application and replace it with our own
6285                     * while keeping the application data.
6286                     */
6287                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6288                            + " reverting from " + ps.codePathString + ": new version "
6289                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6290                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6291                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6292                    synchronized (mInstallLock) {
6293                        args.cleanUpResourcesLI();
6294                    }
6295                }
6296            }
6297        }
6298
6299        // The apk is forward locked (not public) if its code and resources
6300        // are kept in different files. (except for app in either system or
6301        // vendor path).
6302        // TODO grab this value from PackageSettings
6303        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6304            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6305                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6306            }
6307        }
6308
6309        // TODO: extend to support forward-locked splits
6310        String resourcePath = null;
6311        String baseResourcePath = null;
6312        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6313            if (ps != null && ps.resourcePathString != null) {
6314                resourcePath = ps.resourcePathString;
6315                baseResourcePath = ps.resourcePathString;
6316            } else {
6317                // Should not happen at all. Just log an error.
6318                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6319            }
6320        } else {
6321            resourcePath = pkg.codePath;
6322            baseResourcePath = pkg.baseCodePath;
6323        }
6324
6325        // Set application objects path explicitly.
6326        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6327        pkg.applicationInfo.setCodePath(pkg.codePath);
6328        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6329        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6330        pkg.applicationInfo.setResourcePath(resourcePath);
6331        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6332        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6333
6334        // Note that we invoke the following method only if we are about to unpack an application
6335        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6336                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6337
6338        /*
6339         * If the system app should be overridden by a previously installed
6340         * data, hide the system app now and let the /data/app scan pick it up
6341         * again.
6342         */
6343        if (shouldHideSystemApp) {
6344            synchronized (mPackages) {
6345                mSettings.disableSystemPackageLPw(pkg.packageName);
6346            }
6347        }
6348
6349        return scannedPkg;
6350    }
6351
6352    private static String fixProcessName(String defProcessName,
6353            String processName, int uid) {
6354        if (processName == null) {
6355            return defProcessName;
6356        }
6357        return processName;
6358    }
6359
6360    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6361            throws PackageManagerException {
6362        if (pkgSetting.signatures.mSignatures != null) {
6363            // Already existing package. Make sure signatures match
6364            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6365                    == PackageManager.SIGNATURE_MATCH;
6366            if (!match) {
6367                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6368                        == PackageManager.SIGNATURE_MATCH;
6369            }
6370            if (!match) {
6371                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6372                        == PackageManager.SIGNATURE_MATCH;
6373            }
6374            if (!match) {
6375                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6376                        + pkg.packageName + " signatures do not match the "
6377                        + "previously installed version; ignoring!");
6378            }
6379        }
6380
6381        // Check for shared user signatures
6382        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6383            // Already existing package. Make sure signatures match
6384            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6385                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6386            if (!match) {
6387                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6388                        == PackageManager.SIGNATURE_MATCH;
6389            }
6390            if (!match) {
6391                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6392                        == PackageManager.SIGNATURE_MATCH;
6393            }
6394            if (!match) {
6395                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6396                        "Package " + pkg.packageName
6397                        + " has no signatures that match those in shared user "
6398                        + pkgSetting.sharedUser.name + "; ignoring!");
6399            }
6400        }
6401    }
6402
6403    /**
6404     * Enforces that only the system UID or root's UID can call a method exposed
6405     * via Binder.
6406     *
6407     * @param message used as message if SecurityException is thrown
6408     * @throws SecurityException if the caller is not system or root
6409     */
6410    private static final void enforceSystemOrRoot(String message) {
6411        final int uid = Binder.getCallingUid();
6412        if (uid != Process.SYSTEM_UID && uid != 0) {
6413            throw new SecurityException(message);
6414        }
6415    }
6416
6417    @Override
6418    public void performFstrimIfNeeded() {
6419        enforceSystemOrRoot("Only the system can request fstrim");
6420
6421        // Before everything else, see whether we need to fstrim.
6422        try {
6423            IMountService ms = PackageHelper.getMountService();
6424            if (ms != null) {
6425                final boolean isUpgrade = isUpgrade();
6426                boolean doTrim = isUpgrade;
6427                if (doTrim) {
6428                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6429                } else {
6430                    final long interval = android.provider.Settings.Global.getLong(
6431                            mContext.getContentResolver(),
6432                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6433                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6434                    if (interval > 0) {
6435                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6436                        if (timeSinceLast > interval) {
6437                            doTrim = true;
6438                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6439                                    + "; running immediately");
6440                        }
6441                    }
6442                }
6443                if (doTrim) {
6444                    if (!isFirstBoot()) {
6445                        try {
6446                            ActivityManagerNative.getDefault().showBootMessage(
6447                                    mContext.getResources().getString(
6448                                            R.string.android_upgrading_fstrim), true);
6449                        } catch (RemoteException e) {
6450                        }
6451                    }
6452                    ms.runMaintenance();
6453                }
6454            } else {
6455                Slog.e(TAG, "Mount service unavailable!");
6456            }
6457        } catch (RemoteException e) {
6458            // Can't happen; MountService is local
6459        }
6460    }
6461
6462    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6463        List<ResolveInfo> ris = null;
6464        try {
6465            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6466                    intent, null, 0, userId);
6467        } catch (RemoteException e) {
6468        }
6469        ArraySet<String> pkgNames = new ArraySet<String>();
6470        if (ris != null) {
6471            for (ResolveInfo ri : ris) {
6472                pkgNames.add(ri.activityInfo.packageName);
6473            }
6474        }
6475        return pkgNames;
6476    }
6477
6478    @Override
6479    public void notifyPackageUse(String packageName) {
6480        synchronized (mPackages) {
6481            PackageParser.Package p = mPackages.get(packageName);
6482            if (p == null) {
6483                return;
6484            }
6485            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6486        }
6487    }
6488
6489    @Override
6490    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6491        return performDexOptTraced(packageName, instructionSet);
6492    }
6493
6494    public boolean performDexOpt(String packageName, String instructionSet) {
6495        return performDexOptTraced(packageName, instructionSet);
6496    }
6497
6498    private boolean performDexOptTraced(String packageName, String instructionSet) {
6499        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6500        try {
6501            return performDexOptInternal(packageName, instructionSet);
6502        } finally {
6503            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6504        }
6505    }
6506
6507    private boolean performDexOptInternal(String packageName, String instructionSet) {
6508        PackageParser.Package p;
6509        final String targetInstructionSet;
6510        synchronized (mPackages) {
6511            p = mPackages.get(packageName);
6512            if (p == null) {
6513                return false;
6514            }
6515            mPackageUsage.write(false);
6516
6517            targetInstructionSet = instructionSet != null ? instructionSet :
6518                    getPrimaryInstructionSet(p.applicationInfo);
6519            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6520                return false;
6521            }
6522        }
6523        long callingId = Binder.clearCallingIdentity();
6524        try {
6525            synchronized (mInstallLock) {
6526                final String[] instructionSets = new String[] { targetInstructionSet };
6527                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6528                        true /* inclDependencies */);
6529                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6530            }
6531        } finally {
6532            Binder.restoreCallingIdentity(callingId);
6533        }
6534    }
6535
6536    public ArraySet<String> getPackagesThatNeedDexOpt() {
6537        ArraySet<String> pkgs = null;
6538        synchronized (mPackages) {
6539            for (PackageParser.Package p : mPackages.values()) {
6540                if (DEBUG_DEXOPT) {
6541                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6542                }
6543                if (!p.mDexOptPerformed.isEmpty()) {
6544                    continue;
6545                }
6546                if (pkgs == null) {
6547                    pkgs = new ArraySet<String>();
6548                }
6549                pkgs.add(p.packageName);
6550            }
6551        }
6552        return pkgs;
6553    }
6554
6555    public void shutdown() {
6556        mPackageUsage.write(true);
6557    }
6558
6559    @Override
6560    public void forceDexOpt(String packageName) {
6561        enforceSystemOrRoot("forceDexOpt");
6562
6563        PackageParser.Package pkg;
6564        synchronized (mPackages) {
6565            pkg = mPackages.get(packageName);
6566            if (pkg == null) {
6567                throw new IllegalArgumentException("Missing package: " + packageName);
6568            }
6569        }
6570
6571        synchronized (mInstallLock) {
6572            final String[] instructionSets = new String[] {
6573                    getPrimaryInstructionSet(pkg.applicationInfo) };
6574
6575            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6576
6577            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6578                    true /* inclDependencies */);
6579
6580            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6581            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6582                throw new IllegalStateException("Failed to dexopt: " + res);
6583            }
6584        }
6585    }
6586
6587    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6588        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6589            Slog.w(TAG, "Unable to update from " + oldPkg.name
6590                    + " to " + newPkg.packageName
6591                    + ": old package not in system partition");
6592            return false;
6593        } else if (mPackages.get(oldPkg.name) != null) {
6594            Slog.w(TAG, "Unable to update from " + oldPkg.name
6595                    + " to " + newPkg.packageName
6596                    + ": old package still exists");
6597            return false;
6598        }
6599        return true;
6600    }
6601
6602    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6603            throws PackageManagerException {
6604        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6605        if (res != 0) {
6606            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6607                    "Failed to install " + packageName + ": " + res);
6608        }
6609
6610        final int[] users = sUserManager.getUserIds();
6611        for (int user : users) {
6612            if (user != 0) {
6613                res = mInstaller.createUserData(volumeUuid, packageName,
6614                        UserHandle.getUid(user, uid), user, seinfo);
6615                if (res != 0) {
6616                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6617                            "Failed to createUserData " + packageName + ": " + res);
6618                }
6619            }
6620        }
6621    }
6622
6623    private int removeDataDirsLI(String volumeUuid, String packageName) {
6624        int[] users = sUserManager.getUserIds();
6625        int res = 0;
6626        for (int user : users) {
6627            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6628            if (resInner < 0) {
6629                res = resInner;
6630            }
6631        }
6632
6633        return res;
6634    }
6635
6636    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6637        int[] users = sUserManager.getUserIds();
6638        int res = 0;
6639        for (int user : users) {
6640            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6641            if (resInner < 0) {
6642                res = resInner;
6643            }
6644        }
6645        return res;
6646    }
6647
6648    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6649            PackageParser.Package changingLib) {
6650        if (file.path != null) {
6651            usesLibraryFiles.add(file.path);
6652            return;
6653        }
6654        PackageParser.Package p = mPackages.get(file.apk);
6655        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6656            // If we are doing this while in the middle of updating a library apk,
6657            // then we need to make sure to use that new apk for determining the
6658            // dependencies here.  (We haven't yet finished committing the new apk
6659            // to the package manager state.)
6660            if (p == null || p.packageName.equals(changingLib.packageName)) {
6661                p = changingLib;
6662            }
6663        }
6664        if (p != null) {
6665            usesLibraryFiles.addAll(p.getAllCodePaths());
6666        }
6667    }
6668
6669    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6670            PackageParser.Package changingLib) throws PackageManagerException {
6671        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6672            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6673            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6674            for (int i=0; i<N; i++) {
6675                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6676                if (file == null) {
6677                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6678                            "Package " + pkg.packageName + " requires unavailable shared library "
6679                            + pkg.usesLibraries.get(i) + "; failing!");
6680                }
6681                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6682            }
6683            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6684            for (int i=0; i<N; i++) {
6685                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6686                if (file == null) {
6687                    Slog.w(TAG, "Package " + pkg.packageName
6688                            + " desires unavailable shared library "
6689                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6690                } else {
6691                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6692                }
6693            }
6694            N = usesLibraryFiles.size();
6695            if (N > 0) {
6696                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6697            } else {
6698                pkg.usesLibraryFiles = null;
6699            }
6700        }
6701    }
6702
6703    private static boolean hasString(List<String> list, List<String> which) {
6704        if (list == null) {
6705            return false;
6706        }
6707        for (int i=list.size()-1; i>=0; i--) {
6708            for (int j=which.size()-1; j>=0; j--) {
6709                if (which.get(j).equals(list.get(i))) {
6710                    return true;
6711                }
6712            }
6713        }
6714        return false;
6715    }
6716
6717    private void updateAllSharedLibrariesLPw() {
6718        for (PackageParser.Package pkg : mPackages.values()) {
6719            try {
6720                updateSharedLibrariesLPw(pkg, null);
6721            } catch (PackageManagerException e) {
6722                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6723            }
6724        }
6725    }
6726
6727    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6728            PackageParser.Package changingPkg) {
6729        ArrayList<PackageParser.Package> res = null;
6730        for (PackageParser.Package pkg : mPackages.values()) {
6731            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6732                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6733                if (res == null) {
6734                    res = new ArrayList<PackageParser.Package>();
6735                }
6736                res.add(pkg);
6737                try {
6738                    updateSharedLibrariesLPw(pkg, changingPkg);
6739                } catch (PackageManagerException e) {
6740                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6741                }
6742            }
6743        }
6744        return res;
6745    }
6746
6747    /**
6748     * Derive the value of the {@code cpuAbiOverride} based on the provided
6749     * value and an optional stored value from the package settings.
6750     */
6751    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6752        String cpuAbiOverride = null;
6753
6754        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6755            cpuAbiOverride = null;
6756        } else if (abiOverride != null) {
6757            cpuAbiOverride = abiOverride;
6758        } else if (settings != null) {
6759            cpuAbiOverride = settings.cpuAbiOverrideString;
6760        }
6761
6762        return cpuAbiOverride;
6763    }
6764
6765    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6766            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6767        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6768        try {
6769            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6770        } finally {
6771            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6772        }
6773    }
6774
6775    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6776            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6777        boolean success = false;
6778        try {
6779            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6780                    currentTime, user);
6781            success = true;
6782            return res;
6783        } finally {
6784            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6785                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6786            }
6787        }
6788    }
6789
6790    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6791            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6792        final File scanFile = new File(pkg.codePath);
6793        if (pkg.applicationInfo.getCodePath() == null ||
6794                pkg.applicationInfo.getResourcePath() == null) {
6795            // Bail out. The resource and code paths haven't been set.
6796            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6797                    "Code and resource paths haven't been set correctly");
6798        }
6799
6800        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6801            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6802        } else {
6803            // Only allow system apps to be flagged as core apps.
6804            pkg.coreApp = false;
6805        }
6806
6807        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6808            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6809        }
6810
6811        if (mCustomResolverComponentName != null &&
6812                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6813            setUpCustomResolverActivity(pkg);
6814        }
6815
6816        if (pkg.packageName.equals("android")) {
6817            synchronized (mPackages) {
6818                if (mAndroidApplication != null) {
6819                    Slog.w(TAG, "*************************************************");
6820                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6821                    Slog.w(TAG, " file=" + scanFile);
6822                    Slog.w(TAG, "*************************************************");
6823                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6824                            "Core android package being redefined.  Skipping.");
6825                }
6826
6827                // Set up information for our fall-back user intent resolution activity.
6828                mPlatformPackage = pkg;
6829                pkg.mVersionCode = mSdkVersion;
6830                mAndroidApplication = pkg.applicationInfo;
6831
6832                if (!mResolverReplaced) {
6833                    mResolveActivity.applicationInfo = mAndroidApplication;
6834                    mResolveActivity.name = ResolverActivity.class.getName();
6835                    mResolveActivity.packageName = mAndroidApplication.packageName;
6836                    mResolveActivity.processName = "system:ui";
6837                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6838                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6839                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6840                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6841                    mResolveActivity.exported = true;
6842                    mResolveActivity.enabled = true;
6843                    mResolveInfo.activityInfo = mResolveActivity;
6844                    mResolveInfo.priority = 0;
6845                    mResolveInfo.preferredOrder = 0;
6846                    mResolveInfo.match = 0;
6847                    mResolveComponentName = new ComponentName(
6848                            mAndroidApplication.packageName, mResolveActivity.name);
6849                }
6850            }
6851        }
6852
6853        if (DEBUG_PACKAGE_SCANNING) {
6854            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6855                Log.d(TAG, "Scanning package " + pkg.packageName);
6856        }
6857
6858        if (mPackages.containsKey(pkg.packageName)
6859                || mSharedLibraries.containsKey(pkg.packageName)) {
6860            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6861                    "Application package " + pkg.packageName
6862                    + " already installed.  Skipping duplicate.");
6863        }
6864
6865        // If we're only installing presumed-existing packages, require that the
6866        // scanned APK is both already known and at the path previously established
6867        // for it.  Previously unknown packages we pick up normally, but if we have an
6868        // a priori expectation about this package's install presence, enforce it.
6869        // With a singular exception for new system packages. When an OTA contains
6870        // a new system package, we allow the codepath to change from a system location
6871        // to the user-installed location. If we don't allow this change, any newer,
6872        // user-installed version of the application will be ignored.
6873        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6874            if (mExpectingBetter.containsKey(pkg.packageName)) {
6875                logCriticalInfo(Log.WARN,
6876                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6877            } else {
6878                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6879                if (known != null) {
6880                    if (DEBUG_PACKAGE_SCANNING) {
6881                        Log.d(TAG, "Examining " + pkg.codePath
6882                                + " and requiring known paths " + known.codePathString
6883                                + " & " + known.resourcePathString);
6884                    }
6885                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6886                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6887                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6888                                "Application package " + pkg.packageName
6889                                + " found at " + pkg.applicationInfo.getCodePath()
6890                                + " but expected at " + known.codePathString + "; ignoring.");
6891                    }
6892                }
6893            }
6894        }
6895
6896        // Initialize package source and resource directories
6897        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6898        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6899
6900        SharedUserSetting suid = null;
6901        PackageSetting pkgSetting = null;
6902
6903        if (!isSystemApp(pkg)) {
6904            // Only system apps can use these features.
6905            pkg.mOriginalPackages = null;
6906            pkg.mRealPackage = null;
6907            pkg.mAdoptPermissions = null;
6908        }
6909
6910        // writer
6911        synchronized (mPackages) {
6912            if (pkg.mSharedUserId != null) {
6913                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6914                if (suid == null) {
6915                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6916                            "Creating application package " + pkg.packageName
6917                            + " for shared user failed");
6918                }
6919                if (DEBUG_PACKAGE_SCANNING) {
6920                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6921                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6922                                + "): packages=" + suid.packages);
6923                }
6924            }
6925
6926            // Check if we are renaming from an original package name.
6927            PackageSetting origPackage = null;
6928            String realName = null;
6929            if (pkg.mOriginalPackages != null) {
6930                // This package may need to be renamed to a previously
6931                // installed name.  Let's check on that...
6932                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6933                if (pkg.mOriginalPackages.contains(renamed)) {
6934                    // This package had originally been installed as the
6935                    // original name, and we have already taken care of
6936                    // transitioning to the new one.  Just update the new
6937                    // one to continue using the old name.
6938                    realName = pkg.mRealPackage;
6939                    if (!pkg.packageName.equals(renamed)) {
6940                        // Callers into this function may have already taken
6941                        // care of renaming the package; only do it here if
6942                        // it is not already done.
6943                        pkg.setPackageName(renamed);
6944                    }
6945
6946                } else {
6947                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6948                        if ((origPackage = mSettings.peekPackageLPr(
6949                                pkg.mOriginalPackages.get(i))) != null) {
6950                            // We do have the package already installed under its
6951                            // original name...  should we use it?
6952                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6953                                // New package is not compatible with original.
6954                                origPackage = null;
6955                                continue;
6956                            } else if (origPackage.sharedUser != null) {
6957                                // Make sure uid is compatible between packages.
6958                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6959                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6960                                            + " to " + pkg.packageName + ": old uid "
6961                                            + origPackage.sharedUser.name
6962                                            + " differs from " + pkg.mSharedUserId);
6963                                    origPackage = null;
6964                                    continue;
6965                                }
6966                            } else {
6967                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6968                                        + pkg.packageName + " to old name " + origPackage.name);
6969                            }
6970                            break;
6971                        }
6972                    }
6973                }
6974            }
6975
6976            if (mTransferedPackages.contains(pkg.packageName)) {
6977                Slog.w(TAG, "Package " + pkg.packageName
6978                        + " was transferred to another, but its .apk remains");
6979            }
6980
6981            // Just create the setting, don't add it yet. For already existing packages
6982            // the PkgSetting exists already and doesn't have to be created.
6983            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6984                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6985                    pkg.applicationInfo.primaryCpuAbi,
6986                    pkg.applicationInfo.secondaryCpuAbi,
6987                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6988                    user, false);
6989            if (pkgSetting == null) {
6990                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6991                        "Creating application package " + pkg.packageName + " failed");
6992            }
6993
6994            if (pkgSetting.origPackage != null) {
6995                // If we are first transitioning from an original package,
6996                // fix up the new package's name now.  We need to do this after
6997                // looking up the package under its new name, so getPackageLP
6998                // can take care of fiddling things correctly.
6999                pkg.setPackageName(origPackage.name);
7000
7001                // File a report about this.
7002                String msg = "New package " + pkgSetting.realName
7003                        + " renamed to replace old package " + pkgSetting.name;
7004                reportSettingsProblem(Log.WARN, msg);
7005
7006                // Make a note of it.
7007                mTransferedPackages.add(origPackage.name);
7008
7009                // No longer need to retain this.
7010                pkgSetting.origPackage = null;
7011            }
7012
7013            if (realName != null) {
7014                // Make a note of it.
7015                mTransferedPackages.add(pkg.packageName);
7016            }
7017
7018            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7019                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7020            }
7021
7022            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7023                // Check all shared libraries and map to their actual file path.
7024                // We only do this here for apps not on a system dir, because those
7025                // are the only ones that can fail an install due to this.  We
7026                // will take care of the system apps by updating all of their
7027                // library paths after the scan is done.
7028                updateSharedLibrariesLPw(pkg, null);
7029            }
7030
7031            if (mFoundPolicyFile) {
7032                SELinuxMMAC.assignSeinfoValue(pkg);
7033            }
7034
7035            pkg.applicationInfo.uid = pkgSetting.appId;
7036            pkg.mExtras = pkgSetting;
7037            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7038                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7039                    // We just determined the app is signed correctly, so bring
7040                    // over the latest parsed certs.
7041                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7042                } else {
7043                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7044                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7045                                "Package " + pkg.packageName + " upgrade keys do not match the "
7046                                + "previously installed version");
7047                    } else {
7048                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7049                        String msg = "System package " + pkg.packageName
7050                            + " signature changed; retaining data.";
7051                        reportSettingsProblem(Log.WARN, msg);
7052                    }
7053                }
7054            } else {
7055                try {
7056                    verifySignaturesLP(pkgSetting, pkg);
7057                    // We just determined the app is signed correctly, so bring
7058                    // over the latest parsed certs.
7059                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7060                } catch (PackageManagerException e) {
7061                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7062                        throw e;
7063                    }
7064                    // The signature has changed, but this package is in the system
7065                    // image...  let's recover!
7066                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7067                    // However...  if this package is part of a shared user, but it
7068                    // doesn't match the signature of the shared user, let's fail.
7069                    // What this means is that you can't change the signatures
7070                    // associated with an overall shared user, which doesn't seem all
7071                    // that unreasonable.
7072                    if (pkgSetting.sharedUser != null) {
7073                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7074                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7075                            throw new PackageManagerException(
7076                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7077                                            "Signature mismatch for shared user : "
7078                                            + pkgSetting.sharedUser);
7079                        }
7080                    }
7081                    // File a report about this.
7082                    String msg = "System package " + pkg.packageName
7083                        + " signature changed; retaining data.";
7084                    reportSettingsProblem(Log.WARN, msg);
7085                }
7086            }
7087            // Verify that this new package doesn't have any content providers
7088            // that conflict with existing packages.  Only do this if the
7089            // package isn't already installed, since we don't want to break
7090            // things that are installed.
7091            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7092                final int N = pkg.providers.size();
7093                int i;
7094                for (i=0; i<N; i++) {
7095                    PackageParser.Provider p = pkg.providers.get(i);
7096                    if (p.info.authority != null) {
7097                        String names[] = p.info.authority.split(";");
7098                        for (int j = 0; j < names.length; j++) {
7099                            if (mProvidersByAuthority.containsKey(names[j])) {
7100                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7101                                final String otherPackageName =
7102                                        ((other != null && other.getComponentName() != null) ?
7103                                                other.getComponentName().getPackageName() : "?");
7104                                throw new PackageManagerException(
7105                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7106                                                "Can't install because provider name " + names[j]
7107                                                + " (in package " + pkg.applicationInfo.packageName
7108                                                + ") is already used by " + otherPackageName);
7109                            }
7110                        }
7111                    }
7112                }
7113            }
7114
7115            if (pkg.mAdoptPermissions != null) {
7116                // This package wants to adopt ownership of permissions from
7117                // another package.
7118                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7119                    final String origName = pkg.mAdoptPermissions.get(i);
7120                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7121                    if (orig != null) {
7122                        if (verifyPackageUpdateLPr(orig, pkg)) {
7123                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7124                                    + pkg.packageName);
7125                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7126                        }
7127                    }
7128                }
7129            }
7130        }
7131
7132        final String pkgName = pkg.packageName;
7133
7134        final long scanFileTime = scanFile.lastModified();
7135        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7136        pkg.applicationInfo.processName = fixProcessName(
7137                pkg.applicationInfo.packageName,
7138                pkg.applicationInfo.processName,
7139                pkg.applicationInfo.uid);
7140
7141        if (pkg != mPlatformPackage) {
7142            // This is a normal package, need to make its data directory.
7143            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7144                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7145
7146            boolean uidError = false;
7147            if (dataPath.exists()) {
7148                int currentUid = 0;
7149                try {
7150                    StructStat stat = Os.stat(dataPath.getPath());
7151                    currentUid = stat.st_uid;
7152                } catch (ErrnoException e) {
7153                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7154                }
7155
7156                // If we have mismatched owners for the data path, we have a problem.
7157                if (currentUid != pkg.applicationInfo.uid) {
7158                    boolean recovered = false;
7159                    if (currentUid == 0) {
7160                        // The directory somehow became owned by root.  Wow.
7161                        // This is probably because the system was stopped while
7162                        // installd was in the middle of messing with its libs
7163                        // directory.  Ask installd to fix that.
7164                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7165                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7166                        if (ret >= 0) {
7167                            recovered = true;
7168                            String msg = "Package " + pkg.packageName
7169                                    + " unexpectedly changed to uid 0; recovered to " +
7170                                    + pkg.applicationInfo.uid;
7171                            reportSettingsProblem(Log.WARN, msg);
7172                        }
7173                    }
7174                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7175                            || (scanFlags&SCAN_BOOTING) != 0)) {
7176                        // If this is a system app, we can at least delete its
7177                        // current data so the application will still work.
7178                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7179                        if (ret >= 0) {
7180                            // TODO: Kill the processes first
7181                            // Old data gone!
7182                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7183                                    ? "System package " : "Third party package ";
7184                            String msg = prefix + pkg.packageName
7185                                    + " has changed from uid: "
7186                                    + currentUid + " to "
7187                                    + pkg.applicationInfo.uid + "; old data erased";
7188                            reportSettingsProblem(Log.WARN, msg);
7189                            recovered = true;
7190                        }
7191                        if (!recovered) {
7192                            mHasSystemUidErrors = true;
7193                        }
7194                    } else if (!recovered) {
7195                        // If we allow this install to proceed, we will be broken.
7196                        // Abort, abort!
7197                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7198                                "scanPackageLI");
7199                    }
7200                    if (!recovered) {
7201                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7202                            + pkg.applicationInfo.uid + "/fs_"
7203                            + currentUid;
7204                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7205                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7206                        String msg = "Package " + pkg.packageName
7207                                + " has mismatched uid: "
7208                                + currentUid + " on disk, "
7209                                + pkg.applicationInfo.uid + " in settings";
7210                        // writer
7211                        synchronized (mPackages) {
7212                            mSettings.mReadMessages.append(msg);
7213                            mSettings.mReadMessages.append('\n');
7214                            uidError = true;
7215                            if (!pkgSetting.uidError) {
7216                                reportSettingsProblem(Log.ERROR, msg);
7217                            }
7218                        }
7219                    }
7220                }
7221
7222                // Ensure that directories are prepared
7223                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7224                        pkg.applicationInfo.seinfo);
7225
7226                if (mShouldRestoreconData) {
7227                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7228                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7229                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7230                }
7231            } else {
7232                if (DEBUG_PACKAGE_SCANNING) {
7233                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7234                        Log.v(TAG, "Want this data dir: " + dataPath);
7235                }
7236                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7237                        pkg.applicationInfo.seinfo);
7238            }
7239
7240            // Get all of our default paths setup
7241            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7242
7243            pkgSetting.uidError = uidError;
7244        }
7245
7246        final String path = scanFile.getPath();
7247        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7248
7249        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7250            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7251
7252            // Some system apps still use directory structure for native libraries
7253            // in which case we might end up not detecting abi solely based on apk
7254            // structure. Try to detect abi based on directory structure.
7255            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7256                    pkg.applicationInfo.primaryCpuAbi == null) {
7257                setBundledAppAbisAndRoots(pkg, pkgSetting);
7258                setNativeLibraryPaths(pkg);
7259            }
7260
7261        } else {
7262            if ((scanFlags & SCAN_MOVE) != 0) {
7263                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7264                // but we already have this packages package info in the PackageSetting. We just
7265                // use that and derive the native library path based on the new codepath.
7266                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7267                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7268            }
7269
7270            // Set native library paths again. For moves, the path will be updated based on the
7271            // ABIs we've determined above. For non-moves, the path will be updated based on the
7272            // ABIs we determined during compilation, but the path will depend on the final
7273            // package path (after the rename away from the stage path).
7274            setNativeLibraryPaths(pkg);
7275        }
7276
7277        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7278        final int[] userIds = sUserManager.getUserIds();
7279        synchronized (mInstallLock) {
7280            // Make sure all user data directories are ready to roll; we're okay
7281            // if they already exist
7282            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7283                for (int userId : userIds) {
7284                    if (userId != UserHandle.USER_SYSTEM) {
7285                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7286                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7287                                pkg.applicationInfo.seinfo);
7288                    }
7289                }
7290            }
7291
7292            // Create a native library symlink only if we have native libraries
7293            // and if the native libraries are 32 bit libraries. We do not provide
7294            // this symlink for 64 bit libraries.
7295            if (pkg.applicationInfo.primaryCpuAbi != null &&
7296                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7297                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7298                try {
7299                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7300                    for (int userId : userIds) {
7301                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7302                                nativeLibPath, userId) < 0) {
7303                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7304                                    "Failed linking native library dir (user=" + userId + ")");
7305                        }
7306                    }
7307                } finally {
7308                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7309                }
7310            }
7311        }
7312
7313        // This is a special case for the "system" package, where the ABI is
7314        // dictated by the zygote configuration (and init.rc). We should keep track
7315        // of this ABI so that we can deal with "normal" applications that run under
7316        // the same UID correctly.
7317        if (mPlatformPackage == pkg) {
7318            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7319                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7320        }
7321
7322        // If there's a mismatch between the abi-override in the package setting
7323        // and the abiOverride specified for the install. Warn about this because we
7324        // would've already compiled the app without taking the package setting into
7325        // account.
7326        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7327            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7328                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7329                        " for package: " + pkg.packageName);
7330            }
7331        }
7332
7333        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7334        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7335        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7336
7337        // Copy the derived override back to the parsed package, so that we can
7338        // update the package settings accordingly.
7339        pkg.cpuAbiOverride = cpuAbiOverride;
7340
7341        if (DEBUG_ABI_SELECTION) {
7342            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7343                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7344                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7345        }
7346
7347        // Push the derived path down into PackageSettings so we know what to
7348        // clean up at uninstall time.
7349        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7350
7351        if (DEBUG_ABI_SELECTION) {
7352            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7353                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7354                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7355        }
7356
7357        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7358            // We don't do this here during boot because we can do it all
7359            // at once after scanning all existing packages.
7360            //
7361            // We also do this *before* we perform dexopt on this package, so that
7362            // we can avoid redundant dexopts, and also to make sure we've got the
7363            // code and package path correct.
7364            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7365                    pkg, true /* boot complete */);
7366        }
7367
7368        if (mFactoryTest && pkg.requestedPermissions.contains(
7369                android.Manifest.permission.FACTORY_TEST)) {
7370            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7371        }
7372
7373        ArrayList<PackageParser.Package> clientLibPkgs = null;
7374
7375        // writer
7376        synchronized (mPackages) {
7377            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7378                // Only system apps can add new shared libraries.
7379                if (pkg.libraryNames != null) {
7380                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7381                        String name = pkg.libraryNames.get(i);
7382                        boolean allowed = false;
7383                        if (pkg.isUpdatedSystemApp()) {
7384                            // New library entries can only be added through the
7385                            // system image.  This is important to get rid of a lot
7386                            // of nasty edge cases: for example if we allowed a non-
7387                            // system update of the app to add a library, then uninstalling
7388                            // the update would make the library go away, and assumptions
7389                            // we made such as through app install filtering would now
7390                            // have allowed apps on the device which aren't compatible
7391                            // with it.  Better to just have the restriction here, be
7392                            // conservative, and create many fewer cases that can negatively
7393                            // impact the user experience.
7394                            final PackageSetting sysPs = mSettings
7395                                    .getDisabledSystemPkgLPr(pkg.packageName);
7396                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7397                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7398                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7399                                        allowed = true;
7400                                        break;
7401                                    }
7402                                }
7403                            }
7404                        } else {
7405                            allowed = true;
7406                        }
7407                        if (allowed) {
7408                            if (!mSharedLibraries.containsKey(name)) {
7409                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7410                            } else if (!name.equals(pkg.packageName)) {
7411                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7412                                        + name + " already exists; skipping");
7413                            }
7414                        } else {
7415                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7416                                    + name + " that is not declared on system image; skipping");
7417                        }
7418                    }
7419                    if ((scanFlags & SCAN_BOOTING) == 0) {
7420                        // If we are not booting, we need to update any applications
7421                        // that are clients of our shared library.  If we are booting,
7422                        // this will all be done once the scan is complete.
7423                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7424                    }
7425                }
7426            }
7427        }
7428
7429        // Request the ActivityManager to kill the process(only for existing packages)
7430        // so that we do not end up in a confused state while the user is still using the older
7431        // version of the application while the new one gets installed.
7432        if ((scanFlags & SCAN_REPLACING) != 0) {
7433            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7434
7435            killApplication(pkg.applicationInfo.packageName,
7436                        pkg.applicationInfo.uid, "replace pkg");
7437
7438            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7439        }
7440
7441        // Also need to kill any apps that are dependent on the library.
7442        if (clientLibPkgs != null) {
7443            for (int i=0; i<clientLibPkgs.size(); i++) {
7444                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7445                killApplication(clientPkg.applicationInfo.packageName,
7446                        clientPkg.applicationInfo.uid, "update lib");
7447            }
7448        }
7449
7450        // Make sure we're not adding any bogus keyset info
7451        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7452        ksms.assertScannedPackageValid(pkg);
7453
7454        // writer
7455        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7456
7457        boolean createIdmapFailed = false;
7458        synchronized (mPackages) {
7459            // We don't expect installation to fail beyond this point
7460
7461            // Add the new setting to mSettings
7462            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7463            // Add the new setting to mPackages
7464            mPackages.put(pkg.applicationInfo.packageName, pkg);
7465            // Make sure we don't accidentally delete its data.
7466            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7467            while (iter.hasNext()) {
7468                PackageCleanItem item = iter.next();
7469                if (pkgName.equals(item.packageName)) {
7470                    iter.remove();
7471                }
7472            }
7473
7474            // Take care of first install / last update times.
7475            if (currentTime != 0) {
7476                if (pkgSetting.firstInstallTime == 0) {
7477                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7478                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7479                    pkgSetting.lastUpdateTime = currentTime;
7480                }
7481            } else if (pkgSetting.firstInstallTime == 0) {
7482                // We need *something*.  Take time time stamp of the file.
7483                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7484            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7485                if (scanFileTime != pkgSetting.timeStamp) {
7486                    // A package on the system image has changed; consider this
7487                    // to be an update.
7488                    pkgSetting.lastUpdateTime = scanFileTime;
7489                }
7490            }
7491
7492            // Add the package's KeySets to the global KeySetManagerService
7493            ksms.addScannedPackageLPw(pkg);
7494
7495            int N = pkg.providers.size();
7496            StringBuilder r = null;
7497            int i;
7498            for (i=0; i<N; i++) {
7499                PackageParser.Provider p = pkg.providers.get(i);
7500                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7501                        p.info.processName, pkg.applicationInfo.uid);
7502                mProviders.addProvider(p);
7503                p.syncable = p.info.isSyncable;
7504                if (p.info.authority != null) {
7505                    String names[] = p.info.authority.split(";");
7506                    p.info.authority = null;
7507                    for (int j = 0; j < names.length; j++) {
7508                        if (j == 1 && p.syncable) {
7509                            // We only want the first authority for a provider to possibly be
7510                            // syncable, so if we already added this provider using a different
7511                            // authority clear the syncable flag. We copy the provider before
7512                            // changing it because the mProviders object contains a reference
7513                            // to a provider that we don't want to change.
7514                            // Only do this for the second authority since the resulting provider
7515                            // object can be the same for all future authorities for this provider.
7516                            p = new PackageParser.Provider(p);
7517                            p.syncable = false;
7518                        }
7519                        if (!mProvidersByAuthority.containsKey(names[j])) {
7520                            mProvidersByAuthority.put(names[j], p);
7521                            if (p.info.authority == null) {
7522                                p.info.authority = names[j];
7523                            } else {
7524                                p.info.authority = p.info.authority + ";" + names[j];
7525                            }
7526                            if (DEBUG_PACKAGE_SCANNING) {
7527                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7528                                    Log.d(TAG, "Registered content provider: " + names[j]
7529                                            + ", className = " + p.info.name + ", isSyncable = "
7530                                            + p.info.isSyncable);
7531                            }
7532                        } else {
7533                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7534                            Slog.w(TAG, "Skipping provider name " + names[j] +
7535                                    " (in package " + pkg.applicationInfo.packageName +
7536                                    "): name already used by "
7537                                    + ((other != null && other.getComponentName() != null)
7538                                            ? other.getComponentName().getPackageName() : "?"));
7539                        }
7540                    }
7541                }
7542                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7543                    if (r == null) {
7544                        r = new StringBuilder(256);
7545                    } else {
7546                        r.append(' ');
7547                    }
7548                    r.append(p.info.name);
7549                }
7550            }
7551            if (r != null) {
7552                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7553            }
7554
7555            N = pkg.services.size();
7556            r = null;
7557            for (i=0; i<N; i++) {
7558                PackageParser.Service s = pkg.services.get(i);
7559                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7560                        s.info.processName, pkg.applicationInfo.uid);
7561                mServices.addService(s);
7562                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7563                    if (r == null) {
7564                        r = new StringBuilder(256);
7565                    } else {
7566                        r.append(' ');
7567                    }
7568                    r.append(s.info.name);
7569                }
7570            }
7571            if (r != null) {
7572                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7573            }
7574
7575            N = pkg.receivers.size();
7576            r = null;
7577            for (i=0; i<N; i++) {
7578                PackageParser.Activity a = pkg.receivers.get(i);
7579                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7580                        a.info.processName, pkg.applicationInfo.uid);
7581                mReceivers.addActivity(a, "receiver");
7582                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7583                    if (r == null) {
7584                        r = new StringBuilder(256);
7585                    } else {
7586                        r.append(' ');
7587                    }
7588                    r.append(a.info.name);
7589                }
7590            }
7591            if (r != null) {
7592                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7593            }
7594
7595            N = pkg.activities.size();
7596            r = null;
7597            for (i=0; i<N; i++) {
7598                PackageParser.Activity a = pkg.activities.get(i);
7599                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7600                        a.info.processName, pkg.applicationInfo.uid);
7601                mActivities.addActivity(a, "activity");
7602                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7603                    if (r == null) {
7604                        r = new StringBuilder(256);
7605                    } else {
7606                        r.append(' ');
7607                    }
7608                    r.append(a.info.name);
7609                }
7610            }
7611            if (r != null) {
7612                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7613            }
7614
7615            N = pkg.permissionGroups.size();
7616            r = null;
7617            for (i=0; i<N; i++) {
7618                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7619                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7620                if (cur == null) {
7621                    mPermissionGroups.put(pg.info.name, pg);
7622                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7623                        if (r == null) {
7624                            r = new StringBuilder(256);
7625                        } else {
7626                            r.append(' ');
7627                        }
7628                        r.append(pg.info.name);
7629                    }
7630                } else {
7631                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7632                            + pg.info.packageName + " ignored: original from "
7633                            + cur.info.packageName);
7634                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7635                        if (r == null) {
7636                            r = new StringBuilder(256);
7637                        } else {
7638                            r.append(' ');
7639                        }
7640                        r.append("DUP:");
7641                        r.append(pg.info.name);
7642                    }
7643                }
7644            }
7645            if (r != null) {
7646                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7647            }
7648
7649            N = pkg.permissions.size();
7650            r = null;
7651            for (i=0; i<N; i++) {
7652                PackageParser.Permission p = pkg.permissions.get(i);
7653
7654                // Assume by default that we did not install this permission into the system.
7655                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7656
7657                // Now that permission groups have a special meaning, we ignore permission
7658                // groups for legacy apps to prevent unexpected behavior. In particular,
7659                // permissions for one app being granted to someone just becuase they happen
7660                // to be in a group defined by another app (before this had no implications).
7661                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7662                    p.group = mPermissionGroups.get(p.info.group);
7663                    // Warn for a permission in an unknown group.
7664                    if (p.info.group != null && p.group == null) {
7665                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7666                                + p.info.packageName + " in an unknown group " + p.info.group);
7667                    }
7668                }
7669
7670                ArrayMap<String, BasePermission> permissionMap =
7671                        p.tree ? mSettings.mPermissionTrees
7672                                : mSettings.mPermissions;
7673                BasePermission bp = permissionMap.get(p.info.name);
7674
7675                // Allow system apps to redefine non-system permissions
7676                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7677                    final boolean currentOwnerIsSystem = (bp.perm != null
7678                            && isSystemApp(bp.perm.owner));
7679                    if (isSystemApp(p.owner)) {
7680                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7681                            // It's a built-in permission and no owner, take ownership now
7682                            bp.packageSetting = pkgSetting;
7683                            bp.perm = p;
7684                            bp.uid = pkg.applicationInfo.uid;
7685                            bp.sourcePackage = p.info.packageName;
7686                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7687                        } else if (!currentOwnerIsSystem) {
7688                            String msg = "New decl " + p.owner + " of permission  "
7689                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7690                            reportSettingsProblem(Log.WARN, msg);
7691                            bp = null;
7692                        }
7693                    }
7694                }
7695
7696                if (bp == null) {
7697                    bp = new BasePermission(p.info.name, p.info.packageName,
7698                            BasePermission.TYPE_NORMAL);
7699                    permissionMap.put(p.info.name, bp);
7700                }
7701
7702                if (bp.perm == null) {
7703                    if (bp.sourcePackage == null
7704                            || bp.sourcePackage.equals(p.info.packageName)) {
7705                        BasePermission tree = findPermissionTreeLP(p.info.name);
7706                        if (tree == null
7707                                || tree.sourcePackage.equals(p.info.packageName)) {
7708                            bp.packageSetting = pkgSetting;
7709                            bp.perm = p;
7710                            bp.uid = pkg.applicationInfo.uid;
7711                            bp.sourcePackage = p.info.packageName;
7712                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7713                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7714                                if (r == null) {
7715                                    r = new StringBuilder(256);
7716                                } else {
7717                                    r.append(' ');
7718                                }
7719                                r.append(p.info.name);
7720                            }
7721                        } else {
7722                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7723                                    + p.info.packageName + " ignored: base tree "
7724                                    + tree.name + " is from package "
7725                                    + tree.sourcePackage);
7726                        }
7727                    } else {
7728                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7729                                + p.info.packageName + " ignored: original from "
7730                                + bp.sourcePackage);
7731                    }
7732                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7733                    if (r == null) {
7734                        r = new StringBuilder(256);
7735                    } else {
7736                        r.append(' ');
7737                    }
7738                    r.append("DUP:");
7739                    r.append(p.info.name);
7740                }
7741                if (bp.perm == p) {
7742                    bp.protectionLevel = p.info.protectionLevel;
7743                }
7744            }
7745
7746            if (r != null) {
7747                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7748            }
7749
7750            N = pkg.instrumentation.size();
7751            r = null;
7752            for (i=0; i<N; i++) {
7753                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7754                a.info.packageName = pkg.applicationInfo.packageName;
7755                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7756                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7757                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7758                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7759                a.info.dataDir = pkg.applicationInfo.dataDir;
7760                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7761                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7762
7763                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7764                // need other information about the application, like the ABI and what not ?
7765                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7766                mInstrumentation.put(a.getComponentName(), a);
7767                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7768                    if (r == null) {
7769                        r = new StringBuilder(256);
7770                    } else {
7771                        r.append(' ');
7772                    }
7773                    r.append(a.info.name);
7774                }
7775            }
7776            if (r != null) {
7777                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7778            }
7779
7780            if (pkg.protectedBroadcasts != null) {
7781                N = pkg.protectedBroadcasts.size();
7782                for (i=0; i<N; i++) {
7783                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7784                }
7785            }
7786
7787            pkgSetting.setTimeStamp(scanFileTime);
7788
7789            // Create idmap files for pairs of (packages, overlay packages).
7790            // Note: "android", ie framework-res.apk, is handled by native layers.
7791            if (pkg.mOverlayTarget != null) {
7792                // This is an overlay package.
7793                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7794                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7795                        mOverlays.put(pkg.mOverlayTarget,
7796                                new ArrayMap<String, PackageParser.Package>());
7797                    }
7798                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7799                    map.put(pkg.packageName, pkg);
7800                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7801                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7802                        createIdmapFailed = true;
7803                    }
7804                }
7805            } else if (mOverlays.containsKey(pkg.packageName) &&
7806                    !pkg.packageName.equals("android")) {
7807                // This is a regular package, with one or more known overlay packages.
7808                createIdmapsForPackageLI(pkg);
7809            }
7810        }
7811
7812        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7813
7814        if (createIdmapFailed) {
7815            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7816                    "scanPackageLI failed to createIdmap");
7817        }
7818        return pkg;
7819    }
7820
7821    /**
7822     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7823     * is derived purely on the basis of the contents of {@code scanFile} and
7824     * {@code cpuAbiOverride}.
7825     *
7826     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7827     */
7828    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7829                                 String cpuAbiOverride, boolean extractLibs)
7830            throws PackageManagerException {
7831        // TODO: We can probably be smarter about this stuff. For installed apps,
7832        // we can calculate this information at install time once and for all. For
7833        // system apps, we can probably assume that this information doesn't change
7834        // after the first boot scan. As things stand, we do lots of unnecessary work.
7835
7836        // Give ourselves some initial paths; we'll come back for another
7837        // pass once we've determined ABI below.
7838        setNativeLibraryPaths(pkg);
7839
7840        // We would never need to extract libs for forward-locked and external packages,
7841        // since the container service will do it for us. We shouldn't attempt to
7842        // extract libs from system app when it was not updated.
7843        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7844                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7845            extractLibs = false;
7846        }
7847
7848        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7849        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7850
7851        NativeLibraryHelper.Handle handle = null;
7852        try {
7853            handle = NativeLibraryHelper.Handle.create(pkg);
7854            // TODO(multiArch): This can be null for apps that didn't go through the
7855            // usual installation process. We can calculate it again, like we
7856            // do during install time.
7857            //
7858            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7859            // unnecessary.
7860            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7861
7862            // Null out the abis so that they can be recalculated.
7863            pkg.applicationInfo.primaryCpuAbi = null;
7864            pkg.applicationInfo.secondaryCpuAbi = null;
7865            if (isMultiArch(pkg.applicationInfo)) {
7866                // Warn if we've set an abiOverride for multi-lib packages..
7867                // By definition, we need to copy both 32 and 64 bit libraries for
7868                // such packages.
7869                if (pkg.cpuAbiOverride != null
7870                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7871                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7872                }
7873
7874                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7875                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7876                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7877                    if (extractLibs) {
7878                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7879                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7880                                useIsaSpecificSubdirs);
7881                    } else {
7882                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7883                    }
7884                }
7885
7886                maybeThrowExceptionForMultiArchCopy(
7887                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7888
7889                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7890                    if (extractLibs) {
7891                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7892                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7893                                useIsaSpecificSubdirs);
7894                    } else {
7895                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7896                    }
7897                }
7898
7899                maybeThrowExceptionForMultiArchCopy(
7900                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7901
7902                if (abi64 >= 0) {
7903                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7904                }
7905
7906                if (abi32 >= 0) {
7907                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7908                    if (abi64 >= 0) {
7909                        pkg.applicationInfo.secondaryCpuAbi = abi;
7910                    } else {
7911                        pkg.applicationInfo.primaryCpuAbi = abi;
7912                    }
7913                }
7914            } else {
7915                String[] abiList = (cpuAbiOverride != null) ?
7916                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7917
7918                // Enable gross and lame hacks for apps that are built with old
7919                // SDK tools. We must scan their APKs for renderscript bitcode and
7920                // not launch them if it's present. Don't bother checking on devices
7921                // that don't have 64 bit support.
7922                boolean needsRenderScriptOverride = false;
7923                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7924                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7925                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7926                    needsRenderScriptOverride = true;
7927                }
7928
7929                final int copyRet;
7930                if (extractLibs) {
7931                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7932                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7933                } else {
7934                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7935                }
7936
7937                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7938                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7939                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7940                }
7941
7942                if (copyRet >= 0) {
7943                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7944                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7945                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7946                } else if (needsRenderScriptOverride) {
7947                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7948                }
7949            }
7950        } catch (IOException ioe) {
7951            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7952        } finally {
7953            IoUtils.closeQuietly(handle);
7954        }
7955
7956        // Now that we've calculated the ABIs and determined if it's an internal app,
7957        // we will go ahead and populate the nativeLibraryPath.
7958        setNativeLibraryPaths(pkg);
7959    }
7960
7961    /**
7962     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7963     * i.e, so that all packages can be run inside a single process if required.
7964     *
7965     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7966     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7967     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7968     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7969     * updating a package that belongs to a shared user.
7970     *
7971     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7972     * adds unnecessary complexity.
7973     */
7974    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7975            PackageParser.Package scannedPackage, boolean bootComplete) {
7976        String requiredInstructionSet = null;
7977        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7978            requiredInstructionSet = VMRuntime.getInstructionSet(
7979                     scannedPackage.applicationInfo.primaryCpuAbi);
7980        }
7981
7982        PackageSetting requirer = null;
7983        for (PackageSetting ps : packagesForUser) {
7984            // If packagesForUser contains scannedPackage, we skip it. This will happen
7985            // when scannedPackage is an update of an existing package. Without this check,
7986            // we will never be able to change the ABI of any package belonging to a shared
7987            // user, even if it's compatible with other packages.
7988            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7989                if (ps.primaryCpuAbiString == null) {
7990                    continue;
7991                }
7992
7993                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7994                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7995                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7996                    // this but there's not much we can do.
7997                    String errorMessage = "Instruction set mismatch, "
7998                            + ((requirer == null) ? "[caller]" : requirer)
7999                            + " requires " + requiredInstructionSet + " whereas " + ps
8000                            + " requires " + instructionSet;
8001                    Slog.w(TAG, errorMessage);
8002                }
8003
8004                if (requiredInstructionSet == null) {
8005                    requiredInstructionSet = instructionSet;
8006                    requirer = ps;
8007                }
8008            }
8009        }
8010
8011        if (requiredInstructionSet != null) {
8012            String adjustedAbi;
8013            if (requirer != null) {
8014                // requirer != null implies that either scannedPackage was null or that scannedPackage
8015                // did not require an ABI, in which case we have to adjust scannedPackage to match
8016                // the ABI of the set (which is the same as requirer's ABI)
8017                adjustedAbi = requirer.primaryCpuAbiString;
8018                if (scannedPackage != null) {
8019                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8020                }
8021            } else {
8022                // requirer == null implies that we're updating all ABIs in the set to
8023                // match scannedPackage.
8024                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8025            }
8026
8027            for (PackageSetting ps : packagesForUser) {
8028                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8029                    if (ps.primaryCpuAbiString != null) {
8030                        continue;
8031                    }
8032
8033                    ps.primaryCpuAbiString = adjustedAbi;
8034                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8035                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8036                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8037                        mInstaller.rmdex(ps.codePathString,
8038                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8039                    }
8040                }
8041            }
8042        }
8043    }
8044
8045    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8046        synchronized (mPackages) {
8047            mResolverReplaced = true;
8048            // Set up information for custom user intent resolution activity.
8049            mResolveActivity.applicationInfo = pkg.applicationInfo;
8050            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8051            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8052            mResolveActivity.processName = pkg.applicationInfo.packageName;
8053            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8054            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8055                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8056            mResolveActivity.theme = 0;
8057            mResolveActivity.exported = true;
8058            mResolveActivity.enabled = true;
8059            mResolveInfo.activityInfo = mResolveActivity;
8060            mResolveInfo.priority = 0;
8061            mResolveInfo.preferredOrder = 0;
8062            mResolveInfo.match = 0;
8063            mResolveComponentName = mCustomResolverComponentName;
8064            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8065                    mResolveComponentName);
8066        }
8067    }
8068
8069    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8070        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8071
8072        // Set up information for ephemeral installer activity
8073        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8074        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8075        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8076        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8077        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8078        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8079                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8080        mEphemeralInstallerActivity.theme = 0;
8081        mEphemeralInstallerActivity.exported = true;
8082        mEphemeralInstallerActivity.enabled = true;
8083        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8084        mEphemeralInstallerInfo.priority = 0;
8085        mEphemeralInstallerInfo.preferredOrder = 0;
8086        mEphemeralInstallerInfo.match = 0;
8087
8088        if (DEBUG_EPHEMERAL) {
8089            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8090        }
8091    }
8092
8093    private static String calculateBundledApkRoot(final String codePathString) {
8094        final File codePath = new File(codePathString);
8095        final File codeRoot;
8096        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8097            codeRoot = Environment.getRootDirectory();
8098        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8099            codeRoot = Environment.getOemDirectory();
8100        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8101            codeRoot = Environment.getVendorDirectory();
8102        } else {
8103            // Unrecognized code path; take its top real segment as the apk root:
8104            // e.g. /something/app/blah.apk => /something
8105            try {
8106                File f = codePath.getCanonicalFile();
8107                File parent = f.getParentFile();    // non-null because codePath is a file
8108                File tmp;
8109                while ((tmp = parent.getParentFile()) != null) {
8110                    f = parent;
8111                    parent = tmp;
8112                }
8113                codeRoot = f;
8114                Slog.w(TAG, "Unrecognized code path "
8115                        + codePath + " - using " + codeRoot);
8116            } catch (IOException e) {
8117                // Can't canonicalize the code path -- shenanigans?
8118                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8119                return Environment.getRootDirectory().getPath();
8120            }
8121        }
8122        return codeRoot.getPath();
8123    }
8124
8125    /**
8126     * Derive and set the location of native libraries for the given package,
8127     * which varies depending on where and how the package was installed.
8128     */
8129    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8130        final ApplicationInfo info = pkg.applicationInfo;
8131        final String codePath = pkg.codePath;
8132        final File codeFile = new File(codePath);
8133        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8134        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8135
8136        info.nativeLibraryRootDir = null;
8137        info.nativeLibraryRootRequiresIsa = false;
8138        info.nativeLibraryDir = null;
8139        info.secondaryNativeLibraryDir = null;
8140
8141        if (isApkFile(codeFile)) {
8142            // Monolithic install
8143            if (bundledApp) {
8144                // If "/system/lib64/apkname" exists, assume that is the per-package
8145                // native library directory to use; otherwise use "/system/lib/apkname".
8146                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8147                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8148                        getPrimaryInstructionSet(info));
8149
8150                // This is a bundled system app so choose the path based on the ABI.
8151                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8152                // is just the default path.
8153                final String apkName = deriveCodePathName(codePath);
8154                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8155                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8156                        apkName).getAbsolutePath();
8157
8158                if (info.secondaryCpuAbi != null) {
8159                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8160                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8161                            secondaryLibDir, apkName).getAbsolutePath();
8162                }
8163            } else if (asecApp) {
8164                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8165                        .getAbsolutePath();
8166            } else {
8167                final String apkName = deriveCodePathName(codePath);
8168                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8169                        .getAbsolutePath();
8170            }
8171
8172            info.nativeLibraryRootRequiresIsa = false;
8173            info.nativeLibraryDir = info.nativeLibraryRootDir;
8174        } else {
8175            // Cluster install
8176            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8177            info.nativeLibraryRootRequiresIsa = true;
8178
8179            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8180                    getPrimaryInstructionSet(info)).getAbsolutePath();
8181
8182            if (info.secondaryCpuAbi != null) {
8183                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8184                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8185            }
8186        }
8187    }
8188
8189    /**
8190     * Calculate the abis and roots for a bundled app. These can uniquely
8191     * be determined from the contents of the system partition, i.e whether
8192     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8193     * of this information, and instead assume that the system was built
8194     * sensibly.
8195     */
8196    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8197                                           PackageSetting pkgSetting) {
8198        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8199
8200        // If "/system/lib64/apkname" exists, assume that is the per-package
8201        // native library directory to use; otherwise use "/system/lib/apkname".
8202        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8203        setBundledAppAbi(pkg, apkRoot, apkName);
8204        // pkgSetting might be null during rescan following uninstall of updates
8205        // to a bundled app, so accommodate that possibility.  The settings in
8206        // that case will be established later from the parsed package.
8207        //
8208        // If the settings aren't null, sync them up with what we've just derived.
8209        // note that apkRoot isn't stored in the package settings.
8210        if (pkgSetting != null) {
8211            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8212            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8213        }
8214    }
8215
8216    /**
8217     * Deduces the ABI of a bundled app and sets the relevant fields on the
8218     * parsed pkg object.
8219     *
8220     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8221     *        under which system libraries are installed.
8222     * @param apkName the name of the installed package.
8223     */
8224    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8225        final File codeFile = new File(pkg.codePath);
8226
8227        final boolean has64BitLibs;
8228        final boolean has32BitLibs;
8229        if (isApkFile(codeFile)) {
8230            // Monolithic install
8231            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8232            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8233        } else {
8234            // Cluster install
8235            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8236            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8237                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8238                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8239                has64BitLibs = (new File(rootDir, isa)).exists();
8240            } else {
8241                has64BitLibs = false;
8242            }
8243            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8244                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8245                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8246                has32BitLibs = (new File(rootDir, isa)).exists();
8247            } else {
8248                has32BitLibs = false;
8249            }
8250        }
8251
8252        if (has64BitLibs && !has32BitLibs) {
8253            // The package has 64 bit libs, but not 32 bit libs. Its primary
8254            // ABI should be 64 bit. We can safely assume here that the bundled
8255            // native libraries correspond to the most preferred ABI in the list.
8256
8257            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8258            pkg.applicationInfo.secondaryCpuAbi = null;
8259        } else if (has32BitLibs && !has64BitLibs) {
8260            // The package has 32 bit libs but not 64 bit libs. Its primary
8261            // ABI should be 32 bit.
8262
8263            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8264            pkg.applicationInfo.secondaryCpuAbi = null;
8265        } else if (has32BitLibs && has64BitLibs) {
8266            // The application has both 64 and 32 bit bundled libraries. We check
8267            // here that the app declares multiArch support, and warn if it doesn't.
8268            //
8269            // We will be lenient here and record both ABIs. The primary will be the
8270            // ABI that's higher on the list, i.e, a device that's configured to prefer
8271            // 64 bit apps will see a 64 bit primary ABI,
8272
8273            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8274                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8275            }
8276
8277            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8278                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8279                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8280            } else {
8281                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8282                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8283            }
8284        } else {
8285            pkg.applicationInfo.primaryCpuAbi = null;
8286            pkg.applicationInfo.secondaryCpuAbi = null;
8287        }
8288    }
8289
8290    private void killApplication(String pkgName, int appId, String reason) {
8291        // Request the ActivityManager to kill the process(only for existing packages)
8292        // so that we do not end up in a confused state while the user is still using the older
8293        // version of the application while the new one gets installed.
8294        IActivityManager am = ActivityManagerNative.getDefault();
8295        if (am != null) {
8296            try {
8297                am.killApplicationWithAppId(pkgName, appId, reason);
8298            } catch (RemoteException e) {
8299            }
8300        }
8301    }
8302
8303    void removePackageLI(PackageSetting ps, boolean chatty) {
8304        if (DEBUG_INSTALL) {
8305            if (chatty)
8306                Log.d(TAG, "Removing package " + ps.name);
8307        }
8308
8309        // writer
8310        synchronized (mPackages) {
8311            mPackages.remove(ps.name);
8312            final PackageParser.Package pkg = ps.pkg;
8313            if (pkg != null) {
8314                cleanPackageDataStructuresLILPw(pkg, chatty);
8315            }
8316        }
8317    }
8318
8319    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8320        if (DEBUG_INSTALL) {
8321            if (chatty)
8322                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8323        }
8324
8325        // writer
8326        synchronized (mPackages) {
8327            mPackages.remove(pkg.applicationInfo.packageName);
8328            cleanPackageDataStructuresLILPw(pkg, chatty);
8329        }
8330    }
8331
8332    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8333        int N = pkg.providers.size();
8334        StringBuilder r = null;
8335        int i;
8336        for (i=0; i<N; i++) {
8337            PackageParser.Provider p = pkg.providers.get(i);
8338            mProviders.removeProvider(p);
8339            if (p.info.authority == null) {
8340
8341                /* There was another ContentProvider with this authority when
8342                 * this app was installed so this authority is null,
8343                 * Ignore it as we don't have to unregister the provider.
8344                 */
8345                continue;
8346            }
8347            String names[] = p.info.authority.split(";");
8348            for (int j = 0; j < names.length; j++) {
8349                if (mProvidersByAuthority.get(names[j]) == p) {
8350                    mProvidersByAuthority.remove(names[j]);
8351                    if (DEBUG_REMOVE) {
8352                        if (chatty)
8353                            Log.d(TAG, "Unregistered content provider: " + names[j]
8354                                    + ", className = " + p.info.name + ", isSyncable = "
8355                                    + p.info.isSyncable);
8356                    }
8357                }
8358            }
8359            if (DEBUG_REMOVE && chatty) {
8360                if (r == null) {
8361                    r = new StringBuilder(256);
8362                } else {
8363                    r.append(' ');
8364                }
8365                r.append(p.info.name);
8366            }
8367        }
8368        if (r != null) {
8369            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8370        }
8371
8372        N = pkg.services.size();
8373        r = null;
8374        for (i=0; i<N; i++) {
8375            PackageParser.Service s = pkg.services.get(i);
8376            mServices.removeService(s);
8377            if (chatty) {
8378                if (r == null) {
8379                    r = new StringBuilder(256);
8380                } else {
8381                    r.append(' ');
8382                }
8383                r.append(s.info.name);
8384            }
8385        }
8386        if (r != null) {
8387            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8388        }
8389
8390        N = pkg.receivers.size();
8391        r = null;
8392        for (i=0; i<N; i++) {
8393            PackageParser.Activity a = pkg.receivers.get(i);
8394            mReceivers.removeActivity(a, "receiver");
8395            if (DEBUG_REMOVE && chatty) {
8396                if (r == null) {
8397                    r = new StringBuilder(256);
8398                } else {
8399                    r.append(' ');
8400                }
8401                r.append(a.info.name);
8402            }
8403        }
8404        if (r != null) {
8405            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8406        }
8407
8408        N = pkg.activities.size();
8409        r = null;
8410        for (i=0; i<N; i++) {
8411            PackageParser.Activity a = pkg.activities.get(i);
8412            mActivities.removeActivity(a, "activity");
8413            if (DEBUG_REMOVE && chatty) {
8414                if (r == null) {
8415                    r = new StringBuilder(256);
8416                } else {
8417                    r.append(' ');
8418                }
8419                r.append(a.info.name);
8420            }
8421        }
8422        if (r != null) {
8423            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8424        }
8425
8426        N = pkg.permissions.size();
8427        r = null;
8428        for (i=0; i<N; i++) {
8429            PackageParser.Permission p = pkg.permissions.get(i);
8430            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8431            if (bp == null) {
8432                bp = mSettings.mPermissionTrees.get(p.info.name);
8433            }
8434            if (bp != null && bp.perm == p) {
8435                bp.perm = null;
8436                if (DEBUG_REMOVE && chatty) {
8437                    if (r == null) {
8438                        r = new StringBuilder(256);
8439                    } else {
8440                        r.append(' ');
8441                    }
8442                    r.append(p.info.name);
8443                }
8444            }
8445            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8446                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8447                if (appOpPkgs != null) {
8448                    appOpPkgs.remove(pkg.packageName);
8449                }
8450            }
8451        }
8452        if (r != null) {
8453            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8454        }
8455
8456        N = pkg.requestedPermissions.size();
8457        r = null;
8458        for (i=0; i<N; i++) {
8459            String perm = pkg.requestedPermissions.get(i);
8460            BasePermission bp = mSettings.mPermissions.get(perm);
8461            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8462                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8463                if (appOpPkgs != null) {
8464                    appOpPkgs.remove(pkg.packageName);
8465                    if (appOpPkgs.isEmpty()) {
8466                        mAppOpPermissionPackages.remove(perm);
8467                    }
8468                }
8469            }
8470        }
8471        if (r != null) {
8472            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8473        }
8474
8475        N = pkg.instrumentation.size();
8476        r = null;
8477        for (i=0; i<N; i++) {
8478            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8479            mInstrumentation.remove(a.getComponentName());
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, "  Instrumentation: " + r);
8491        }
8492
8493        r = null;
8494        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8495            // Only system apps can hold shared libraries.
8496            if (pkg.libraryNames != null) {
8497                for (i=0; i<pkg.libraryNames.size(); i++) {
8498                    String name = pkg.libraryNames.get(i);
8499                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8500                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8501                        mSharedLibraries.remove(name);
8502                        if (DEBUG_REMOVE && chatty) {
8503                            if (r == null) {
8504                                r = new StringBuilder(256);
8505                            } else {
8506                                r.append(' ');
8507                            }
8508                            r.append(name);
8509                        }
8510                    }
8511                }
8512            }
8513        }
8514        if (r != null) {
8515            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8516        }
8517    }
8518
8519    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8520        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8521            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8522                return true;
8523            }
8524        }
8525        return false;
8526    }
8527
8528    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8529    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8530    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8531
8532    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8533            int flags) {
8534        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8535        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8536    }
8537
8538    private void updatePermissionsLPw(String changingPkg,
8539            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8540        // Make sure there are no dangling permission trees.
8541        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8542        while (it.hasNext()) {
8543            final BasePermission bp = it.next();
8544            if (bp.packageSetting == null) {
8545                // We may not yet have parsed the package, so just see if
8546                // we still know about its settings.
8547                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8548            }
8549            if (bp.packageSetting == null) {
8550                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8551                        + " from package " + bp.sourcePackage);
8552                it.remove();
8553            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8554                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8555                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8556                            + " from package " + bp.sourcePackage);
8557                    flags |= UPDATE_PERMISSIONS_ALL;
8558                    it.remove();
8559                }
8560            }
8561        }
8562
8563        // Make sure all dynamic permissions have been assigned to a package,
8564        // and make sure there are no dangling permissions.
8565        it = mSettings.mPermissions.values().iterator();
8566        while (it.hasNext()) {
8567            final BasePermission bp = it.next();
8568            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8569                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8570                        + bp.name + " pkg=" + bp.sourcePackage
8571                        + " info=" + bp.pendingInfo);
8572                if (bp.packageSetting == null && bp.pendingInfo != null) {
8573                    final BasePermission tree = findPermissionTreeLP(bp.name);
8574                    if (tree != null && tree.perm != null) {
8575                        bp.packageSetting = tree.packageSetting;
8576                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8577                                new PermissionInfo(bp.pendingInfo));
8578                        bp.perm.info.packageName = tree.perm.info.packageName;
8579                        bp.perm.info.name = bp.name;
8580                        bp.uid = tree.uid;
8581                    }
8582                }
8583            }
8584            if (bp.packageSetting == null) {
8585                // We may not yet have parsed the package, so just see if
8586                // we still know about its settings.
8587                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8588            }
8589            if (bp.packageSetting == null) {
8590                Slog.w(TAG, "Removing dangling permission: " + bp.name
8591                        + " from package " + bp.sourcePackage);
8592                it.remove();
8593            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8594                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8595                    Slog.i(TAG, "Removing old permission: " + bp.name
8596                            + " from package " + bp.sourcePackage);
8597                    flags |= UPDATE_PERMISSIONS_ALL;
8598                    it.remove();
8599                }
8600            }
8601        }
8602
8603        // Now update the permissions for all packages, in particular
8604        // replace the granted permissions of the system packages.
8605        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8606            for (PackageParser.Package pkg : mPackages.values()) {
8607                if (pkg != pkgInfo) {
8608                    // Only replace for packages on requested volume
8609                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8610                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8611                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8612                    grantPermissionsLPw(pkg, replace, changingPkg);
8613                }
8614            }
8615        }
8616
8617        if (pkgInfo != null) {
8618            // Only replace for packages on requested volume
8619            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8620            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8621                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8622            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8623        }
8624    }
8625
8626    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8627            String packageOfInterest) {
8628        // IMPORTANT: There are two types of permissions: install and runtime.
8629        // Install time permissions are granted when the app is installed to
8630        // all device users and users added in the future. Runtime permissions
8631        // are granted at runtime explicitly to specific users. Normal and signature
8632        // protected permissions are install time permissions. Dangerous permissions
8633        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8634        // otherwise they are runtime permissions. This function does not manage
8635        // runtime permissions except for the case an app targeting Lollipop MR1
8636        // being upgraded to target a newer SDK, in which case dangerous permissions
8637        // are transformed from install time to runtime ones.
8638
8639        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8640        if (ps == null) {
8641            return;
8642        }
8643
8644        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8645
8646        PermissionsState permissionsState = ps.getPermissionsState();
8647        PermissionsState origPermissions = permissionsState;
8648
8649        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8650
8651        boolean runtimePermissionsRevoked = false;
8652        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8653
8654        boolean changedInstallPermission = false;
8655
8656        if (replace) {
8657            ps.installPermissionsFixed = false;
8658            if (!ps.isSharedUser()) {
8659                origPermissions = new PermissionsState(permissionsState);
8660                permissionsState.reset();
8661            } else {
8662                // We need to know only about runtime permission changes since the
8663                // calling code always writes the install permissions state but
8664                // the runtime ones are written only if changed. The only cases of
8665                // changed runtime permissions here are promotion of an install to
8666                // runtime and revocation of a runtime from a shared user.
8667                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8668                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8669                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8670                    runtimePermissionsRevoked = true;
8671                }
8672            }
8673        }
8674
8675        permissionsState.setGlobalGids(mGlobalGids);
8676
8677        final int N = pkg.requestedPermissions.size();
8678        for (int i=0; i<N; i++) {
8679            final String name = pkg.requestedPermissions.get(i);
8680            final BasePermission bp = mSettings.mPermissions.get(name);
8681
8682            if (DEBUG_INSTALL) {
8683                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8684            }
8685
8686            if (bp == null || bp.packageSetting == null) {
8687                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8688                    Slog.w(TAG, "Unknown permission " + name
8689                            + " in package " + pkg.packageName);
8690                }
8691                continue;
8692            }
8693
8694            final String perm = bp.name;
8695            boolean allowedSig = false;
8696            int grant = GRANT_DENIED;
8697
8698            // Keep track of app op permissions.
8699            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8700                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8701                if (pkgs == null) {
8702                    pkgs = new ArraySet<>();
8703                    mAppOpPermissionPackages.put(bp.name, pkgs);
8704                }
8705                pkgs.add(pkg.packageName);
8706            }
8707
8708            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8709            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8710                    >= Build.VERSION_CODES.M;
8711            switch (level) {
8712                case PermissionInfo.PROTECTION_NORMAL: {
8713                    // For all apps normal permissions are install time ones.
8714                    grant = GRANT_INSTALL;
8715                } break;
8716
8717                case PermissionInfo.PROTECTION_DANGEROUS: {
8718                    // If a permission review is required for legacy apps we represent
8719                    // their permissions as always granted runtime ones since we need
8720                    // to keep the review required permission flag per user while an
8721                    // install permission's state is shared across all users.
8722                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8723                        // For legacy apps dangerous permissions are install time ones.
8724                        grant = GRANT_INSTALL;
8725                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8726                        // For legacy apps that became modern, install becomes runtime.
8727                        grant = GRANT_UPGRADE;
8728                    } else if (mPromoteSystemApps
8729                            && isSystemApp(ps)
8730                            && mExistingSystemPackages.contains(ps.name)) {
8731                        // For legacy system apps, install becomes runtime.
8732                        // We cannot check hasInstallPermission() for system apps since those
8733                        // permissions were granted implicitly and not persisted pre-M.
8734                        grant = GRANT_UPGRADE;
8735                    } else {
8736                        // For modern apps keep runtime permissions unchanged.
8737                        grant = GRANT_RUNTIME;
8738                    }
8739                } break;
8740
8741                case PermissionInfo.PROTECTION_SIGNATURE: {
8742                    // For all apps signature permissions are install time ones.
8743                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8744                    if (allowedSig) {
8745                        grant = GRANT_INSTALL;
8746                    }
8747                } break;
8748            }
8749
8750            if (DEBUG_INSTALL) {
8751                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8752            }
8753
8754            if (grant != GRANT_DENIED) {
8755                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8756                    // If this is an existing, non-system package, then
8757                    // we can't add any new permissions to it.
8758                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8759                        // Except...  if this is a permission that was added
8760                        // to the platform (note: need to only do this when
8761                        // updating the platform).
8762                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8763                            grant = GRANT_DENIED;
8764                        }
8765                    }
8766                }
8767
8768                switch (grant) {
8769                    case GRANT_INSTALL: {
8770                        // Revoke this as runtime permission to handle the case of
8771                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8772                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8773                            if (origPermissions.getRuntimePermissionState(
8774                                    bp.name, userId) != null) {
8775                                // Revoke the runtime permission and clear the flags.
8776                                origPermissions.revokeRuntimePermission(bp, userId);
8777                                origPermissions.updatePermissionFlags(bp, userId,
8778                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8779                                // If we revoked a permission permission, we have to write.
8780                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8781                                        changedRuntimePermissionUserIds, userId);
8782                            }
8783                        }
8784                        // Grant an install permission.
8785                        if (permissionsState.grantInstallPermission(bp) !=
8786                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8787                            changedInstallPermission = true;
8788                        }
8789                    } break;
8790
8791                    case GRANT_RUNTIME: {
8792                        // Grant previously granted runtime permissions.
8793                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8794                            PermissionState permissionState = origPermissions
8795                                    .getRuntimePermissionState(bp.name, userId);
8796                            int flags = permissionState != null
8797                                    ? permissionState.getFlags() : 0;
8798                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8799                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8800                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8801                                    // If we cannot put the permission as it was, we have to write.
8802                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8803                                            changedRuntimePermissionUserIds, userId);
8804                                }
8805                                // If the app supports runtime permissions no need for a review.
8806                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8807                                        && appSupportsRuntimePermissions
8808                                        && (flags & PackageManager
8809                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8810                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8811                                    // Since we changed the flags, we have to write.
8812                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8813                                            changedRuntimePermissionUserIds, userId);
8814                                }
8815                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8816                                    && !appSupportsRuntimePermissions) {
8817                                // For legacy apps that need a permission review, every new
8818                                // runtime permission is granted but it is pending a review.
8819                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8820                                    permissionsState.grantRuntimePermission(bp, userId);
8821                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8822                                    // We changed the permission and flags, hence have to write.
8823                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8824                                            changedRuntimePermissionUserIds, userId);
8825                                }
8826                            }
8827                            // Propagate the permission flags.
8828                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8829                        }
8830                    } break;
8831
8832                    case GRANT_UPGRADE: {
8833                        // Grant runtime permissions for a previously held install permission.
8834                        PermissionState permissionState = origPermissions
8835                                .getInstallPermissionState(bp.name);
8836                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8837
8838                        if (origPermissions.revokeInstallPermission(bp)
8839                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8840                            // We will be transferring the permission flags, so clear them.
8841                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8842                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8843                            changedInstallPermission = true;
8844                        }
8845
8846                        // If the permission is not to be promoted to runtime we ignore it and
8847                        // also its other flags as they are not applicable to install permissions.
8848                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8849                            for (int userId : currentUserIds) {
8850                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8851                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8852                                    // Transfer the permission flags.
8853                                    permissionsState.updatePermissionFlags(bp, userId,
8854                                            flags, flags);
8855                                    // If we granted the permission, we have to write.
8856                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8857                                            changedRuntimePermissionUserIds, userId);
8858                                }
8859                            }
8860                        }
8861                    } break;
8862
8863                    default: {
8864                        if (packageOfInterest == null
8865                                || packageOfInterest.equals(pkg.packageName)) {
8866                            Slog.w(TAG, "Not granting permission " + perm
8867                                    + " to package " + pkg.packageName
8868                                    + " because it was previously installed without");
8869                        }
8870                    } break;
8871                }
8872            } else {
8873                if (permissionsState.revokeInstallPermission(bp) !=
8874                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8875                    // Also drop the permission flags.
8876                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8877                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8878                    changedInstallPermission = true;
8879                    Slog.i(TAG, "Un-granting permission " + perm
8880                            + " from package " + pkg.packageName
8881                            + " (protectionLevel=" + bp.protectionLevel
8882                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8883                            + ")");
8884                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8885                    // Don't print warning for app op permissions, since it is fine for them
8886                    // not to be granted, there is a UI for the user to decide.
8887                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8888                        Slog.w(TAG, "Not granting permission " + perm
8889                                + " to package " + pkg.packageName
8890                                + " (protectionLevel=" + bp.protectionLevel
8891                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8892                                + ")");
8893                    }
8894                }
8895            }
8896        }
8897
8898        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8899                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8900            // This is the first that we have heard about this package, so the
8901            // permissions we have now selected are fixed until explicitly
8902            // changed.
8903            ps.installPermissionsFixed = true;
8904        }
8905
8906        // Persist the runtime permissions state for users with changes. If permissions
8907        // were revoked because no app in the shared user declares them we have to
8908        // write synchronously to avoid losing runtime permissions state.
8909        for (int userId : changedRuntimePermissionUserIds) {
8910            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8911        }
8912
8913        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8914    }
8915
8916    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8917        boolean allowed = false;
8918        final int NP = PackageParser.NEW_PERMISSIONS.length;
8919        for (int ip=0; ip<NP; ip++) {
8920            final PackageParser.NewPermissionInfo npi
8921                    = PackageParser.NEW_PERMISSIONS[ip];
8922            if (npi.name.equals(perm)
8923                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8924                allowed = true;
8925                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8926                        + pkg.packageName);
8927                break;
8928            }
8929        }
8930        return allowed;
8931    }
8932
8933    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8934            BasePermission bp, PermissionsState origPermissions) {
8935        boolean allowed;
8936        allowed = (compareSignatures(
8937                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8938                        == PackageManager.SIGNATURE_MATCH)
8939                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8940                        == PackageManager.SIGNATURE_MATCH);
8941        if (!allowed && (bp.protectionLevel
8942                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8943            if (isSystemApp(pkg)) {
8944                // For updated system applications, a system permission
8945                // is granted only if it had been defined by the original application.
8946                if (pkg.isUpdatedSystemApp()) {
8947                    final PackageSetting sysPs = mSettings
8948                            .getDisabledSystemPkgLPr(pkg.packageName);
8949                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8950                        // If the original was granted this permission, we take
8951                        // that grant decision as read and propagate it to the
8952                        // update.
8953                        if (sysPs.isPrivileged()) {
8954                            allowed = true;
8955                        }
8956                    } else {
8957                        // The system apk may have been updated with an older
8958                        // version of the one on the data partition, but which
8959                        // granted a new system permission that it didn't have
8960                        // before.  In this case we do want to allow the app to
8961                        // now get the new permission if the ancestral apk is
8962                        // privileged to get it.
8963                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8964                            for (int j=0;
8965                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8966                                if (perm.equals(
8967                                        sysPs.pkg.requestedPermissions.get(j))) {
8968                                    allowed = true;
8969                                    break;
8970                                }
8971                            }
8972                        }
8973                    }
8974                } else {
8975                    allowed = isPrivilegedApp(pkg);
8976                }
8977            }
8978        }
8979        if (!allowed) {
8980            if (!allowed && (bp.protectionLevel
8981                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8982                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8983                // If this was a previously normal/dangerous permission that got moved
8984                // to a system permission as part of the runtime permission redesign, then
8985                // we still want to blindly grant it to old apps.
8986                allowed = true;
8987            }
8988            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8989                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8990                // If this permission is to be granted to the system installer and
8991                // this app is an installer, then it gets the permission.
8992                allowed = true;
8993            }
8994            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8995                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8996                // If this permission is to be granted to the system verifier and
8997                // this app is a verifier, then it gets the permission.
8998                allowed = true;
8999            }
9000            if (!allowed && (bp.protectionLevel
9001                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9002                    && isSystemApp(pkg)) {
9003                // Any pre-installed system app is allowed to get this permission.
9004                allowed = true;
9005            }
9006            if (!allowed && (bp.protectionLevel
9007                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9008                // For development permissions, a development permission
9009                // is granted only if it was already granted.
9010                allowed = origPermissions.hasInstallPermission(perm);
9011            }
9012        }
9013        return allowed;
9014    }
9015
9016    final class ActivityIntentResolver
9017            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9018        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9019                boolean defaultOnly, int userId) {
9020            if (!sUserManager.exists(userId)) return null;
9021            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9022            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9023        }
9024
9025        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9026                int userId) {
9027            if (!sUserManager.exists(userId)) return null;
9028            mFlags = flags;
9029            return super.queryIntent(intent, resolvedType,
9030                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9031        }
9032
9033        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9034                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9035            if (!sUserManager.exists(userId)) return null;
9036            if (packageActivities == null) {
9037                return null;
9038            }
9039            mFlags = flags;
9040            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9041            final int N = packageActivities.size();
9042            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9043                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9044
9045            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9046            for (int i = 0; i < N; ++i) {
9047                intentFilters = packageActivities.get(i).intents;
9048                if (intentFilters != null && intentFilters.size() > 0) {
9049                    PackageParser.ActivityIntentInfo[] array =
9050                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9051                    intentFilters.toArray(array);
9052                    listCut.add(array);
9053                }
9054            }
9055            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9056        }
9057
9058        public final void addActivity(PackageParser.Activity a, String type) {
9059            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9060            mActivities.put(a.getComponentName(), a);
9061            if (DEBUG_SHOW_INFO)
9062                Log.v(
9063                TAG, "  " + type + " " +
9064                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9065            if (DEBUG_SHOW_INFO)
9066                Log.v(TAG, "    Class=" + a.info.name);
9067            final int NI = a.intents.size();
9068            for (int j=0; j<NI; j++) {
9069                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9070                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9071                    intent.setPriority(0);
9072                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9073                            + a.className + " with priority > 0, forcing to 0");
9074                }
9075                if (DEBUG_SHOW_INFO) {
9076                    Log.v(TAG, "    IntentFilter:");
9077                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9078                }
9079                if (!intent.debugCheck()) {
9080                    Log.w(TAG, "==> For Activity " + a.info.name);
9081                }
9082                addFilter(intent);
9083            }
9084        }
9085
9086        public final void removeActivity(PackageParser.Activity a, String type) {
9087            mActivities.remove(a.getComponentName());
9088            if (DEBUG_SHOW_INFO) {
9089                Log.v(TAG, "  " + type + " "
9090                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9091                                : a.info.name) + ":");
9092                Log.v(TAG, "    Class=" + a.info.name);
9093            }
9094            final int NI = a.intents.size();
9095            for (int j=0; j<NI; j++) {
9096                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9097                if (DEBUG_SHOW_INFO) {
9098                    Log.v(TAG, "    IntentFilter:");
9099                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9100                }
9101                removeFilter(intent);
9102            }
9103        }
9104
9105        @Override
9106        protected boolean allowFilterResult(
9107                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9108            ActivityInfo filterAi = filter.activity.info;
9109            for (int i=dest.size()-1; i>=0; i--) {
9110                ActivityInfo destAi = dest.get(i).activityInfo;
9111                if (destAi.name == filterAi.name
9112                        && destAi.packageName == filterAi.packageName) {
9113                    return false;
9114                }
9115            }
9116            return true;
9117        }
9118
9119        @Override
9120        protected ActivityIntentInfo[] newArray(int size) {
9121            return new ActivityIntentInfo[size];
9122        }
9123
9124        @Override
9125        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9126            if (!sUserManager.exists(userId)) return true;
9127            PackageParser.Package p = filter.activity.owner;
9128            if (p != null) {
9129                PackageSetting ps = (PackageSetting)p.mExtras;
9130                if (ps != null) {
9131                    // System apps are never considered stopped for purposes of
9132                    // filtering, because there may be no way for the user to
9133                    // actually re-launch them.
9134                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9135                            && ps.getStopped(userId);
9136                }
9137            }
9138            return false;
9139        }
9140
9141        @Override
9142        protected boolean isPackageForFilter(String packageName,
9143                PackageParser.ActivityIntentInfo info) {
9144            return packageName.equals(info.activity.owner.packageName);
9145        }
9146
9147        @Override
9148        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9149                int match, int userId) {
9150            if (!sUserManager.exists(userId)) return null;
9151            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9152                return null;
9153            }
9154            final PackageParser.Activity activity = info.activity;
9155            if (mSafeMode && (activity.info.applicationInfo.flags
9156                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9157                return null;
9158            }
9159            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9160            if (ps == null) {
9161                return null;
9162            }
9163            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9164                    ps.readUserState(userId), userId);
9165            if (ai == null) {
9166                return null;
9167            }
9168            final ResolveInfo res = new ResolveInfo();
9169            res.activityInfo = ai;
9170            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9171                res.filter = info;
9172            }
9173            if (info != null) {
9174                res.handleAllWebDataURI = info.handleAllWebDataURI();
9175            }
9176            res.priority = info.getPriority();
9177            res.preferredOrder = activity.owner.mPreferredOrder;
9178            //System.out.println("Result: " + res.activityInfo.className +
9179            //                   " = " + res.priority);
9180            res.match = match;
9181            res.isDefault = info.hasDefault;
9182            res.labelRes = info.labelRes;
9183            res.nonLocalizedLabel = info.nonLocalizedLabel;
9184            if (userNeedsBadging(userId)) {
9185                res.noResourceId = true;
9186            } else {
9187                res.icon = info.icon;
9188            }
9189            res.iconResourceId = info.icon;
9190            res.system = res.activityInfo.applicationInfo.isSystemApp();
9191            return res;
9192        }
9193
9194        @Override
9195        protected void sortResults(List<ResolveInfo> results) {
9196            Collections.sort(results, mResolvePrioritySorter);
9197        }
9198
9199        @Override
9200        protected void dumpFilter(PrintWriter out, String prefix,
9201                PackageParser.ActivityIntentInfo filter) {
9202            out.print(prefix); out.print(
9203                    Integer.toHexString(System.identityHashCode(filter.activity)));
9204                    out.print(' ');
9205                    filter.activity.printComponentShortName(out);
9206                    out.print(" filter ");
9207                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9208        }
9209
9210        @Override
9211        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9212            return filter.activity;
9213        }
9214
9215        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9216            PackageParser.Activity activity = (PackageParser.Activity)label;
9217            out.print(prefix); out.print(
9218                    Integer.toHexString(System.identityHashCode(activity)));
9219                    out.print(' ');
9220                    activity.printComponentShortName(out);
9221            if (count > 1) {
9222                out.print(" ("); out.print(count); out.print(" filters)");
9223            }
9224            out.println();
9225        }
9226
9227//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9228//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9229//            final List<ResolveInfo> retList = Lists.newArrayList();
9230//            while (i.hasNext()) {
9231//                final ResolveInfo resolveInfo = i.next();
9232//                if (isEnabledLP(resolveInfo.activityInfo)) {
9233//                    retList.add(resolveInfo);
9234//                }
9235//            }
9236//            return retList;
9237//        }
9238
9239        // Keys are String (activity class name), values are Activity.
9240        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9241                = new ArrayMap<ComponentName, PackageParser.Activity>();
9242        private int mFlags;
9243    }
9244
9245    private final class ServiceIntentResolver
9246            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9247        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9248                boolean defaultOnly, int userId) {
9249            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9250            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9251        }
9252
9253        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9254                int userId) {
9255            if (!sUserManager.exists(userId)) return null;
9256            mFlags = flags;
9257            return super.queryIntent(intent, resolvedType,
9258                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9259        }
9260
9261        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9262                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9263            if (!sUserManager.exists(userId)) return null;
9264            if (packageServices == null) {
9265                return null;
9266            }
9267            mFlags = flags;
9268            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9269            final int N = packageServices.size();
9270            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9271                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9272
9273            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9274            for (int i = 0; i < N; ++i) {
9275                intentFilters = packageServices.get(i).intents;
9276                if (intentFilters != null && intentFilters.size() > 0) {
9277                    PackageParser.ServiceIntentInfo[] array =
9278                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9279                    intentFilters.toArray(array);
9280                    listCut.add(array);
9281                }
9282            }
9283            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9284        }
9285
9286        public final void addService(PackageParser.Service s) {
9287            mServices.put(s.getComponentName(), s);
9288            if (DEBUG_SHOW_INFO) {
9289                Log.v(TAG, "  "
9290                        + (s.info.nonLocalizedLabel != null
9291                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9292                Log.v(TAG, "    Class=" + s.info.name);
9293            }
9294            final int NI = s.intents.size();
9295            int j;
9296            for (j=0; j<NI; j++) {
9297                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9298                if (DEBUG_SHOW_INFO) {
9299                    Log.v(TAG, "    IntentFilter:");
9300                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9301                }
9302                if (!intent.debugCheck()) {
9303                    Log.w(TAG, "==> For Service " + s.info.name);
9304                }
9305                addFilter(intent);
9306            }
9307        }
9308
9309        public final void removeService(PackageParser.Service s) {
9310            mServices.remove(s.getComponentName());
9311            if (DEBUG_SHOW_INFO) {
9312                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9313                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9314                Log.v(TAG, "    Class=" + s.info.name);
9315            }
9316            final int NI = s.intents.size();
9317            int j;
9318            for (j=0; j<NI; j++) {
9319                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9320                if (DEBUG_SHOW_INFO) {
9321                    Log.v(TAG, "    IntentFilter:");
9322                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9323                }
9324                removeFilter(intent);
9325            }
9326        }
9327
9328        @Override
9329        protected boolean allowFilterResult(
9330                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9331            ServiceInfo filterSi = filter.service.info;
9332            for (int i=dest.size()-1; i>=0; i--) {
9333                ServiceInfo destAi = dest.get(i).serviceInfo;
9334                if (destAi.name == filterSi.name
9335                        && destAi.packageName == filterSi.packageName) {
9336                    return false;
9337                }
9338            }
9339            return true;
9340        }
9341
9342        @Override
9343        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9344            return new PackageParser.ServiceIntentInfo[size];
9345        }
9346
9347        @Override
9348        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9349            if (!sUserManager.exists(userId)) return true;
9350            PackageParser.Package p = filter.service.owner;
9351            if (p != null) {
9352                PackageSetting ps = (PackageSetting)p.mExtras;
9353                if (ps != null) {
9354                    // System apps are never considered stopped for purposes of
9355                    // filtering, because there may be no way for the user to
9356                    // actually re-launch them.
9357                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9358                            && ps.getStopped(userId);
9359                }
9360            }
9361            return false;
9362        }
9363
9364        @Override
9365        protected boolean isPackageForFilter(String packageName,
9366                PackageParser.ServiceIntentInfo info) {
9367            return packageName.equals(info.service.owner.packageName);
9368        }
9369
9370        @Override
9371        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9372                int match, int userId) {
9373            if (!sUserManager.exists(userId)) return null;
9374            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9375            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9376                return null;
9377            }
9378            final PackageParser.Service service = info.service;
9379            if (mSafeMode && (service.info.applicationInfo.flags
9380                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9381                return null;
9382            }
9383            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9384            if (ps == null) {
9385                return null;
9386            }
9387            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9388                    ps.readUserState(userId), userId);
9389            if (si == null) {
9390                return null;
9391            }
9392            final ResolveInfo res = new ResolveInfo();
9393            res.serviceInfo = si;
9394            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9395                res.filter = filter;
9396            }
9397            res.priority = info.getPriority();
9398            res.preferredOrder = service.owner.mPreferredOrder;
9399            res.match = match;
9400            res.isDefault = info.hasDefault;
9401            res.labelRes = info.labelRes;
9402            res.nonLocalizedLabel = info.nonLocalizedLabel;
9403            res.icon = info.icon;
9404            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9405            return res;
9406        }
9407
9408        @Override
9409        protected void sortResults(List<ResolveInfo> results) {
9410            Collections.sort(results, mResolvePrioritySorter);
9411        }
9412
9413        @Override
9414        protected void dumpFilter(PrintWriter out, String prefix,
9415                PackageParser.ServiceIntentInfo filter) {
9416            out.print(prefix); out.print(
9417                    Integer.toHexString(System.identityHashCode(filter.service)));
9418                    out.print(' ');
9419                    filter.service.printComponentShortName(out);
9420                    out.print(" filter ");
9421                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9422        }
9423
9424        @Override
9425        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9426            return filter.service;
9427        }
9428
9429        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9430            PackageParser.Service service = (PackageParser.Service)label;
9431            out.print(prefix); out.print(
9432                    Integer.toHexString(System.identityHashCode(service)));
9433                    out.print(' ');
9434                    service.printComponentShortName(out);
9435            if (count > 1) {
9436                out.print(" ("); out.print(count); out.print(" filters)");
9437            }
9438            out.println();
9439        }
9440
9441//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9442//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9443//            final List<ResolveInfo> retList = Lists.newArrayList();
9444//            while (i.hasNext()) {
9445//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9446//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9447//                    retList.add(resolveInfo);
9448//                }
9449//            }
9450//            return retList;
9451//        }
9452
9453        // Keys are String (activity class name), values are Activity.
9454        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9455                = new ArrayMap<ComponentName, PackageParser.Service>();
9456        private int mFlags;
9457    };
9458
9459    private final class ProviderIntentResolver
9460            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9461        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9462                boolean defaultOnly, int userId) {
9463            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9464            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9465        }
9466
9467        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9468                int userId) {
9469            if (!sUserManager.exists(userId))
9470                return null;
9471            mFlags = flags;
9472            return super.queryIntent(intent, resolvedType,
9473                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9474        }
9475
9476        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9477                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9478            if (!sUserManager.exists(userId))
9479                return null;
9480            if (packageProviders == null) {
9481                return null;
9482            }
9483            mFlags = flags;
9484            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9485            final int N = packageProviders.size();
9486            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9487                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9488
9489            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9490            for (int i = 0; i < N; ++i) {
9491                intentFilters = packageProviders.get(i).intents;
9492                if (intentFilters != null && intentFilters.size() > 0) {
9493                    PackageParser.ProviderIntentInfo[] array =
9494                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9495                    intentFilters.toArray(array);
9496                    listCut.add(array);
9497                }
9498            }
9499            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9500        }
9501
9502        public final void addProvider(PackageParser.Provider p) {
9503            if (mProviders.containsKey(p.getComponentName())) {
9504                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9505                return;
9506            }
9507
9508            mProviders.put(p.getComponentName(), p);
9509            if (DEBUG_SHOW_INFO) {
9510                Log.v(TAG, "  "
9511                        + (p.info.nonLocalizedLabel != null
9512                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9513                Log.v(TAG, "    Class=" + p.info.name);
9514            }
9515            final int NI = p.intents.size();
9516            int j;
9517            for (j = 0; j < NI; j++) {
9518                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9519                if (DEBUG_SHOW_INFO) {
9520                    Log.v(TAG, "    IntentFilter:");
9521                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9522                }
9523                if (!intent.debugCheck()) {
9524                    Log.w(TAG, "==> For Provider " + p.info.name);
9525                }
9526                addFilter(intent);
9527            }
9528        }
9529
9530        public final void removeProvider(PackageParser.Provider p) {
9531            mProviders.remove(p.getComponentName());
9532            if (DEBUG_SHOW_INFO) {
9533                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9534                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9535                Log.v(TAG, "    Class=" + p.info.name);
9536            }
9537            final int NI = p.intents.size();
9538            int j;
9539            for (j = 0; j < NI; j++) {
9540                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9541                if (DEBUG_SHOW_INFO) {
9542                    Log.v(TAG, "    IntentFilter:");
9543                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9544                }
9545                removeFilter(intent);
9546            }
9547        }
9548
9549        @Override
9550        protected boolean allowFilterResult(
9551                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9552            ProviderInfo filterPi = filter.provider.info;
9553            for (int i = dest.size() - 1; i >= 0; i--) {
9554                ProviderInfo destPi = dest.get(i).providerInfo;
9555                if (destPi.name == filterPi.name
9556                        && destPi.packageName == filterPi.packageName) {
9557                    return false;
9558                }
9559            }
9560            return true;
9561        }
9562
9563        @Override
9564        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9565            return new PackageParser.ProviderIntentInfo[size];
9566        }
9567
9568        @Override
9569        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9570            if (!sUserManager.exists(userId))
9571                return true;
9572            PackageParser.Package p = filter.provider.owner;
9573            if (p != null) {
9574                PackageSetting ps = (PackageSetting) p.mExtras;
9575                if (ps != null) {
9576                    // System apps are never considered stopped for purposes of
9577                    // filtering, because there may be no way for the user to
9578                    // actually re-launch them.
9579                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9580                            && ps.getStopped(userId);
9581                }
9582            }
9583            return false;
9584        }
9585
9586        @Override
9587        protected boolean isPackageForFilter(String packageName,
9588                PackageParser.ProviderIntentInfo info) {
9589            return packageName.equals(info.provider.owner.packageName);
9590        }
9591
9592        @Override
9593        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9594                int match, int userId) {
9595            if (!sUserManager.exists(userId))
9596                return null;
9597            final PackageParser.ProviderIntentInfo info = filter;
9598            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9599                return null;
9600            }
9601            final PackageParser.Provider provider = info.provider;
9602            if (mSafeMode && (provider.info.applicationInfo.flags
9603                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9604                return null;
9605            }
9606            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9607            if (ps == null) {
9608                return null;
9609            }
9610            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9611                    ps.readUserState(userId), userId);
9612            if (pi == null) {
9613                return null;
9614            }
9615            final ResolveInfo res = new ResolveInfo();
9616            res.providerInfo = pi;
9617            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9618                res.filter = filter;
9619            }
9620            res.priority = info.getPriority();
9621            res.preferredOrder = provider.owner.mPreferredOrder;
9622            res.match = match;
9623            res.isDefault = info.hasDefault;
9624            res.labelRes = info.labelRes;
9625            res.nonLocalizedLabel = info.nonLocalizedLabel;
9626            res.icon = info.icon;
9627            res.system = res.providerInfo.applicationInfo.isSystemApp();
9628            return res;
9629        }
9630
9631        @Override
9632        protected void sortResults(List<ResolveInfo> results) {
9633            Collections.sort(results, mResolvePrioritySorter);
9634        }
9635
9636        @Override
9637        protected void dumpFilter(PrintWriter out, String prefix,
9638                PackageParser.ProviderIntentInfo filter) {
9639            out.print(prefix);
9640            out.print(
9641                    Integer.toHexString(System.identityHashCode(filter.provider)));
9642            out.print(' ');
9643            filter.provider.printComponentShortName(out);
9644            out.print(" filter ");
9645            out.println(Integer.toHexString(System.identityHashCode(filter)));
9646        }
9647
9648        @Override
9649        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9650            return filter.provider;
9651        }
9652
9653        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9654            PackageParser.Provider provider = (PackageParser.Provider)label;
9655            out.print(prefix); out.print(
9656                    Integer.toHexString(System.identityHashCode(provider)));
9657                    out.print(' ');
9658                    provider.printComponentShortName(out);
9659            if (count > 1) {
9660                out.print(" ("); out.print(count); out.print(" filters)");
9661            }
9662            out.println();
9663        }
9664
9665        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9666                = new ArrayMap<ComponentName, PackageParser.Provider>();
9667        private int mFlags;
9668    }
9669
9670    private static final class EphemeralIntentResolver
9671            extends IntentResolver<IntentFilter, ResolveInfo> {
9672        @Override
9673        protected IntentFilter[] newArray(int size) {
9674            return new IntentFilter[size];
9675        }
9676
9677        @Override
9678        protected boolean isPackageForFilter(String packageName, IntentFilter info) {
9679            return true;
9680        }
9681
9682        @Override
9683        protected ResolveInfo newResult(IntentFilter info, int match, int userId) {
9684            if (!sUserManager.exists(userId)) return null;
9685            final ResolveInfo res = new ResolveInfo();
9686            res.filter = info;
9687            return res;
9688        }
9689    }
9690
9691    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9692            new Comparator<ResolveInfo>() {
9693        public int compare(ResolveInfo r1, ResolveInfo r2) {
9694            int v1 = r1.priority;
9695            int v2 = r2.priority;
9696            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9697            if (v1 != v2) {
9698                return (v1 > v2) ? -1 : 1;
9699            }
9700            v1 = r1.preferredOrder;
9701            v2 = r2.preferredOrder;
9702            if (v1 != v2) {
9703                return (v1 > v2) ? -1 : 1;
9704            }
9705            if (r1.isDefault != r2.isDefault) {
9706                return r1.isDefault ? -1 : 1;
9707            }
9708            v1 = r1.match;
9709            v2 = r2.match;
9710            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9711            if (v1 != v2) {
9712                return (v1 > v2) ? -1 : 1;
9713            }
9714            if (r1.system != r2.system) {
9715                return r1.system ? -1 : 1;
9716            }
9717            return 0;
9718        }
9719    };
9720
9721    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9722            new Comparator<ProviderInfo>() {
9723        public int compare(ProviderInfo p1, ProviderInfo p2) {
9724            final int v1 = p1.initOrder;
9725            final int v2 = p2.initOrder;
9726            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9727        }
9728    };
9729
9730    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9731            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9732            final int[] userIds) {
9733        mHandler.post(new Runnable() {
9734            @Override
9735            public void run() {
9736                try {
9737                    final IActivityManager am = ActivityManagerNative.getDefault();
9738                    if (am == null) return;
9739                    final int[] resolvedUserIds;
9740                    if (userIds == null) {
9741                        resolvedUserIds = am.getRunningUserIds();
9742                    } else {
9743                        resolvedUserIds = userIds;
9744                    }
9745                    for (int id : resolvedUserIds) {
9746                        final Intent intent = new Intent(action,
9747                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9748                        if (extras != null) {
9749                            intent.putExtras(extras);
9750                        }
9751                        if (targetPkg != null) {
9752                            intent.setPackage(targetPkg);
9753                        }
9754                        // Modify the UID when posting to other users
9755                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9756                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9757                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9758                            intent.putExtra(Intent.EXTRA_UID, uid);
9759                        }
9760                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9761                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9762                        if (DEBUG_BROADCASTS) {
9763                            RuntimeException here = new RuntimeException("here");
9764                            here.fillInStackTrace();
9765                            Slog.d(TAG, "Sending to user " + id + ": "
9766                                    + intent.toShortString(false, true, false, false)
9767                                    + " " + intent.getExtras(), here);
9768                        }
9769                        am.broadcastIntent(null, intent, null, finishedReceiver,
9770                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9771                                null, finishedReceiver != null, false, id);
9772                    }
9773                } catch (RemoteException ex) {
9774                }
9775            }
9776        });
9777    }
9778
9779    /**
9780     * Check if the external storage media is available. This is true if there
9781     * is a mounted external storage medium or if the external storage is
9782     * emulated.
9783     */
9784    private boolean isExternalMediaAvailable() {
9785        return mMediaMounted || Environment.isExternalStorageEmulated();
9786    }
9787
9788    @Override
9789    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9790        // writer
9791        synchronized (mPackages) {
9792            if (!isExternalMediaAvailable()) {
9793                // If the external storage is no longer mounted at this point,
9794                // the caller may not have been able to delete all of this
9795                // packages files and can not delete any more.  Bail.
9796                return null;
9797            }
9798            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9799            if (lastPackage != null) {
9800                pkgs.remove(lastPackage);
9801            }
9802            if (pkgs.size() > 0) {
9803                return pkgs.get(0);
9804            }
9805        }
9806        return null;
9807    }
9808
9809    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9810        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9811                userId, andCode ? 1 : 0, packageName);
9812        if (mSystemReady) {
9813            msg.sendToTarget();
9814        } else {
9815            if (mPostSystemReadyMessages == null) {
9816                mPostSystemReadyMessages = new ArrayList<>();
9817            }
9818            mPostSystemReadyMessages.add(msg);
9819        }
9820    }
9821
9822    void startCleaningPackages() {
9823        // reader
9824        synchronized (mPackages) {
9825            if (!isExternalMediaAvailable()) {
9826                return;
9827            }
9828            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9829                return;
9830            }
9831        }
9832        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9833        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9834        IActivityManager am = ActivityManagerNative.getDefault();
9835        if (am != null) {
9836            try {
9837                am.startService(null, intent, null, mContext.getOpPackageName(),
9838                        UserHandle.USER_SYSTEM);
9839            } catch (RemoteException e) {
9840            }
9841        }
9842    }
9843
9844    @Override
9845    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9846            int installFlags, String installerPackageName, VerificationParams verificationParams,
9847            String packageAbiOverride) {
9848        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9849                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9850    }
9851
9852    @Override
9853    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9854            int installFlags, String installerPackageName, VerificationParams verificationParams,
9855            String packageAbiOverride, int userId) {
9856        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9857
9858        final int callingUid = Binder.getCallingUid();
9859        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9860
9861        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9862            try {
9863                if (observer != null) {
9864                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9865                }
9866            } catch (RemoteException re) {
9867            }
9868            return;
9869        }
9870
9871        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9872            installFlags |= PackageManager.INSTALL_FROM_ADB;
9873
9874        } else {
9875            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9876            // about installerPackageName.
9877
9878            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9879            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9880        }
9881
9882        UserHandle user;
9883        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9884            user = UserHandle.ALL;
9885        } else {
9886            user = new UserHandle(userId);
9887        }
9888
9889        // Only system components can circumvent runtime permissions when installing.
9890        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9891                && mContext.checkCallingOrSelfPermission(Manifest.permission
9892                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9893            throw new SecurityException("You need the "
9894                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9895                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9896        }
9897
9898        verificationParams.setInstallerUid(callingUid);
9899
9900        final File originFile = new File(originPath);
9901        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9902
9903        final Message msg = mHandler.obtainMessage(INIT_COPY);
9904        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9905                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9906        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9907        msg.obj = params;
9908
9909        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9910                System.identityHashCode(msg.obj));
9911        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9912                System.identityHashCode(msg.obj));
9913
9914        mHandler.sendMessage(msg);
9915    }
9916
9917    void installStage(String packageName, File stagedDir, String stagedCid,
9918            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9919            String installerPackageName, int installerUid, UserHandle user) {
9920        if (DEBUG_EPHEMERAL) {
9921            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
9922                Slog.d(TAG, "Ephemeral install of " + packageName);
9923            }
9924        }
9925        final VerificationParams verifParams = new VerificationParams(
9926                null, sessionParams.originatingUri, sessionParams.referrerUri,
9927                sessionParams.originatingUid, null);
9928        verifParams.setInstallerUid(installerUid);
9929
9930        final OriginInfo origin;
9931        if (stagedDir != null) {
9932            origin = OriginInfo.fromStagedFile(stagedDir);
9933        } else {
9934            origin = OriginInfo.fromStagedContainer(stagedCid);
9935        }
9936
9937        final Message msg = mHandler.obtainMessage(INIT_COPY);
9938        final InstallParams params = new InstallParams(origin, null, observer,
9939                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9940                verifParams, user, sessionParams.abiOverride,
9941                sessionParams.grantedRuntimePermissions);
9942        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9943        msg.obj = params;
9944
9945        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9946                System.identityHashCode(msg.obj));
9947        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9948                System.identityHashCode(msg.obj));
9949
9950        mHandler.sendMessage(msg);
9951    }
9952
9953    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9954        Bundle extras = new Bundle(1);
9955        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9956
9957        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9958                packageName, extras, 0, null, null, new int[] {userId});
9959        try {
9960            IActivityManager am = ActivityManagerNative.getDefault();
9961            final boolean isSystem =
9962                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9963            if (isSystem && am.isUserRunning(userId, 0)) {
9964                // The just-installed/enabled app is bundled on the system, so presumed
9965                // to be able to run automatically without needing an explicit launch.
9966                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9967                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9968                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9969                        .setPackage(packageName);
9970                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9971                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9972            }
9973        } catch (RemoteException e) {
9974            // shouldn't happen
9975            Slog.w(TAG, "Unable to bootstrap installed package", e);
9976        }
9977    }
9978
9979    @Override
9980    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9981            int userId) {
9982        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9983        PackageSetting pkgSetting;
9984        final int uid = Binder.getCallingUid();
9985        enforceCrossUserPermission(uid, userId, true, true,
9986                "setApplicationHiddenSetting for user " + userId);
9987
9988        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9989            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9990            return false;
9991        }
9992
9993        long callingId = Binder.clearCallingIdentity();
9994        try {
9995            boolean sendAdded = false;
9996            boolean sendRemoved = false;
9997            // writer
9998            synchronized (mPackages) {
9999                pkgSetting = mSettings.mPackages.get(packageName);
10000                if (pkgSetting == null) {
10001                    return false;
10002                }
10003                if (pkgSetting.getHidden(userId) != hidden) {
10004                    pkgSetting.setHidden(hidden, userId);
10005                    mSettings.writePackageRestrictionsLPr(userId);
10006                    if (hidden) {
10007                        sendRemoved = true;
10008                    } else {
10009                        sendAdded = true;
10010                    }
10011                }
10012            }
10013            if (sendAdded) {
10014                sendPackageAddedForUser(packageName, pkgSetting, userId);
10015                return true;
10016            }
10017            if (sendRemoved) {
10018                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10019                        "hiding pkg");
10020                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10021                return true;
10022            }
10023        } finally {
10024            Binder.restoreCallingIdentity(callingId);
10025        }
10026        return false;
10027    }
10028
10029    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10030            int userId) {
10031        final PackageRemovedInfo info = new PackageRemovedInfo();
10032        info.removedPackage = packageName;
10033        info.removedUsers = new int[] {userId};
10034        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10035        info.sendBroadcast(false, false, false);
10036    }
10037
10038    /**
10039     * Returns true if application is not found or there was an error. Otherwise it returns
10040     * the hidden state of the package for the given user.
10041     */
10042    @Override
10043    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10044        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10045        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10046                false, "getApplicationHidden for user " + userId);
10047        PackageSetting pkgSetting;
10048        long callingId = Binder.clearCallingIdentity();
10049        try {
10050            // writer
10051            synchronized (mPackages) {
10052                pkgSetting = mSettings.mPackages.get(packageName);
10053                if (pkgSetting == null) {
10054                    return true;
10055                }
10056                return pkgSetting.getHidden(userId);
10057            }
10058        } finally {
10059            Binder.restoreCallingIdentity(callingId);
10060        }
10061    }
10062
10063    /**
10064     * @hide
10065     */
10066    @Override
10067    public int installExistingPackageAsUser(String packageName, int userId) {
10068        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10069                null);
10070        PackageSetting pkgSetting;
10071        final int uid = Binder.getCallingUid();
10072        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10073                + userId);
10074        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10075            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10076        }
10077
10078        long callingId = Binder.clearCallingIdentity();
10079        try {
10080            boolean sendAdded = false;
10081
10082            // writer
10083            synchronized (mPackages) {
10084                pkgSetting = mSettings.mPackages.get(packageName);
10085                if (pkgSetting == null) {
10086                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10087                }
10088                if (!pkgSetting.getInstalled(userId)) {
10089                    pkgSetting.setInstalled(true, userId);
10090                    pkgSetting.setHidden(false, userId);
10091                    mSettings.writePackageRestrictionsLPr(userId);
10092                    sendAdded = true;
10093                }
10094            }
10095
10096            if (sendAdded) {
10097                sendPackageAddedForUser(packageName, pkgSetting, userId);
10098            }
10099        } finally {
10100            Binder.restoreCallingIdentity(callingId);
10101        }
10102
10103        return PackageManager.INSTALL_SUCCEEDED;
10104    }
10105
10106    boolean isUserRestricted(int userId, String restrictionKey) {
10107        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10108        if (restrictions.getBoolean(restrictionKey, false)) {
10109            Log.w(TAG, "User is restricted: " + restrictionKey);
10110            return true;
10111        }
10112        return false;
10113    }
10114
10115    @Override
10116    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10117        mContext.enforceCallingOrSelfPermission(
10118                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10119                "Only package verification agents can verify applications");
10120
10121        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10122        final PackageVerificationResponse response = new PackageVerificationResponse(
10123                verificationCode, Binder.getCallingUid());
10124        msg.arg1 = id;
10125        msg.obj = response;
10126        mHandler.sendMessage(msg);
10127    }
10128
10129    @Override
10130    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10131            long millisecondsToDelay) {
10132        mContext.enforceCallingOrSelfPermission(
10133                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10134                "Only package verification agents can extend verification timeouts");
10135
10136        final PackageVerificationState state = mPendingVerification.get(id);
10137        final PackageVerificationResponse response = new PackageVerificationResponse(
10138                verificationCodeAtTimeout, Binder.getCallingUid());
10139
10140        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10141            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10142        }
10143        if (millisecondsToDelay < 0) {
10144            millisecondsToDelay = 0;
10145        }
10146        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10147                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10148            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10149        }
10150
10151        if ((state != null) && !state.timeoutExtended()) {
10152            state.extendTimeout();
10153
10154            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10155            msg.arg1 = id;
10156            msg.obj = response;
10157            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10158        }
10159    }
10160
10161    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10162            int verificationCode, UserHandle user) {
10163        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10164        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10165        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10166        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10167        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10168
10169        mContext.sendBroadcastAsUser(intent, user,
10170                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10171    }
10172
10173    private ComponentName matchComponentForVerifier(String packageName,
10174            List<ResolveInfo> receivers) {
10175        ActivityInfo targetReceiver = null;
10176
10177        final int NR = receivers.size();
10178        for (int i = 0; i < NR; i++) {
10179            final ResolveInfo info = receivers.get(i);
10180            if (info.activityInfo == null) {
10181                continue;
10182            }
10183
10184            if (packageName.equals(info.activityInfo.packageName)) {
10185                targetReceiver = info.activityInfo;
10186                break;
10187            }
10188        }
10189
10190        if (targetReceiver == null) {
10191            return null;
10192        }
10193
10194        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10195    }
10196
10197    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10198            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10199        if (pkgInfo.verifiers.length == 0) {
10200            return null;
10201        }
10202
10203        final int N = pkgInfo.verifiers.length;
10204        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10205        for (int i = 0; i < N; i++) {
10206            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10207
10208            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10209                    receivers);
10210            if (comp == null) {
10211                continue;
10212            }
10213
10214            final int verifierUid = getUidForVerifier(verifierInfo);
10215            if (verifierUid == -1) {
10216                continue;
10217            }
10218
10219            if (DEBUG_VERIFY) {
10220                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10221                        + " with the correct signature");
10222            }
10223            sufficientVerifiers.add(comp);
10224            verificationState.addSufficientVerifier(verifierUid);
10225        }
10226
10227        return sufficientVerifiers;
10228    }
10229
10230    private int getUidForVerifier(VerifierInfo verifierInfo) {
10231        synchronized (mPackages) {
10232            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10233            if (pkg == null) {
10234                return -1;
10235            } else if (pkg.mSignatures.length != 1) {
10236                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10237                        + " has more than one signature; ignoring");
10238                return -1;
10239            }
10240
10241            /*
10242             * If the public key of the package's signature does not match
10243             * our expected public key, then this is a different package and
10244             * we should skip.
10245             */
10246
10247            final byte[] expectedPublicKey;
10248            try {
10249                final Signature verifierSig = pkg.mSignatures[0];
10250                final PublicKey publicKey = verifierSig.getPublicKey();
10251                expectedPublicKey = publicKey.getEncoded();
10252            } catch (CertificateException e) {
10253                return -1;
10254            }
10255
10256            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10257
10258            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10259                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10260                        + " does not have the expected public key; ignoring");
10261                return -1;
10262            }
10263
10264            return pkg.applicationInfo.uid;
10265        }
10266    }
10267
10268    @Override
10269    public void finishPackageInstall(int token) {
10270        enforceSystemOrRoot("Only the system is allowed to finish installs");
10271
10272        if (DEBUG_INSTALL) {
10273            Slog.v(TAG, "BM finishing package install for " + token);
10274        }
10275        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10276
10277        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10278        mHandler.sendMessage(msg);
10279    }
10280
10281    /**
10282     * Get the verification agent timeout.
10283     *
10284     * @return verification timeout in milliseconds
10285     */
10286    private long getVerificationTimeout() {
10287        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10288                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10289                DEFAULT_VERIFICATION_TIMEOUT);
10290    }
10291
10292    /**
10293     * Get the default verification agent response code.
10294     *
10295     * @return default verification response code
10296     */
10297    private int getDefaultVerificationResponse() {
10298        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10299                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10300                DEFAULT_VERIFICATION_RESPONSE);
10301    }
10302
10303    /**
10304     * Check whether or not package verification has been enabled.
10305     *
10306     * @return true if verification should be performed
10307     */
10308    private boolean isVerificationEnabled(int userId, int installFlags) {
10309        if (!DEFAULT_VERIFY_ENABLE) {
10310            return false;
10311        }
10312        // TODO: fix b/25118622; don't bypass verification
10313        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10314            return false;
10315        }
10316        // Ephemeral apps don't get the full verification treatment
10317        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10318            if (DEBUG_EPHEMERAL) {
10319                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10320            }
10321            return false;
10322        }
10323
10324        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10325
10326        // Check if installing from ADB
10327        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10328            // Do not run verification in a test harness environment
10329            if (ActivityManager.isRunningInTestHarness()) {
10330                return false;
10331            }
10332            if (ensureVerifyAppsEnabled) {
10333                return true;
10334            }
10335            // Check if the developer does not want package verification for ADB installs
10336            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10337                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10338                return false;
10339            }
10340        }
10341
10342        if (ensureVerifyAppsEnabled) {
10343            return true;
10344        }
10345
10346        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10347                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10348    }
10349
10350    @Override
10351    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10352            throws RemoteException {
10353        mContext.enforceCallingOrSelfPermission(
10354                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10355                "Only intentfilter verification agents can verify applications");
10356
10357        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10358        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10359                Binder.getCallingUid(), verificationCode, failedDomains);
10360        msg.arg1 = id;
10361        msg.obj = response;
10362        mHandler.sendMessage(msg);
10363    }
10364
10365    @Override
10366    public int getIntentVerificationStatus(String packageName, int userId) {
10367        synchronized (mPackages) {
10368            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10369        }
10370    }
10371
10372    @Override
10373    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10374        mContext.enforceCallingOrSelfPermission(
10375                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10376
10377        boolean result = false;
10378        synchronized (mPackages) {
10379            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10380        }
10381        if (result) {
10382            scheduleWritePackageRestrictionsLocked(userId);
10383        }
10384        return result;
10385    }
10386
10387    @Override
10388    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10389        synchronized (mPackages) {
10390            return mSettings.getIntentFilterVerificationsLPr(packageName);
10391        }
10392    }
10393
10394    @Override
10395    public List<IntentFilter> getAllIntentFilters(String packageName) {
10396        if (TextUtils.isEmpty(packageName)) {
10397            return Collections.<IntentFilter>emptyList();
10398        }
10399        synchronized (mPackages) {
10400            PackageParser.Package pkg = mPackages.get(packageName);
10401            if (pkg == null || pkg.activities == null) {
10402                return Collections.<IntentFilter>emptyList();
10403            }
10404            final int count = pkg.activities.size();
10405            ArrayList<IntentFilter> result = new ArrayList<>();
10406            for (int n=0; n<count; n++) {
10407                PackageParser.Activity activity = pkg.activities.get(n);
10408                if (activity.intents != null || activity.intents.size() > 0) {
10409                    result.addAll(activity.intents);
10410                }
10411            }
10412            return result;
10413        }
10414    }
10415
10416    @Override
10417    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10418        mContext.enforceCallingOrSelfPermission(
10419                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10420
10421        synchronized (mPackages) {
10422            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10423            if (packageName != null) {
10424                result |= updateIntentVerificationStatus(packageName,
10425                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10426                        userId);
10427                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10428                        packageName, userId);
10429            }
10430            return result;
10431        }
10432    }
10433
10434    @Override
10435    public String getDefaultBrowserPackageName(int userId) {
10436        synchronized (mPackages) {
10437            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10438        }
10439    }
10440
10441    /**
10442     * Get the "allow unknown sources" setting.
10443     *
10444     * @return the current "allow unknown sources" setting
10445     */
10446    private int getUnknownSourcesSettings() {
10447        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10448                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10449                -1);
10450    }
10451
10452    @Override
10453    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10454        final int uid = Binder.getCallingUid();
10455        // writer
10456        synchronized (mPackages) {
10457            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10458            if (targetPackageSetting == null) {
10459                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10460            }
10461
10462            PackageSetting installerPackageSetting;
10463            if (installerPackageName != null) {
10464                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10465                if (installerPackageSetting == null) {
10466                    throw new IllegalArgumentException("Unknown installer package: "
10467                            + installerPackageName);
10468                }
10469            } else {
10470                installerPackageSetting = null;
10471            }
10472
10473            Signature[] callerSignature;
10474            Object obj = mSettings.getUserIdLPr(uid);
10475            if (obj != null) {
10476                if (obj instanceof SharedUserSetting) {
10477                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10478                } else if (obj instanceof PackageSetting) {
10479                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10480                } else {
10481                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10482                }
10483            } else {
10484                throw new SecurityException("Unknown calling uid " + uid);
10485            }
10486
10487            // Verify: can't set installerPackageName to a package that is
10488            // not signed with the same cert as the caller.
10489            if (installerPackageSetting != null) {
10490                if (compareSignatures(callerSignature,
10491                        installerPackageSetting.signatures.mSignatures)
10492                        != PackageManager.SIGNATURE_MATCH) {
10493                    throw new SecurityException(
10494                            "Caller does not have same cert as new installer package "
10495                            + installerPackageName);
10496                }
10497            }
10498
10499            // Verify: if target already has an installer package, it must
10500            // be signed with the same cert as the caller.
10501            if (targetPackageSetting.installerPackageName != null) {
10502                PackageSetting setting = mSettings.mPackages.get(
10503                        targetPackageSetting.installerPackageName);
10504                // If the currently set package isn't valid, then it's always
10505                // okay to change it.
10506                if (setting != null) {
10507                    if (compareSignatures(callerSignature,
10508                            setting.signatures.mSignatures)
10509                            != PackageManager.SIGNATURE_MATCH) {
10510                        throw new SecurityException(
10511                                "Caller does not have same cert as old installer package "
10512                                + targetPackageSetting.installerPackageName);
10513                    }
10514                }
10515            }
10516
10517            // Okay!
10518            targetPackageSetting.installerPackageName = installerPackageName;
10519            scheduleWriteSettingsLocked();
10520        }
10521    }
10522
10523    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10524        // Queue up an async operation since the package installation may take a little while.
10525        mHandler.post(new Runnable() {
10526            public void run() {
10527                mHandler.removeCallbacks(this);
10528                 // Result object to be returned
10529                PackageInstalledInfo res = new PackageInstalledInfo();
10530                res.returnCode = currentStatus;
10531                res.uid = -1;
10532                res.pkg = null;
10533                res.removedInfo = new PackageRemovedInfo();
10534                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10535                    args.doPreInstall(res.returnCode);
10536                    synchronized (mInstallLock) {
10537                        installPackageTracedLI(args, res);
10538                    }
10539                    args.doPostInstall(res.returnCode, res.uid);
10540                }
10541
10542                // A restore should be performed at this point if (a) the install
10543                // succeeded, (b) the operation is not an update, and (c) the new
10544                // package has not opted out of backup participation.
10545                final boolean update = res.removedInfo.removedPackage != null;
10546                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10547                boolean doRestore = !update
10548                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10549
10550                // Set up the post-install work request bookkeeping.  This will be used
10551                // and cleaned up by the post-install event handling regardless of whether
10552                // there's a restore pass performed.  Token values are >= 1.
10553                int token;
10554                if (mNextInstallToken < 0) mNextInstallToken = 1;
10555                token = mNextInstallToken++;
10556
10557                PostInstallData data = new PostInstallData(args, res);
10558                mRunningInstalls.put(token, data);
10559                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10560
10561                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10562                    // Pass responsibility to the Backup Manager.  It will perform a
10563                    // restore if appropriate, then pass responsibility back to the
10564                    // Package Manager to run the post-install observer callbacks
10565                    // and broadcasts.
10566                    IBackupManager bm = IBackupManager.Stub.asInterface(
10567                            ServiceManager.getService(Context.BACKUP_SERVICE));
10568                    if (bm != null) {
10569                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10570                                + " to BM for possible restore");
10571                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10572                        try {
10573                            // TODO: http://b/22388012
10574                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10575                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10576                            } else {
10577                                doRestore = false;
10578                            }
10579                        } catch (RemoteException e) {
10580                            // can't happen; the backup manager is local
10581                        } catch (Exception e) {
10582                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10583                            doRestore = false;
10584                        }
10585                    } else {
10586                        Slog.e(TAG, "Backup Manager not found!");
10587                        doRestore = false;
10588                    }
10589                }
10590
10591                if (!doRestore) {
10592                    // No restore possible, or the Backup Manager was mysteriously not
10593                    // available -- just fire the post-install work request directly.
10594                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10595
10596                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10597
10598                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10599                    mHandler.sendMessage(msg);
10600                }
10601            }
10602        });
10603    }
10604
10605    private abstract class HandlerParams {
10606        private static final int MAX_RETRIES = 4;
10607
10608        /**
10609         * Number of times startCopy() has been attempted and had a non-fatal
10610         * error.
10611         */
10612        private int mRetries = 0;
10613
10614        /** User handle for the user requesting the information or installation. */
10615        private final UserHandle mUser;
10616        String traceMethod;
10617        int traceCookie;
10618
10619        HandlerParams(UserHandle user) {
10620            mUser = user;
10621        }
10622
10623        UserHandle getUser() {
10624            return mUser;
10625        }
10626
10627        HandlerParams setTraceMethod(String traceMethod) {
10628            this.traceMethod = traceMethod;
10629            return this;
10630        }
10631
10632        HandlerParams setTraceCookie(int traceCookie) {
10633            this.traceCookie = traceCookie;
10634            return this;
10635        }
10636
10637        final boolean startCopy() {
10638            boolean res;
10639            try {
10640                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10641
10642                if (++mRetries > MAX_RETRIES) {
10643                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10644                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10645                    handleServiceError();
10646                    return false;
10647                } else {
10648                    handleStartCopy();
10649                    res = true;
10650                }
10651            } catch (RemoteException e) {
10652                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10653                mHandler.sendEmptyMessage(MCS_RECONNECT);
10654                res = false;
10655            }
10656            handleReturnCode();
10657            return res;
10658        }
10659
10660        final void serviceError() {
10661            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10662            handleServiceError();
10663            handleReturnCode();
10664        }
10665
10666        abstract void handleStartCopy() throws RemoteException;
10667        abstract void handleServiceError();
10668        abstract void handleReturnCode();
10669    }
10670
10671    class MeasureParams extends HandlerParams {
10672        private final PackageStats mStats;
10673        private boolean mSuccess;
10674
10675        private final IPackageStatsObserver mObserver;
10676
10677        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10678            super(new UserHandle(stats.userHandle));
10679            mObserver = observer;
10680            mStats = stats;
10681        }
10682
10683        @Override
10684        public String toString() {
10685            return "MeasureParams{"
10686                + Integer.toHexString(System.identityHashCode(this))
10687                + " " + mStats.packageName + "}";
10688        }
10689
10690        @Override
10691        void handleStartCopy() throws RemoteException {
10692            synchronized (mInstallLock) {
10693                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10694            }
10695
10696            if (mSuccess) {
10697                final boolean mounted;
10698                if (Environment.isExternalStorageEmulated()) {
10699                    mounted = true;
10700                } else {
10701                    final String status = Environment.getExternalStorageState();
10702                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10703                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10704                }
10705
10706                if (mounted) {
10707                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10708
10709                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10710                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10711
10712                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10713                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10714
10715                    // Always subtract cache size, since it's a subdirectory
10716                    mStats.externalDataSize -= mStats.externalCacheSize;
10717
10718                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10719                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10720
10721                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10722                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10723                }
10724            }
10725        }
10726
10727        @Override
10728        void handleReturnCode() {
10729            if (mObserver != null) {
10730                try {
10731                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10732                } catch (RemoteException e) {
10733                    Slog.i(TAG, "Observer no longer exists.");
10734                }
10735            }
10736        }
10737
10738        @Override
10739        void handleServiceError() {
10740            Slog.e(TAG, "Could not measure application " + mStats.packageName
10741                            + " external storage");
10742        }
10743    }
10744
10745    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10746            throws RemoteException {
10747        long result = 0;
10748        for (File path : paths) {
10749            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10750        }
10751        return result;
10752    }
10753
10754    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10755        for (File path : paths) {
10756            try {
10757                mcs.clearDirectory(path.getAbsolutePath());
10758            } catch (RemoteException e) {
10759            }
10760        }
10761    }
10762
10763    static class OriginInfo {
10764        /**
10765         * Location where install is coming from, before it has been
10766         * copied/renamed into place. This could be a single monolithic APK
10767         * file, or a cluster directory. This location may be untrusted.
10768         */
10769        final File file;
10770        final String cid;
10771
10772        /**
10773         * Flag indicating that {@link #file} or {@link #cid} has already been
10774         * staged, meaning downstream users don't need to defensively copy the
10775         * contents.
10776         */
10777        final boolean staged;
10778
10779        /**
10780         * Flag indicating that {@link #file} or {@link #cid} is an already
10781         * installed app that is being moved.
10782         */
10783        final boolean existing;
10784
10785        final String resolvedPath;
10786        final File resolvedFile;
10787
10788        static OriginInfo fromNothing() {
10789            return new OriginInfo(null, null, false, false);
10790        }
10791
10792        static OriginInfo fromUntrustedFile(File file) {
10793            return new OriginInfo(file, null, false, false);
10794        }
10795
10796        static OriginInfo fromExistingFile(File file) {
10797            return new OriginInfo(file, null, false, true);
10798        }
10799
10800        static OriginInfo fromStagedFile(File file) {
10801            return new OriginInfo(file, null, true, false);
10802        }
10803
10804        static OriginInfo fromStagedContainer(String cid) {
10805            return new OriginInfo(null, cid, true, false);
10806        }
10807
10808        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10809            this.file = file;
10810            this.cid = cid;
10811            this.staged = staged;
10812            this.existing = existing;
10813
10814            if (cid != null) {
10815                resolvedPath = PackageHelper.getSdDir(cid);
10816                resolvedFile = new File(resolvedPath);
10817            } else if (file != null) {
10818                resolvedPath = file.getAbsolutePath();
10819                resolvedFile = file;
10820            } else {
10821                resolvedPath = null;
10822                resolvedFile = null;
10823            }
10824        }
10825    }
10826
10827    class MoveInfo {
10828        final int moveId;
10829        final String fromUuid;
10830        final String toUuid;
10831        final String packageName;
10832        final String dataAppName;
10833        final int appId;
10834        final String seinfo;
10835
10836        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10837                String dataAppName, int appId, String seinfo) {
10838            this.moveId = moveId;
10839            this.fromUuid = fromUuid;
10840            this.toUuid = toUuid;
10841            this.packageName = packageName;
10842            this.dataAppName = dataAppName;
10843            this.appId = appId;
10844            this.seinfo = seinfo;
10845        }
10846    }
10847
10848    class InstallParams extends HandlerParams {
10849        final OriginInfo origin;
10850        final MoveInfo move;
10851        final IPackageInstallObserver2 observer;
10852        int installFlags;
10853        final String installerPackageName;
10854        final String volumeUuid;
10855        final VerificationParams verificationParams;
10856        private InstallArgs mArgs;
10857        private int mRet;
10858        final String packageAbiOverride;
10859        final String[] grantedRuntimePermissions;
10860
10861        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10862                int installFlags, String installerPackageName, String volumeUuid,
10863                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10864                String[] grantedPermissions) {
10865            super(user);
10866            this.origin = origin;
10867            this.move = move;
10868            this.observer = observer;
10869            this.installFlags = installFlags;
10870            this.installerPackageName = installerPackageName;
10871            this.volumeUuid = volumeUuid;
10872            this.verificationParams = verificationParams;
10873            this.packageAbiOverride = packageAbiOverride;
10874            this.grantedRuntimePermissions = grantedPermissions;
10875        }
10876
10877        @Override
10878        public String toString() {
10879            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10880                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10881        }
10882
10883        public ManifestDigest getManifestDigest() {
10884            if (verificationParams == null) {
10885                return null;
10886            }
10887            return verificationParams.getManifestDigest();
10888        }
10889
10890        private int installLocationPolicy(PackageInfoLite pkgLite) {
10891            String packageName = pkgLite.packageName;
10892            int installLocation = pkgLite.installLocation;
10893            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10894            // reader
10895            synchronized (mPackages) {
10896                PackageParser.Package pkg = mPackages.get(packageName);
10897                if (pkg != null) {
10898                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10899                        // Check for downgrading.
10900                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10901                            try {
10902                                checkDowngrade(pkg, pkgLite);
10903                            } catch (PackageManagerException e) {
10904                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10905                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10906                            }
10907                        }
10908                        // Check for updated system application.
10909                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10910                            if (onSd) {
10911                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10912                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10913                            }
10914                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10915                        } else {
10916                            if (onSd) {
10917                                // Install flag overrides everything.
10918                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10919                            }
10920                            // If current upgrade specifies particular preference
10921                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10922                                // Application explicitly specified internal.
10923                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10924                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10925                                // App explictly prefers external. Let policy decide
10926                            } else {
10927                                // Prefer previous location
10928                                if (isExternal(pkg)) {
10929                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10930                                }
10931                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10932                            }
10933                        }
10934                    } else {
10935                        // Invalid install. Return error code
10936                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10937                    }
10938                }
10939            }
10940            // All the special cases have been taken care of.
10941            // Return result based on recommended install location.
10942            if (onSd) {
10943                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10944            }
10945            return pkgLite.recommendedInstallLocation;
10946        }
10947
10948        /*
10949         * Invoke remote method to get package information and install
10950         * location values. Override install location based on default
10951         * policy if needed and then create install arguments based
10952         * on the install location.
10953         */
10954        public void handleStartCopy() throws RemoteException {
10955            int ret = PackageManager.INSTALL_SUCCEEDED;
10956
10957            // If we're already staged, we've firmly committed to an install location
10958            if (origin.staged) {
10959                if (origin.file != null) {
10960                    installFlags |= PackageManager.INSTALL_INTERNAL;
10961                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10962                } else if (origin.cid != null) {
10963                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10964                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10965                } else {
10966                    throw new IllegalStateException("Invalid stage location");
10967                }
10968            }
10969
10970            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10971            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10972            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
10973            PackageInfoLite pkgLite = null;
10974
10975            if (onInt && onSd) {
10976                // Check if both bits are set.
10977                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10978                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10979            } else if (onSd && ephemeral) {
10980                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
10981                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10982            } else {
10983                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10984                        packageAbiOverride);
10985
10986                if (DEBUG_EPHEMERAL && ephemeral) {
10987                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
10988                }
10989
10990                /*
10991                 * If we have too little free space, try to free cache
10992                 * before giving up.
10993                 */
10994                if (!origin.staged && pkgLite.recommendedInstallLocation
10995                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10996                    // TODO: focus freeing disk space on the target device
10997                    final StorageManager storage = StorageManager.from(mContext);
10998                    final long lowThreshold = storage.getStorageLowBytes(
10999                            Environment.getDataDirectory());
11000
11001                    final long sizeBytes = mContainerService.calculateInstalledSize(
11002                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11003
11004                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11005                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11006                                installFlags, packageAbiOverride);
11007                    }
11008
11009                    /*
11010                     * The cache free must have deleted the file we
11011                     * downloaded to install.
11012                     *
11013                     * TODO: fix the "freeCache" call to not delete
11014                     *       the file we care about.
11015                     */
11016                    if (pkgLite.recommendedInstallLocation
11017                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11018                        pkgLite.recommendedInstallLocation
11019                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11020                    }
11021                }
11022            }
11023
11024            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11025                int loc = pkgLite.recommendedInstallLocation;
11026                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11027                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11028                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11029                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11030                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11031                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11032                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11033                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11034                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11035                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11036                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11037                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11038                } else {
11039                    // Override with defaults if needed.
11040                    loc = installLocationPolicy(pkgLite);
11041                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11042                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11043                    } else if (!onSd && !onInt) {
11044                        // Override install location with flags
11045                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11046                            // Set the flag to install on external media.
11047                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11048                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11049                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11050                            if (DEBUG_EPHEMERAL) {
11051                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11052                            }
11053                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11054                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11055                                    |PackageManager.INSTALL_INTERNAL);
11056                        } else {
11057                            // Make sure the flag for installing on external
11058                            // media is unset
11059                            installFlags |= PackageManager.INSTALL_INTERNAL;
11060                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11061                        }
11062                    }
11063                }
11064            }
11065
11066            final InstallArgs args = createInstallArgs(this);
11067            mArgs = args;
11068
11069            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11070                // TODO: http://b/22976637
11071                // Apps installed for "all" users use the device owner to verify the app
11072                UserHandle verifierUser = getUser();
11073                if (verifierUser == UserHandle.ALL) {
11074                    verifierUser = UserHandle.SYSTEM;
11075                }
11076
11077                /*
11078                 * Determine if we have any installed package verifiers. If we
11079                 * do, then we'll defer to them to verify the packages.
11080                 */
11081                final int requiredUid = mRequiredVerifierPackage == null ? -1
11082                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11083                if (!origin.existing && requiredUid != -1
11084                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11085                    final Intent verification = new Intent(
11086                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11087                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11088                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11089                            PACKAGE_MIME_TYPE);
11090                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11091
11092                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11093                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11094                            verifierUser.getIdentifier());
11095
11096                    if (DEBUG_VERIFY) {
11097                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11098                                + verification.toString() + " with " + pkgLite.verifiers.length
11099                                + " optional verifiers");
11100                    }
11101
11102                    final int verificationId = mPendingVerificationToken++;
11103
11104                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11105
11106                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11107                            installerPackageName);
11108
11109                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11110                            installFlags);
11111
11112                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11113                            pkgLite.packageName);
11114
11115                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11116                            pkgLite.versionCode);
11117
11118                    if (verificationParams != null) {
11119                        if (verificationParams.getVerificationURI() != null) {
11120                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11121                                 verificationParams.getVerificationURI());
11122                        }
11123                        if (verificationParams.getOriginatingURI() != null) {
11124                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11125                                  verificationParams.getOriginatingURI());
11126                        }
11127                        if (verificationParams.getReferrer() != null) {
11128                            verification.putExtra(Intent.EXTRA_REFERRER,
11129                                  verificationParams.getReferrer());
11130                        }
11131                        if (verificationParams.getOriginatingUid() >= 0) {
11132                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11133                                  verificationParams.getOriginatingUid());
11134                        }
11135                        if (verificationParams.getInstallerUid() >= 0) {
11136                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11137                                  verificationParams.getInstallerUid());
11138                        }
11139                    }
11140
11141                    final PackageVerificationState verificationState = new PackageVerificationState(
11142                            requiredUid, args);
11143
11144                    mPendingVerification.append(verificationId, verificationState);
11145
11146                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11147                            receivers, verificationState);
11148
11149                    /*
11150                     * If any sufficient verifiers were listed in the package
11151                     * manifest, attempt to ask them.
11152                     */
11153                    if (sufficientVerifiers != null) {
11154                        final int N = sufficientVerifiers.size();
11155                        if (N == 0) {
11156                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11157                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11158                        } else {
11159                            for (int i = 0; i < N; i++) {
11160                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11161
11162                                final Intent sufficientIntent = new Intent(verification);
11163                                sufficientIntent.setComponent(verifierComponent);
11164                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11165                            }
11166                        }
11167                    }
11168
11169                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11170                            mRequiredVerifierPackage, receivers);
11171                    if (ret == PackageManager.INSTALL_SUCCEEDED
11172                            && mRequiredVerifierPackage != null) {
11173                        Trace.asyncTraceBegin(
11174                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11175                        /*
11176                         * Send the intent to the required verification agent,
11177                         * but only start the verification timeout after the
11178                         * target BroadcastReceivers have run.
11179                         */
11180                        verification.setComponent(requiredVerifierComponent);
11181                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11182                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11183                                new BroadcastReceiver() {
11184                                    @Override
11185                                    public void onReceive(Context context, Intent intent) {
11186                                        final Message msg = mHandler
11187                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11188                                        msg.arg1 = verificationId;
11189                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11190                                    }
11191                                }, null, 0, null, null);
11192
11193                        /*
11194                         * We don't want the copy to proceed until verification
11195                         * succeeds, so null out this field.
11196                         */
11197                        mArgs = null;
11198                    }
11199                } else {
11200                    /*
11201                     * No package verification is enabled, so immediately start
11202                     * the remote call to initiate copy using temporary file.
11203                     */
11204                    ret = args.copyApk(mContainerService, true);
11205                }
11206            }
11207
11208            mRet = ret;
11209        }
11210
11211        @Override
11212        void handleReturnCode() {
11213            // If mArgs is null, then MCS couldn't be reached. When it
11214            // reconnects, it will try again to install. At that point, this
11215            // will succeed.
11216            if (mArgs != null) {
11217                processPendingInstall(mArgs, mRet);
11218            }
11219        }
11220
11221        @Override
11222        void handleServiceError() {
11223            mArgs = createInstallArgs(this);
11224            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11225        }
11226
11227        public boolean isForwardLocked() {
11228            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11229        }
11230    }
11231
11232    /**
11233     * Used during creation of InstallArgs
11234     *
11235     * @param installFlags package installation flags
11236     * @return true if should be installed on external storage
11237     */
11238    private static boolean installOnExternalAsec(int installFlags) {
11239        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11240            return false;
11241        }
11242        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11243            return true;
11244        }
11245        return false;
11246    }
11247
11248    /**
11249     * Used during creation of InstallArgs
11250     *
11251     * @param installFlags package installation flags
11252     * @return true if should be installed as forward locked
11253     */
11254    private static boolean installForwardLocked(int installFlags) {
11255        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11256    }
11257
11258    private InstallArgs createInstallArgs(InstallParams params) {
11259        if (params.move != null) {
11260            return new MoveInstallArgs(params);
11261        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11262            return new AsecInstallArgs(params);
11263        } else {
11264            return new FileInstallArgs(params);
11265        }
11266    }
11267
11268    /**
11269     * Create args that describe an existing installed package. Typically used
11270     * when cleaning up old installs, or used as a move source.
11271     */
11272    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11273            String resourcePath, String[] instructionSets) {
11274        final boolean isInAsec;
11275        if (installOnExternalAsec(installFlags)) {
11276            /* Apps on SD card are always in ASEC containers. */
11277            isInAsec = true;
11278        } else if (installForwardLocked(installFlags)
11279                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11280            /*
11281             * Forward-locked apps are only in ASEC containers if they're the
11282             * new style
11283             */
11284            isInAsec = true;
11285        } else {
11286            isInAsec = false;
11287        }
11288
11289        if (isInAsec) {
11290            return new AsecInstallArgs(codePath, instructionSets,
11291                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11292        } else {
11293            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11294        }
11295    }
11296
11297    static abstract class InstallArgs {
11298        /** @see InstallParams#origin */
11299        final OriginInfo origin;
11300        /** @see InstallParams#move */
11301        final MoveInfo move;
11302
11303        final IPackageInstallObserver2 observer;
11304        // Always refers to PackageManager flags only
11305        final int installFlags;
11306        final String installerPackageName;
11307        final String volumeUuid;
11308        final ManifestDigest manifestDigest;
11309        final UserHandle user;
11310        final String abiOverride;
11311        final String[] installGrantPermissions;
11312        /** If non-null, drop an async trace when the install completes */
11313        final String traceMethod;
11314        final int traceCookie;
11315
11316        // The list of instruction sets supported by this app. This is currently
11317        // only used during the rmdex() phase to clean up resources. We can get rid of this
11318        // if we move dex files under the common app path.
11319        /* nullable */ String[] instructionSets;
11320
11321        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11322                int installFlags, String installerPackageName, String volumeUuid,
11323                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11324                String abiOverride, String[] installGrantPermissions,
11325                String traceMethod, int traceCookie) {
11326            this.origin = origin;
11327            this.move = move;
11328            this.installFlags = installFlags;
11329            this.observer = observer;
11330            this.installerPackageName = installerPackageName;
11331            this.volumeUuid = volumeUuid;
11332            this.manifestDigest = manifestDigest;
11333            this.user = user;
11334            this.instructionSets = instructionSets;
11335            this.abiOverride = abiOverride;
11336            this.installGrantPermissions = installGrantPermissions;
11337            this.traceMethod = traceMethod;
11338            this.traceCookie = traceCookie;
11339        }
11340
11341        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11342        abstract int doPreInstall(int status);
11343
11344        /**
11345         * Rename package into final resting place. All paths on the given
11346         * scanned package should be updated to reflect the rename.
11347         */
11348        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11349        abstract int doPostInstall(int status, int uid);
11350
11351        /** @see PackageSettingBase#codePathString */
11352        abstract String getCodePath();
11353        /** @see PackageSettingBase#resourcePathString */
11354        abstract String getResourcePath();
11355
11356        // Need installer lock especially for dex file removal.
11357        abstract void cleanUpResourcesLI();
11358        abstract boolean doPostDeleteLI(boolean delete);
11359
11360        /**
11361         * Called before the source arguments are copied. This is used mostly
11362         * for MoveParams when it needs to read the source file to put it in the
11363         * destination.
11364         */
11365        int doPreCopy() {
11366            return PackageManager.INSTALL_SUCCEEDED;
11367        }
11368
11369        /**
11370         * Called after the source arguments are copied. This is used mostly for
11371         * MoveParams when it needs to read the source file to put it in the
11372         * destination.
11373         *
11374         * @return
11375         */
11376        int doPostCopy(int uid) {
11377            return PackageManager.INSTALL_SUCCEEDED;
11378        }
11379
11380        protected boolean isFwdLocked() {
11381            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11382        }
11383
11384        protected boolean isExternalAsec() {
11385            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11386        }
11387
11388        protected boolean isEphemeral() {
11389            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11390        }
11391
11392        UserHandle getUser() {
11393            return user;
11394        }
11395    }
11396
11397    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11398        if (!allCodePaths.isEmpty()) {
11399            if (instructionSets == null) {
11400                throw new IllegalStateException("instructionSet == null");
11401            }
11402            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11403            for (String codePath : allCodePaths) {
11404                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11405                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11406                    if (retCode < 0) {
11407                        Slog.w(TAG, "Couldn't remove dex file for package: "
11408                                + " at location " + codePath + ", retcode=" + retCode);
11409                        // we don't consider this to be a failure of the core package deletion
11410                    }
11411                }
11412            }
11413        }
11414    }
11415
11416    /**
11417     * Logic to handle installation of non-ASEC applications, including copying
11418     * and renaming logic.
11419     */
11420    class FileInstallArgs extends InstallArgs {
11421        private File codeFile;
11422        private File resourceFile;
11423
11424        // Example topology:
11425        // /data/app/com.example/base.apk
11426        // /data/app/com.example/split_foo.apk
11427        // /data/app/com.example/lib/arm/libfoo.so
11428        // /data/app/com.example/lib/arm64/libfoo.so
11429        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11430
11431        /** New install */
11432        FileInstallArgs(InstallParams params) {
11433            super(params.origin, params.move, params.observer, params.installFlags,
11434                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11435                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11436                    params.grantedRuntimePermissions,
11437                    params.traceMethod, params.traceCookie);
11438            if (isFwdLocked()) {
11439                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11440            }
11441        }
11442
11443        /** Existing install */
11444        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11445            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11446                    null, null, null, 0);
11447            this.codeFile = (codePath != null) ? new File(codePath) : null;
11448            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11449        }
11450
11451        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11452            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11453            try {
11454                return doCopyApk(imcs, temp);
11455            } finally {
11456                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11457            }
11458        }
11459
11460        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11461            if (origin.staged) {
11462                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11463                codeFile = origin.file;
11464                resourceFile = origin.file;
11465                return PackageManager.INSTALL_SUCCEEDED;
11466            }
11467
11468            try {
11469                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11470                final File tempDir =
11471                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11472                codeFile = tempDir;
11473                resourceFile = tempDir;
11474            } catch (IOException e) {
11475                Slog.w(TAG, "Failed to create copy file: " + e);
11476                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11477            }
11478
11479            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11480                @Override
11481                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11482                    if (!FileUtils.isValidExtFilename(name)) {
11483                        throw new IllegalArgumentException("Invalid filename: " + name);
11484                    }
11485                    try {
11486                        final File file = new File(codeFile, name);
11487                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11488                                O_RDWR | O_CREAT, 0644);
11489                        Os.chmod(file.getAbsolutePath(), 0644);
11490                        return new ParcelFileDescriptor(fd);
11491                    } catch (ErrnoException e) {
11492                        throw new RemoteException("Failed to open: " + e.getMessage());
11493                    }
11494                }
11495            };
11496
11497            int ret = PackageManager.INSTALL_SUCCEEDED;
11498            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11499            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11500                Slog.e(TAG, "Failed to copy package");
11501                return ret;
11502            }
11503
11504            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11505            NativeLibraryHelper.Handle handle = null;
11506            try {
11507                handle = NativeLibraryHelper.Handle.create(codeFile);
11508                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11509                        abiOverride);
11510            } catch (IOException e) {
11511                Slog.e(TAG, "Copying native libraries failed", e);
11512                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11513            } finally {
11514                IoUtils.closeQuietly(handle);
11515            }
11516
11517            return ret;
11518        }
11519
11520        int doPreInstall(int status) {
11521            if (status != PackageManager.INSTALL_SUCCEEDED) {
11522                cleanUp();
11523            }
11524            return status;
11525        }
11526
11527        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11528            if (status != PackageManager.INSTALL_SUCCEEDED) {
11529                cleanUp();
11530                return false;
11531            }
11532
11533            final File targetDir = codeFile.getParentFile();
11534            final File beforeCodeFile = codeFile;
11535            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11536
11537            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11538            try {
11539                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11540            } catch (ErrnoException e) {
11541                Slog.w(TAG, "Failed to rename", e);
11542                return false;
11543            }
11544
11545            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11546                Slog.w(TAG, "Failed to restorecon");
11547                return false;
11548            }
11549
11550            // Reflect the rename internally
11551            codeFile = afterCodeFile;
11552            resourceFile = afterCodeFile;
11553
11554            // Reflect the rename in scanned details
11555            pkg.codePath = afterCodeFile.getAbsolutePath();
11556            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11557                    pkg.baseCodePath);
11558            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11559                    pkg.splitCodePaths);
11560
11561            // Reflect the rename in app info
11562            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11563            pkg.applicationInfo.setCodePath(pkg.codePath);
11564            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11565            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11566            pkg.applicationInfo.setResourcePath(pkg.codePath);
11567            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11568            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11569
11570            return true;
11571        }
11572
11573        int doPostInstall(int status, int uid) {
11574            if (status != PackageManager.INSTALL_SUCCEEDED) {
11575                cleanUp();
11576            }
11577            return status;
11578        }
11579
11580        @Override
11581        String getCodePath() {
11582            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11583        }
11584
11585        @Override
11586        String getResourcePath() {
11587            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11588        }
11589
11590        private boolean cleanUp() {
11591            if (codeFile == null || !codeFile.exists()) {
11592                return false;
11593            }
11594
11595            if (codeFile.isDirectory()) {
11596                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11597            } else {
11598                codeFile.delete();
11599            }
11600
11601            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11602                resourceFile.delete();
11603            }
11604
11605            return true;
11606        }
11607
11608        void cleanUpResourcesLI() {
11609            // Try enumerating all code paths before deleting
11610            List<String> allCodePaths = Collections.EMPTY_LIST;
11611            if (codeFile != null && codeFile.exists()) {
11612                try {
11613                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11614                    allCodePaths = pkg.getAllCodePaths();
11615                } catch (PackageParserException e) {
11616                    // Ignored; we tried our best
11617                }
11618            }
11619
11620            cleanUp();
11621            removeDexFiles(allCodePaths, instructionSets);
11622        }
11623
11624        boolean doPostDeleteLI(boolean delete) {
11625            // XXX err, shouldn't we respect the delete flag?
11626            cleanUpResourcesLI();
11627            return true;
11628        }
11629    }
11630
11631    private boolean isAsecExternal(String cid) {
11632        final String asecPath = PackageHelper.getSdFilesystem(cid);
11633        return !asecPath.startsWith(mAsecInternalPath);
11634    }
11635
11636    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11637            PackageManagerException {
11638        if (copyRet < 0) {
11639            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11640                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11641                throw new PackageManagerException(copyRet, message);
11642            }
11643        }
11644    }
11645
11646    /**
11647     * Extract the MountService "container ID" from the full code path of an
11648     * .apk.
11649     */
11650    static String cidFromCodePath(String fullCodePath) {
11651        int eidx = fullCodePath.lastIndexOf("/");
11652        String subStr1 = fullCodePath.substring(0, eidx);
11653        int sidx = subStr1.lastIndexOf("/");
11654        return subStr1.substring(sidx+1, eidx);
11655    }
11656
11657    /**
11658     * Logic to handle installation of ASEC applications, including copying and
11659     * renaming logic.
11660     */
11661    class AsecInstallArgs extends InstallArgs {
11662        static final String RES_FILE_NAME = "pkg.apk";
11663        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11664
11665        String cid;
11666        String packagePath;
11667        String resourcePath;
11668
11669        /** New install */
11670        AsecInstallArgs(InstallParams params) {
11671            super(params.origin, params.move, params.observer, params.installFlags,
11672                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11673                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11674                    params.grantedRuntimePermissions,
11675                    params.traceMethod, params.traceCookie);
11676        }
11677
11678        /** Existing install */
11679        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11680                        boolean isExternal, boolean isForwardLocked) {
11681            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11682                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11683                    instructionSets, null, null, null, 0);
11684            // Hackily pretend we're still looking at a full code path
11685            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11686                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11687            }
11688
11689            // Extract cid from fullCodePath
11690            int eidx = fullCodePath.lastIndexOf("/");
11691            String subStr1 = fullCodePath.substring(0, eidx);
11692            int sidx = subStr1.lastIndexOf("/");
11693            cid = subStr1.substring(sidx+1, eidx);
11694            setMountPath(subStr1);
11695        }
11696
11697        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11698            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11699                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11700                    instructionSets, null, null, null, 0);
11701            this.cid = cid;
11702            setMountPath(PackageHelper.getSdDir(cid));
11703        }
11704
11705        void createCopyFile() {
11706            cid = mInstallerService.allocateExternalStageCidLegacy();
11707        }
11708
11709        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11710            if (origin.staged && origin.cid != null) {
11711                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11712                cid = origin.cid;
11713                setMountPath(PackageHelper.getSdDir(cid));
11714                return PackageManager.INSTALL_SUCCEEDED;
11715            }
11716
11717            if (temp) {
11718                createCopyFile();
11719            } else {
11720                /*
11721                 * Pre-emptively destroy the container since it's destroyed if
11722                 * copying fails due to it existing anyway.
11723                 */
11724                PackageHelper.destroySdDir(cid);
11725            }
11726
11727            final String newMountPath = imcs.copyPackageToContainer(
11728                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11729                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11730
11731            if (newMountPath != null) {
11732                setMountPath(newMountPath);
11733                return PackageManager.INSTALL_SUCCEEDED;
11734            } else {
11735                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11736            }
11737        }
11738
11739        @Override
11740        String getCodePath() {
11741            return packagePath;
11742        }
11743
11744        @Override
11745        String getResourcePath() {
11746            return resourcePath;
11747        }
11748
11749        int doPreInstall(int status) {
11750            if (status != PackageManager.INSTALL_SUCCEEDED) {
11751                // Destroy container
11752                PackageHelper.destroySdDir(cid);
11753            } else {
11754                boolean mounted = PackageHelper.isContainerMounted(cid);
11755                if (!mounted) {
11756                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11757                            Process.SYSTEM_UID);
11758                    if (newMountPath != null) {
11759                        setMountPath(newMountPath);
11760                    } else {
11761                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11762                    }
11763                }
11764            }
11765            return status;
11766        }
11767
11768        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11769            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11770            String newMountPath = null;
11771            if (PackageHelper.isContainerMounted(cid)) {
11772                // Unmount the container
11773                if (!PackageHelper.unMountSdDir(cid)) {
11774                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11775                    return false;
11776                }
11777            }
11778            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11779                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11780                        " which might be stale. Will try to clean up.");
11781                // Clean up the stale container and proceed to recreate.
11782                if (!PackageHelper.destroySdDir(newCacheId)) {
11783                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11784                    return false;
11785                }
11786                // Successfully cleaned up stale container. Try to rename again.
11787                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11788                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11789                            + " inspite of cleaning it up.");
11790                    return false;
11791                }
11792            }
11793            if (!PackageHelper.isContainerMounted(newCacheId)) {
11794                Slog.w(TAG, "Mounting container " + newCacheId);
11795                newMountPath = PackageHelper.mountSdDir(newCacheId,
11796                        getEncryptKey(), Process.SYSTEM_UID);
11797            } else {
11798                newMountPath = PackageHelper.getSdDir(newCacheId);
11799            }
11800            if (newMountPath == null) {
11801                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11802                return false;
11803            }
11804            Log.i(TAG, "Succesfully renamed " + cid +
11805                    " to " + newCacheId +
11806                    " at new path: " + newMountPath);
11807            cid = newCacheId;
11808
11809            final File beforeCodeFile = new File(packagePath);
11810            setMountPath(newMountPath);
11811            final File afterCodeFile = new File(packagePath);
11812
11813            // Reflect the rename in scanned details
11814            pkg.codePath = afterCodeFile.getAbsolutePath();
11815            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11816                    pkg.baseCodePath);
11817            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11818                    pkg.splitCodePaths);
11819
11820            // Reflect the rename in app info
11821            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11822            pkg.applicationInfo.setCodePath(pkg.codePath);
11823            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11824            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11825            pkg.applicationInfo.setResourcePath(pkg.codePath);
11826            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11827            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11828
11829            return true;
11830        }
11831
11832        private void setMountPath(String mountPath) {
11833            final File mountFile = new File(mountPath);
11834
11835            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11836            if (monolithicFile.exists()) {
11837                packagePath = monolithicFile.getAbsolutePath();
11838                if (isFwdLocked()) {
11839                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11840                } else {
11841                    resourcePath = packagePath;
11842                }
11843            } else {
11844                packagePath = mountFile.getAbsolutePath();
11845                resourcePath = packagePath;
11846            }
11847        }
11848
11849        int doPostInstall(int status, int uid) {
11850            if (status != PackageManager.INSTALL_SUCCEEDED) {
11851                cleanUp();
11852            } else {
11853                final int groupOwner;
11854                final String protectedFile;
11855                if (isFwdLocked()) {
11856                    groupOwner = UserHandle.getSharedAppGid(uid);
11857                    protectedFile = RES_FILE_NAME;
11858                } else {
11859                    groupOwner = -1;
11860                    protectedFile = null;
11861                }
11862
11863                if (uid < Process.FIRST_APPLICATION_UID
11864                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11865                    Slog.e(TAG, "Failed to finalize " + cid);
11866                    PackageHelper.destroySdDir(cid);
11867                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11868                }
11869
11870                boolean mounted = PackageHelper.isContainerMounted(cid);
11871                if (!mounted) {
11872                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11873                }
11874            }
11875            return status;
11876        }
11877
11878        private void cleanUp() {
11879            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11880
11881            // Destroy secure container
11882            PackageHelper.destroySdDir(cid);
11883        }
11884
11885        private List<String> getAllCodePaths() {
11886            final File codeFile = new File(getCodePath());
11887            if (codeFile != null && codeFile.exists()) {
11888                try {
11889                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11890                    return pkg.getAllCodePaths();
11891                } catch (PackageParserException e) {
11892                    // Ignored; we tried our best
11893                }
11894            }
11895            return Collections.EMPTY_LIST;
11896        }
11897
11898        void cleanUpResourcesLI() {
11899            // Enumerate all code paths before deleting
11900            cleanUpResourcesLI(getAllCodePaths());
11901        }
11902
11903        private void cleanUpResourcesLI(List<String> allCodePaths) {
11904            cleanUp();
11905            removeDexFiles(allCodePaths, instructionSets);
11906        }
11907
11908        String getPackageName() {
11909            return getAsecPackageName(cid);
11910        }
11911
11912        boolean doPostDeleteLI(boolean delete) {
11913            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11914            final List<String> allCodePaths = getAllCodePaths();
11915            boolean mounted = PackageHelper.isContainerMounted(cid);
11916            if (mounted) {
11917                // Unmount first
11918                if (PackageHelper.unMountSdDir(cid)) {
11919                    mounted = false;
11920                }
11921            }
11922            if (!mounted && delete) {
11923                cleanUpResourcesLI(allCodePaths);
11924            }
11925            return !mounted;
11926        }
11927
11928        @Override
11929        int doPreCopy() {
11930            if (isFwdLocked()) {
11931                if (!PackageHelper.fixSdPermissions(cid,
11932                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11933                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11934                }
11935            }
11936
11937            return PackageManager.INSTALL_SUCCEEDED;
11938        }
11939
11940        @Override
11941        int doPostCopy(int uid) {
11942            if (isFwdLocked()) {
11943                if (uid < Process.FIRST_APPLICATION_UID
11944                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11945                                RES_FILE_NAME)) {
11946                    Slog.e(TAG, "Failed to finalize " + cid);
11947                    PackageHelper.destroySdDir(cid);
11948                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11949                }
11950            }
11951
11952            return PackageManager.INSTALL_SUCCEEDED;
11953        }
11954    }
11955
11956    /**
11957     * Logic to handle movement of existing installed applications.
11958     */
11959    class MoveInstallArgs extends InstallArgs {
11960        private File codeFile;
11961        private File resourceFile;
11962
11963        /** New install */
11964        MoveInstallArgs(InstallParams params) {
11965            super(params.origin, params.move, params.observer, params.installFlags,
11966                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11967                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11968                    params.grantedRuntimePermissions,
11969                    params.traceMethod, params.traceCookie);
11970        }
11971
11972        int copyApk(IMediaContainerService imcs, boolean temp) {
11973            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11974                    + move.fromUuid + " to " + move.toUuid);
11975            synchronized (mInstaller) {
11976                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11977                        move.dataAppName, move.appId, move.seinfo) != 0) {
11978                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11979                }
11980            }
11981
11982            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11983            resourceFile = codeFile;
11984            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11985
11986            return PackageManager.INSTALL_SUCCEEDED;
11987        }
11988
11989        int doPreInstall(int status) {
11990            if (status != PackageManager.INSTALL_SUCCEEDED) {
11991                cleanUp(move.toUuid);
11992            }
11993            return status;
11994        }
11995
11996        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11997            if (status != PackageManager.INSTALL_SUCCEEDED) {
11998                cleanUp(move.toUuid);
11999                return false;
12000            }
12001
12002            // Reflect the move in app info
12003            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12004            pkg.applicationInfo.setCodePath(pkg.codePath);
12005            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12006            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12007            pkg.applicationInfo.setResourcePath(pkg.codePath);
12008            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12009            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12010
12011            return true;
12012        }
12013
12014        int doPostInstall(int status, int uid) {
12015            if (status == PackageManager.INSTALL_SUCCEEDED) {
12016                cleanUp(move.fromUuid);
12017            } else {
12018                cleanUp(move.toUuid);
12019            }
12020            return status;
12021        }
12022
12023        @Override
12024        String getCodePath() {
12025            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12026        }
12027
12028        @Override
12029        String getResourcePath() {
12030            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12031        }
12032
12033        private boolean cleanUp(String volumeUuid) {
12034            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12035                    move.dataAppName);
12036            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12037            synchronized (mInstallLock) {
12038                // Clean up both app data and code
12039                removeDataDirsLI(volumeUuid, move.packageName);
12040                if (codeFile.isDirectory()) {
12041                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12042                } else {
12043                    codeFile.delete();
12044                }
12045            }
12046            return true;
12047        }
12048
12049        void cleanUpResourcesLI() {
12050            throw new UnsupportedOperationException();
12051        }
12052
12053        boolean doPostDeleteLI(boolean delete) {
12054            throw new UnsupportedOperationException();
12055        }
12056    }
12057
12058    static String getAsecPackageName(String packageCid) {
12059        int idx = packageCid.lastIndexOf("-");
12060        if (idx == -1) {
12061            return packageCid;
12062        }
12063        return packageCid.substring(0, idx);
12064    }
12065
12066    // Utility method used to create code paths based on package name and available index.
12067    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12068        String idxStr = "";
12069        int idx = 1;
12070        // Fall back to default value of idx=1 if prefix is not
12071        // part of oldCodePath
12072        if (oldCodePath != null) {
12073            String subStr = oldCodePath;
12074            // Drop the suffix right away
12075            if (suffix != null && subStr.endsWith(suffix)) {
12076                subStr = subStr.substring(0, subStr.length() - suffix.length());
12077            }
12078            // If oldCodePath already contains prefix find out the
12079            // ending index to either increment or decrement.
12080            int sidx = subStr.lastIndexOf(prefix);
12081            if (sidx != -1) {
12082                subStr = subStr.substring(sidx + prefix.length());
12083                if (subStr != null) {
12084                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12085                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12086                    }
12087                    try {
12088                        idx = Integer.parseInt(subStr);
12089                        if (idx <= 1) {
12090                            idx++;
12091                        } else {
12092                            idx--;
12093                        }
12094                    } catch(NumberFormatException e) {
12095                    }
12096                }
12097            }
12098        }
12099        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12100        return prefix + idxStr;
12101    }
12102
12103    private File getNextCodePath(File targetDir, String packageName) {
12104        int suffix = 1;
12105        File result;
12106        do {
12107            result = new File(targetDir, packageName + "-" + suffix);
12108            suffix++;
12109        } while (result.exists());
12110        return result;
12111    }
12112
12113    // Utility method that returns the relative package path with respect
12114    // to the installation directory. Like say for /data/data/com.test-1.apk
12115    // string com.test-1 is returned.
12116    static String deriveCodePathName(String codePath) {
12117        if (codePath == null) {
12118            return null;
12119        }
12120        final File codeFile = new File(codePath);
12121        final String name = codeFile.getName();
12122        if (codeFile.isDirectory()) {
12123            return name;
12124        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12125            final int lastDot = name.lastIndexOf('.');
12126            return name.substring(0, lastDot);
12127        } else {
12128            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12129            return null;
12130        }
12131    }
12132
12133    class PackageInstalledInfo {
12134        String name;
12135        int uid;
12136        // The set of users that originally had this package installed.
12137        int[] origUsers;
12138        // The set of users that now have this package installed.
12139        int[] newUsers;
12140        PackageParser.Package pkg;
12141        int returnCode;
12142        String returnMsg;
12143        PackageRemovedInfo removedInfo;
12144
12145        public void setError(int code, String msg) {
12146            returnCode = code;
12147            returnMsg = msg;
12148            Slog.w(TAG, msg);
12149        }
12150
12151        public void setError(String msg, PackageParserException e) {
12152            returnCode = e.error;
12153            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12154            Slog.w(TAG, msg, e);
12155        }
12156
12157        public void setError(String msg, PackageManagerException e) {
12158            returnCode = e.error;
12159            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12160            Slog.w(TAG, msg, e);
12161        }
12162
12163        // In some error cases we want to convey more info back to the observer
12164        String origPackage;
12165        String origPermission;
12166    }
12167
12168    /*
12169     * Install a non-existing package.
12170     */
12171    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12172            UserHandle user, String installerPackageName, String volumeUuid,
12173            PackageInstalledInfo res) {
12174        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12175
12176        // Remember this for later, in case we need to rollback this install
12177        String pkgName = pkg.packageName;
12178
12179        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12180        // TODO: b/23350563
12181        final boolean dataDirExists = Environment
12182                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12183
12184        synchronized(mPackages) {
12185            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12186                // A package with the same name is already installed, though
12187                // it has been renamed to an older name.  The package we
12188                // are trying to install should be installed as an update to
12189                // the existing one, but that has not been requested, so bail.
12190                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12191                        + " without first uninstalling package running as "
12192                        + mSettings.mRenamedPackages.get(pkgName));
12193                return;
12194            }
12195            if (mPackages.containsKey(pkgName)) {
12196                // Don't allow installation over an existing package with the same name.
12197                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12198                        + " without first uninstalling.");
12199                return;
12200            }
12201        }
12202
12203        try {
12204            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12205                    System.currentTimeMillis(), user);
12206
12207            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12208            // delete the partially installed application. the data directory will have to be
12209            // restored if it was already existing
12210            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12211                // remove package from internal structures.  Note that we want deletePackageX to
12212                // delete the package data and cache directories that it created in
12213                // scanPackageLocked, unless those directories existed before we even tried to
12214                // install.
12215                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12216                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12217                                res.removedInfo, true);
12218            }
12219
12220        } catch (PackageManagerException e) {
12221            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12222        }
12223
12224        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12225    }
12226
12227    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12228        // Can't rotate keys during boot or if sharedUser.
12229        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12230                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12231            return false;
12232        }
12233        // app is using upgradeKeySets; make sure all are valid
12234        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12235        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12236        for (int i = 0; i < upgradeKeySets.length; i++) {
12237            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12238                Slog.wtf(TAG, "Package "
12239                         + (oldPs.name != null ? oldPs.name : "<null>")
12240                         + " contains upgrade-key-set reference to unknown key-set: "
12241                         + upgradeKeySets[i]
12242                         + " reverting to signatures check.");
12243                return false;
12244            }
12245        }
12246        return true;
12247    }
12248
12249    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12250        // Upgrade keysets are being used.  Determine if new package has a superset of the
12251        // required keys.
12252        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12253        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12254        for (int i = 0; i < upgradeKeySets.length; i++) {
12255            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12256            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12257                return true;
12258            }
12259        }
12260        return false;
12261    }
12262
12263    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12264            UserHandle user, String installerPackageName, String volumeUuid,
12265            PackageInstalledInfo res) {
12266        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12267
12268        final PackageParser.Package oldPackage;
12269        final String pkgName = pkg.packageName;
12270        final int[] allUsers;
12271        final boolean[] perUserInstalled;
12272
12273        // First find the old package info and check signatures
12274        synchronized(mPackages) {
12275            oldPackage = mPackages.get(pkgName);
12276            final boolean oldIsEphemeral
12277                    = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_EPHEMERAL) != 0);
12278            if (isEphemeral && !oldIsEphemeral) {
12279                // can't downgrade from full to ephemeral
12280                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12281                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12282                return;
12283            }
12284            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12285            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12286            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12287                if(!checkUpgradeKeySetLP(ps, pkg)) {
12288                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12289                            "New package not signed by keys specified by upgrade-keysets: "
12290                            + pkgName);
12291                    return;
12292                }
12293            } else {
12294                // default to original signature matching
12295                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12296                    != PackageManager.SIGNATURE_MATCH) {
12297                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12298                            "New package has a different signature: " + pkgName);
12299                    return;
12300                }
12301            }
12302
12303            // In case of rollback, remember per-user/profile install state
12304            allUsers = sUserManager.getUserIds();
12305            perUserInstalled = new boolean[allUsers.length];
12306            for (int i = 0; i < allUsers.length; i++) {
12307                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12308            }
12309        }
12310
12311        boolean sysPkg = (isSystemApp(oldPackage));
12312        if (sysPkg) {
12313            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12314                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12315        } else {
12316            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12317                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12318        }
12319    }
12320
12321    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12322            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12323            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12324            String volumeUuid, PackageInstalledInfo res) {
12325        String pkgName = deletedPackage.packageName;
12326        boolean deletedPkg = true;
12327        boolean updatedSettings = false;
12328
12329        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12330                + deletedPackage);
12331        long origUpdateTime;
12332        if (pkg.mExtras != null) {
12333            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12334        } else {
12335            origUpdateTime = 0;
12336        }
12337
12338        // First delete the existing package while retaining the data directory
12339        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12340                res.removedInfo, true)) {
12341            // If the existing package wasn't successfully deleted
12342            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12343            deletedPkg = false;
12344        } else {
12345            // Successfully deleted the old package; proceed with replace.
12346
12347            // If deleted package lived in a container, give users a chance to
12348            // relinquish resources before killing.
12349            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12350                if (DEBUG_INSTALL) {
12351                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12352                }
12353                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12354                final ArrayList<String> pkgList = new ArrayList<String>(1);
12355                pkgList.add(deletedPackage.applicationInfo.packageName);
12356                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12357            }
12358
12359            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12360            try {
12361                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12362                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12363                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12364                        perUserInstalled, res, user);
12365                updatedSettings = true;
12366            } catch (PackageManagerException e) {
12367                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12368            }
12369        }
12370
12371        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12372            // remove package from internal structures.  Note that we want deletePackageX to
12373            // delete the package data and cache directories that it created in
12374            // scanPackageLocked, unless those directories existed before we even tried to
12375            // install.
12376            if(updatedSettings) {
12377                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12378                deletePackageLI(
12379                        pkgName, null, true, allUsers, perUserInstalled,
12380                        PackageManager.DELETE_KEEP_DATA,
12381                                res.removedInfo, true);
12382            }
12383            // Since we failed to install the new package we need to restore the old
12384            // package that we deleted.
12385            if (deletedPkg) {
12386                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12387                File restoreFile = new File(deletedPackage.codePath);
12388                // Parse old package
12389                boolean oldExternal = isExternal(deletedPackage);
12390                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12391                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12392                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12393                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12394                try {
12395                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12396                            null);
12397                } catch (PackageManagerException e) {
12398                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12399                            + e.getMessage());
12400                    return;
12401                }
12402                // Restore of old package succeeded. Update permissions.
12403                // writer
12404                synchronized (mPackages) {
12405                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12406                            UPDATE_PERMISSIONS_ALL);
12407                    // can downgrade to reader
12408                    mSettings.writeLPr();
12409                }
12410                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12411            }
12412        }
12413    }
12414
12415    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12416            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12417            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12418            String volumeUuid, PackageInstalledInfo res) {
12419        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12420                + ", old=" + deletedPackage);
12421        boolean disabledSystem = false;
12422        boolean updatedSettings = false;
12423        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12424        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12425                != 0) {
12426            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12427        }
12428        String packageName = deletedPackage.packageName;
12429        if (packageName == null) {
12430            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12431                    "Attempt to delete null packageName.");
12432            return;
12433        }
12434        PackageParser.Package oldPkg;
12435        PackageSetting oldPkgSetting;
12436        // reader
12437        synchronized (mPackages) {
12438            oldPkg = mPackages.get(packageName);
12439            oldPkgSetting = mSettings.mPackages.get(packageName);
12440            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12441                    (oldPkgSetting == null)) {
12442                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12443                        "Couldn't find package:" + packageName + " information");
12444                return;
12445            }
12446        }
12447
12448        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12449
12450        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12451        res.removedInfo.removedPackage = packageName;
12452        // Remove existing system package
12453        removePackageLI(oldPkgSetting, true);
12454        // writer
12455        synchronized (mPackages) {
12456            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12457            if (!disabledSystem && deletedPackage != null) {
12458                // We didn't need to disable the .apk as a current system package,
12459                // which means we are replacing another update that is already
12460                // installed.  We need to make sure to delete the older one's .apk.
12461                res.removedInfo.args = createInstallArgsForExisting(0,
12462                        deletedPackage.applicationInfo.getCodePath(),
12463                        deletedPackage.applicationInfo.getResourcePath(),
12464                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12465            } else {
12466                res.removedInfo.args = null;
12467            }
12468        }
12469
12470        // Successfully disabled the old package. Now proceed with re-installation
12471        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12472
12473        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12474        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12475
12476        PackageParser.Package newPackage = null;
12477        try {
12478            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12479            if (newPackage.mExtras != null) {
12480                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12481                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12482                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12483
12484                // is the update attempting to change shared user? that isn't going to work...
12485                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12486                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12487                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12488                            + " to " + newPkgSetting.sharedUser);
12489                    updatedSettings = true;
12490                }
12491            }
12492
12493            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12494                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12495                        perUserInstalled, res, user);
12496                updatedSettings = true;
12497            }
12498
12499        } catch (PackageManagerException e) {
12500            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12501        }
12502
12503        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12504            // Re installation failed. Restore old information
12505            // Remove new pkg information
12506            if (newPackage != null) {
12507                removeInstalledPackageLI(newPackage, true);
12508            }
12509            // Add back the old system package
12510            try {
12511                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12512            } catch (PackageManagerException e) {
12513                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12514            }
12515            // Restore the old system information in Settings
12516            synchronized (mPackages) {
12517                if (disabledSystem) {
12518                    mSettings.enableSystemPackageLPw(packageName);
12519                }
12520                if (updatedSettings) {
12521                    mSettings.setInstallerPackageName(packageName,
12522                            oldPkgSetting.installerPackageName);
12523                }
12524                mSettings.writeLPr();
12525            }
12526        }
12527    }
12528
12529    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12530        // Collect all used permissions in the UID
12531        ArraySet<String> usedPermissions = new ArraySet<>();
12532        final int packageCount = su.packages.size();
12533        for (int i = 0; i < packageCount; i++) {
12534            PackageSetting ps = su.packages.valueAt(i);
12535            if (ps.pkg == null) {
12536                continue;
12537            }
12538            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12539            for (int j = 0; j < requestedPermCount; j++) {
12540                String permission = ps.pkg.requestedPermissions.get(j);
12541                BasePermission bp = mSettings.mPermissions.get(permission);
12542                if (bp != null) {
12543                    usedPermissions.add(permission);
12544                }
12545            }
12546        }
12547
12548        PermissionsState permissionsState = su.getPermissionsState();
12549        // Prune install permissions
12550        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12551        final int installPermCount = installPermStates.size();
12552        for (int i = installPermCount - 1; i >= 0;  i--) {
12553            PermissionState permissionState = installPermStates.get(i);
12554            if (!usedPermissions.contains(permissionState.getName())) {
12555                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12556                if (bp != null) {
12557                    permissionsState.revokeInstallPermission(bp);
12558                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12559                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12560                }
12561            }
12562        }
12563
12564        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12565
12566        // Prune runtime permissions
12567        for (int userId : allUserIds) {
12568            List<PermissionState> runtimePermStates = permissionsState
12569                    .getRuntimePermissionStates(userId);
12570            final int runtimePermCount = runtimePermStates.size();
12571            for (int i = runtimePermCount - 1; i >= 0; i--) {
12572                PermissionState permissionState = runtimePermStates.get(i);
12573                if (!usedPermissions.contains(permissionState.getName())) {
12574                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12575                    if (bp != null) {
12576                        permissionsState.revokeRuntimePermission(bp, userId);
12577                        permissionsState.updatePermissionFlags(bp, userId,
12578                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12579                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12580                                runtimePermissionChangedUserIds, userId);
12581                    }
12582                }
12583            }
12584        }
12585
12586        return runtimePermissionChangedUserIds;
12587    }
12588
12589    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12590            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12591            UserHandle user) {
12592        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12593
12594        String pkgName = newPackage.packageName;
12595        synchronized (mPackages) {
12596            //write settings. the installStatus will be incomplete at this stage.
12597            //note that the new package setting would have already been
12598            //added to mPackages. It hasn't been persisted yet.
12599            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12600            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12601            mSettings.writeLPr();
12602            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12603        }
12604
12605        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12606        synchronized (mPackages) {
12607            updatePermissionsLPw(newPackage.packageName, newPackage,
12608                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12609                            ? UPDATE_PERMISSIONS_ALL : 0));
12610            // For system-bundled packages, we assume that installing an upgraded version
12611            // of the package implies that the user actually wants to run that new code,
12612            // so we enable the package.
12613            PackageSetting ps = mSettings.mPackages.get(pkgName);
12614            if (ps != null) {
12615                if (isSystemApp(newPackage)) {
12616                    // NB: implicit assumption that system package upgrades apply to all users
12617                    if (DEBUG_INSTALL) {
12618                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12619                    }
12620                    if (res.origUsers != null) {
12621                        for (int userHandle : res.origUsers) {
12622                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12623                                    userHandle, installerPackageName);
12624                        }
12625                    }
12626                    // Also convey the prior install/uninstall state
12627                    if (allUsers != null && perUserInstalled != null) {
12628                        for (int i = 0; i < allUsers.length; i++) {
12629                            if (DEBUG_INSTALL) {
12630                                Slog.d(TAG, "    user " + allUsers[i]
12631                                        + " => " + perUserInstalled[i]);
12632                            }
12633                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12634                        }
12635                        // these install state changes will be persisted in the
12636                        // upcoming call to mSettings.writeLPr().
12637                    }
12638                }
12639                // It's implied that when a user requests installation, they want the app to be
12640                // installed and enabled.
12641                int userId = user.getIdentifier();
12642                if (userId != UserHandle.USER_ALL) {
12643                    ps.setInstalled(true, userId);
12644                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12645                }
12646            }
12647            res.name = pkgName;
12648            res.uid = newPackage.applicationInfo.uid;
12649            res.pkg = newPackage;
12650            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12651            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12652            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12653            //to update install status
12654            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12655            mSettings.writeLPr();
12656            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12657        }
12658
12659        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12660    }
12661
12662    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12663        try {
12664            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12665            installPackageLI(args, res);
12666        } finally {
12667            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12668        }
12669    }
12670
12671    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12672        final int installFlags = args.installFlags;
12673        final String installerPackageName = args.installerPackageName;
12674        final String volumeUuid = args.volumeUuid;
12675        final File tmpPackageFile = new File(args.getCodePath());
12676        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12677        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12678                || (args.volumeUuid != null));
12679        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12680        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12681        boolean replace = false;
12682        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12683        if (args.move != null) {
12684            // moving a complete application; perfom an initial scan on the new install location
12685            scanFlags |= SCAN_INITIAL;
12686        }
12687        // Result object to be returned
12688        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12689
12690        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12691
12692        // Sanity check
12693        if (ephemeral && (forwardLocked || onExternal)) {
12694            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12695                    + " external=" + onExternal);
12696            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12697            return;
12698        }
12699
12700        // Retrieve PackageSettings and parse package
12701        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12702                | PackageParser.PARSE_ENFORCE_CODE
12703                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12704                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12705                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0)
12706                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12707        PackageParser pp = new PackageParser();
12708        pp.setSeparateProcesses(mSeparateProcesses);
12709        pp.setDisplayMetrics(mMetrics);
12710
12711        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12712        final PackageParser.Package pkg;
12713        try {
12714            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12715        } catch (PackageParserException e) {
12716            res.setError("Failed parse during installPackageLI", e);
12717            return;
12718        } finally {
12719            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12720        }
12721
12722        // Mark that we have an install time CPU ABI override.
12723        pkg.cpuAbiOverride = args.abiOverride;
12724
12725        String pkgName = res.name = pkg.packageName;
12726        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12727            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12728                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12729                return;
12730            }
12731        }
12732
12733        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12734        try {
12735            pp.collectCertificates(pkg, parseFlags);
12736        } catch (PackageParserException e) {
12737            res.setError("Failed collect during installPackageLI", e);
12738            return;
12739        } finally {
12740            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12741        }
12742
12743        /* If the installer passed in a manifest digest, compare it now. */
12744        if (args.manifestDigest != null) {
12745            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12746            try {
12747                pp.collectManifestDigest(pkg);
12748            } catch (PackageParserException e) {
12749                res.setError("Failed collect during installPackageLI", e);
12750                return;
12751            } finally {
12752                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12753            }
12754
12755            if (DEBUG_INSTALL) {
12756                final String parsedManifest = pkg.manifestDigest == null ? "null"
12757                        : pkg.manifestDigest.toString();
12758                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12759                        + parsedManifest);
12760            }
12761
12762            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12763                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12764                return;
12765            }
12766        } else if (DEBUG_INSTALL) {
12767            final String parsedManifest = pkg.manifestDigest == null
12768                    ? "null" : pkg.manifestDigest.toString();
12769            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12770        }
12771
12772        // Get rid of all references to package scan path via parser.
12773        pp = null;
12774        String oldCodePath = null;
12775        boolean systemApp = false;
12776        synchronized (mPackages) {
12777            // Check if installing already existing package
12778            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12779                String oldName = mSettings.mRenamedPackages.get(pkgName);
12780                if (pkg.mOriginalPackages != null
12781                        && pkg.mOriginalPackages.contains(oldName)
12782                        && mPackages.containsKey(oldName)) {
12783                    // This package is derived from an original package,
12784                    // and this device has been updating from that original
12785                    // name.  We must continue using the original name, so
12786                    // rename the new package here.
12787                    pkg.setPackageName(oldName);
12788                    pkgName = pkg.packageName;
12789                    replace = true;
12790                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12791                            + oldName + " pkgName=" + pkgName);
12792                } else if (mPackages.containsKey(pkgName)) {
12793                    // This package, under its official name, already exists
12794                    // on the device; we should replace it.
12795                    replace = true;
12796                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12797                }
12798
12799                // Prevent apps opting out from runtime permissions
12800                if (replace) {
12801                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12802                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12803                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12804                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12805                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12806                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12807                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12808                                        + " doesn't support runtime permissions but the old"
12809                                        + " target SDK " + oldTargetSdk + " does.");
12810                        return;
12811                    }
12812                }
12813            }
12814
12815            PackageSetting ps = mSettings.mPackages.get(pkgName);
12816            if (ps != null) {
12817                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12818
12819                // Quick sanity check that we're signed correctly if updating;
12820                // we'll check this again later when scanning, but we want to
12821                // bail early here before tripping over redefined permissions.
12822                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12823                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12824                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12825                                + pkg.packageName + " upgrade keys do not match the "
12826                                + "previously installed version");
12827                        return;
12828                    }
12829                } else {
12830                    try {
12831                        verifySignaturesLP(ps, pkg);
12832                    } catch (PackageManagerException e) {
12833                        res.setError(e.error, e.getMessage());
12834                        return;
12835                    }
12836                }
12837
12838                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12839                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12840                    systemApp = (ps.pkg.applicationInfo.flags &
12841                            ApplicationInfo.FLAG_SYSTEM) != 0;
12842                }
12843                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12844            }
12845
12846            // Check whether the newly-scanned package wants to define an already-defined perm
12847            int N = pkg.permissions.size();
12848            for (int i = N-1; i >= 0; i--) {
12849                PackageParser.Permission perm = pkg.permissions.get(i);
12850                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12851                if (bp != null) {
12852                    // If the defining package is signed with our cert, it's okay.  This
12853                    // also includes the "updating the same package" case, of course.
12854                    // "updating same package" could also involve key-rotation.
12855                    final boolean sigsOk;
12856                    if (bp.sourcePackage.equals(pkg.packageName)
12857                            && (bp.packageSetting instanceof PackageSetting)
12858                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12859                                    scanFlags))) {
12860                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12861                    } else {
12862                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12863                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12864                    }
12865                    if (!sigsOk) {
12866                        // If the owning package is the system itself, we log but allow
12867                        // install to proceed; we fail the install on all other permission
12868                        // redefinitions.
12869                        if (!bp.sourcePackage.equals("android")) {
12870                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12871                                    + pkg.packageName + " attempting to redeclare permission "
12872                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12873                            res.origPermission = perm.info.name;
12874                            res.origPackage = bp.sourcePackage;
12875                            return;
12876                        } else {
12877                            Slog.w(TAG, "Package " + pkg.packageName
12878                                    + " attempting to redeclare system permission "
12879                                    + perm.info.name + "; ignoring new declaration");
12880                            pkg.permissions.remove(i);
12881                        }
12882                    }
12883                }
12884            }
12885
12886        }
12887
12888        if (systemApp) {
12889            if (onExternal) {
12890                // Abort update; system app can't be replaced with app on sdcard
12891                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12892                        "Cannot install updates to system apps on sdcard");
12893                return;
12894            } else if (ephemeral) {
12895                // Abort update; system app can't be replaced with an ephemeral app
12896                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12897                        "Cannot update a system app with an ephemeral app");
12898                return;
12899            }
12900        }
12901
12902        if (args.move != null) {
12903            // We did an in-place move, so dex is ready to roll
12904            scanFlags |= SCAN_NO_DEX;
12905            scanFlags |= SCAN_MOVE;
12906
12907            synchronized (mPackages) {
12908                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12909                if (ps == null) {
12910                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12911                            "Missing settings for moved package " + pkgName);
12912                }
12913
12914                // We moved the entire application as-is, so bring over the
12915                // previously derived ABI information.
12916                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12917                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12918            }
12919
12920        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12921            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12922            scanFlags |= SCAN_NO_DEX;
12923
12924            try {
12925                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12926                        true /* extract libs */);
12927            } catch (PackageManagerException pme) {
12928                Slog.e(TAG, "Error deriving application ABI", pme);
12929                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12930                return;
12931            }
12932        }
12933
12934        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12935            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12936            return;
12937        }
12938
12939        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12940
12941        if (replace) {
12942            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12943                    installerPackageName, volumeUuid, res);
12944        } else {
12945            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12946                    args.user, installerPackageName, volumeUuid, res);
12947        }
12948        synchronized (mPackages) {
12949            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12950            if (ps != null) {
12951                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12952            }
12953        }
12954    }
12955
12956    private void startIntentFilterVerifications(int userId, boolean replacing,
12957            PackageParser.Package pkg) {
12958        if (mIntentFilterVerifierComponent == null) {
12959            Slog.w(TAG, "No IntentFilter verification will not be done as "
12960                    + "there is no IntentFilterVerifier available!");
12961            return;
12962        }
12963
12964        final int verifierUid = getPackageUid(
12965                mIntentFilterVerifierComponent.getPackageName(),
12966                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12967
12968        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12969        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12970        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12971        mHandler.sendMessage(msg);
12972    }
12973
12974    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12975            PackageParser.Package pkg) {
12976        int size = pkg.activities.size();
12977        if (size == 0) {
12978            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12979                    "No activity, so no need to verify any IntentFilter!");
12980            return;
12981        }
12982
12983        final boolean hasDomainURLs = hasDomainURLs(pkg);
12984        if (!hasDomainURLs) {
12985            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12986                    "No domain URLs, so no need to verify any IntentFilter!");
12987            return;
12988        }
12989
12990        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12991                + " if any IntentFilter from the " + size
12992                + " Activities needs verification ...");
12993
12994        int count = 0;
12995        final String packageName = pkg.packageName;
12996
12997        synchronized (mPackages) {
12998            // If this is a new install and we see that we've already run verification for this
12999            // package, we have nothing to do: it means the state was restored from backup.
13000            if (!replacing) {
13001                IntentFilterVerificationInfo ivi =
13002                        mSettings.getIntentFilterVerificationLPr(packageName);
13003                if (ivi != null) {
13004                    if (DEBUG_DOMAIN_VERIFICATION) {
13005                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13006                                + ivi.getStatusString());
13007                    }
13008                    return;
13009                }
13010            }
13011
13012            // If any filters need to be verified, then all need to be.
13013            boolean needToVerify = false;
13014            for (PackageParser.Activity a : pkg.activities) {
13015                for (ActivityIntentInfo filter : a.intents) {
13016                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13017                        if (DEBUG_DOMAIN_VERIFICATION) {
13018                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13019                        }
13020                        needToVerify = true;
13021                        break;
13022                    }
13023                }
13024            }
13025
13026            if (needToVerify) {
13027                final int verificationId = mIntentFilterVerificationToken++;
13028                for (PackageParser.Activity a : pkg.activities) {
13029                    for (ActivityIntentInfo filter : a.intents) {
13030                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13031                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13032                                    "Verification needed for IntentFilter:" + filter.toString());
13033                            mIntentFilterVerifier.addOneIntentFilterVerification(
13034                                    verifierUid, userId, verificationId, filter, packageName);
13035                            count++;
13036                        }
13037                    }
13038                }
13039            }
13040        }
13041
13042        if (count > 0) {
13043            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13044                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13045                    +  " for userId:" + userId);
13046            mIntentFilterVerifier.startVerifications(userId);
13047        } else {
13048            if (DEBUG_DOMAIN_VERIFICATION) {
13049                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13050            }
13051        }
13052    }
13053
13054    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13055        final ComponentName cn  = filter.activity.getComponentName();
13056        final String packageName = cn.getPackageName();
13057
13058        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13059                packageName);
13060        if (ivi == null) {
13061            return true;
13062        }
13063        int status = ivi.getStatus();
13064        switch (status) {
13065            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13066            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13067                return true;
13068
13069            default:
13070                // Nothing to do
13071                return false;
13072        }
13073    }
13074
13075    private static boolean isMultiArch(PackageSetting ps) {
13076        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13077    }
13078
13079    private static boolean isMultiArch(ApplicationInfo info) {
13080        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13081    }
13082
13083    private static boolean isExternal(PackageParser.Package pkg) {
13084        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13085    }
13086
13087    private static boolean isExternal(PackageSetting ps) {
13088        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13089    }
13090
13091    private static boolean isExternal(ApplicationInfo info) {
13092        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13093    }
13094
13095    private static boolean isEphemeral(PackageParser.Package pkg) {
13096        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EPHEMERAL) != 0;
13097    }
13098
13099    private static boolean isEphemeral(PackageSetting ps) {
13100        return (ps.pkgFlags & ApplicationInfo.FLAG_EPHEMERAL) != 0;
13101    }
13102
13103    private static boolean isSystemApp(PackageParser.Package pkg) {
13104        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13105    }
13106
13107    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13108        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13109    }
13110
13111    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13112        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13113    }
13114
13115    private static boolean isSystemApp(PackageSetting ps) {
13116        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13117    }
13118
13119    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13120        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13121    }
13122
13123    private int packageFlagsToInstallFlags(PackageSetting ps) {
13124        int installFlags = 0;
13125        if (isEphemeral(ps)) {
13126            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13127        }
13128        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13129            // This existing package was an external ASEC install when we have
13130            // the external flag without a UUID
13131            installFlags |= PackageManager.INSTALL_EXTERNAL;
13132        }
13133        if (ps.isForwardLocked()) {
13134            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13135        }
13136        return installFlags;
13137    }
13138
13139    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13140        if (isExternal(pkg)) {
13141            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13142                return StorageManager.UUID_PRIMARY_PHYSICAL;
13143            } else {
13144                return pkg.volumeUuid;
13145            }
13146        } else {
13147            return StorageManager.UUID_PRIVATE_INTERNAL;
13148        }
13149    }
13150
13151    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13152        if (isExternal(pkg)) {
13153            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13154                return mSettings.getExternalVersion();
13155            } else {
13156                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13157            }
13158        } else {
13159            return mSettings.getInternalVersion();
13160        }
13161    }
13162
13163    private void deleteTempPackageFiles() {
13164        final FilenameFilter filter = new FilenameFilter() {
13165            public boolean accept(File dir, String name) {
13166                return name.startsWith("vmdl") && name.endsWith(".tmp");
13167            }
13168        };
13169        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13170            file.delete();
13171        }
13172    }
13173
13174    @Override
13175    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13176            int flags) {
13177        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13178                flags);
13179    }
13180
13181    @Override
13182    public void deletePackage(final String packageName,
13183            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13184        mContext.enforceCallingOrSelfPermission(
13185                android.Manifest.permission.DELETE_PACKAGES, null);
13186        Preconditions.checkNotNull(packageName);
13187        Preconditions.checkNotNull(observer);
13188        final int uid = Binder.getCallingUid();
13189        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13190        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13191        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13192            mContext.enforceCallingOrSelfPermission(
13193                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13194                    "deletePackage for user " + userId);
13195        }
13196
13197        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13198            try {
13199                observer.onPackageDeleted(packageName,
13200                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13201            } catch (RemoteException re) {
13202            }
13203            return;
13204        }
13205
13206        for (int currentUserId : users) {
13207            if (getBlockUninstallForUser(packageName, currentUserId)) {
13208                try {
13209                    observer.onPackageDeleted(packageName,
13210                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13211                } catch (RemoteException re) {
13212                }
13213                return;
13214            }
13215        }
13216
13217        if (DEBUG_REMOVE) {
13218            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13219        }
13220        // Queue up an async operation since the package deletion may take a little while.
13221        mHandler.post(new Runnable() {
13222            public void run() {
13223                mHandler.removeCallbacks(this);
13224                final int returnCode = deletePackageX(packageName, userId, flags);
13225                try {
13226                    observer.onPackageDeleted(packageName, returnCode, null);
13227                } catch (RemoteException e) {
13228                    Log.i(TAG, "Observer no longer exists.");
13229                } //end catch
13230            } //end run
13231        });
13232    }
13233
13234    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13235        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13236                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13237        try {
13238            if (dpm != null) {
13239                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13240                        /* callingUserOnly =*/ false);
13241                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13242                        : deviceOwnerComponentName.getPackageName();
13243                // Does the package contains the device owner?
13244                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13245                // this check is probably not needed, since DO should be registered as a device
13246                // admin on some user too. (Original bug for this: b/17657954)
13247                if (packageName.equals(deviceOwnerPackageName)) {
13248                    return true;
13249                }
13250                // Does it contain a device admin for any user?
13251                int[] users;
13252                if (userId == UserHandle.USER_ALL) {
13253                    users = sUserManager.getUserIds();
13254                } else {
13255                    users = new int[]{userId};
13256                }
13257                for (int i = 0; i < users.length; ++i) {
13258                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13259                        return true;
13260                    }
13261                }
13262            }
13263        } catch (RemoteException e) {
13264        }
13265        return false;
13266    }
13267
13268    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13269        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13270    }
13271
13272    /**
13273     *  This method is an internal method that could be get invoked either
13274     *  to delete an installed package or to clean up a failed installation.
13275     *  After deleting an installed package, a broadcast is sent to notify any
13276     *  listeners that the package has been installed. For cleaning up a failed
13277     *  installation, the broadcast is not necessary since the package's
13278     *  installation wouldn't have sent the initial broadcast either
13279     *  The key steps in deleting a package are
13280     *  deleting the package information in internal structures like mPackages,
13281     *  deleting the packages base directories through installd
13282     *  updating mSettings to reflect current status
13283     *  persisting settings for later use
13284     *  sending a broadcast if necessary
13285     */
13286    private int deletePackageX(String packageName, int userId, int flags) {
13287        final PackageRemovedInfo info = new PackageRemovedInfo();
13288        final boolean res;
13289
13290        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13291                ? UserHandle.ALL : new UserHandle(userId);
13292
13293        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13294            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13295            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13296        }
13297
13298        boolean removedForAllUsers = false;
13299        boolean systemUpdate = false;
13300
13301        // for the uninstall-updates case and restricted profiles, remember the per-
13302        // userhandle installed state
13303        int[] allUsers;
13304        boolean[] perUserInstalled;
13305        synchronized (mPackages) {
13306            PackageSetting ps = mSettings.mPackages.get(packageName);
13307            allUsers = sUserManager.getUserIds();
13308            perUserInstalled = new boolean[allUsers.length];
13309            for (int i = 0; i < allUsers.length; i++) {
13310                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13311            }
13312        }
13313
13314        synchronized (mInstallLock) {
13315            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13316            res = deletePackageLI(packageName, removeForUser,
13317                    true, allUsers, perUserInstalled,
13318                    flags | REMOVE_CHATTY, info, true);
13319            systemUpdate = info.isRemovedPackageSystemUpdate;
13320            if (res && !systemUpdate && mPackages.get(packageName) == null) {
13321                removedForAllUsers = true;
13322            }
13323            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13324                    + " removedForAllUsers=" + removedForAllUsers);
13325        }
13326
13327        if (res) {
13328            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13329
13330            // If the removed package was a system update, the old system package
13331            // was re-enabled; we need to broadcast this information
13332            if (systemUpdate) {
13333                Bundle extras = new Bundle(1);
13334                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13335                        ? info.removedAppId : info.uid);
13336                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13337
13338                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13339                        extras, 0, null, null, null);
13340                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13341                        extras, 0, null, null, null);
13342                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13343                        null, 0, packageName, null, null);
13344            }
13345        }
13346        // Force a gc here.
13347        Runtime.getRuntime().gc();
13348        // Delete the resources here after sending the broadcast to let
13349        // other processes clean up before deleting resources.
13350        if (info.args != null) {
13351            synchronized (mInstallLock) {
13352                info.args.doPostDeleteLI(true);
13353            }
13354        }
13355
13356        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13357    }
13358
13359    class PackageRemovedInfo {
13360        String removedPackage;
13361        int uid = -1;
13362        int removedAppId = -1;
13363        int[] removedUsers = null;
13364        boolean isRemovedPackageSystemUpdate = false;
13365        // Clean up resources deleted packages.
13366        InstallArgs args = null;
13367
13368        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13369            Bundle extras = new Bundle(1);
13370            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13371            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13372            if (replacing) {
13373                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13374            }
13375            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13376            if (removedPackage != null) {
13377                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13378                        extras, 0, null, null, removedUsers);
13379                if (fullRemove && !replacing) {
13380                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13381                            extras, 0, null, null, removedUsers);
13382                }
13383            }
13384            if (removedAppId >= 0) {
13385                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13386                        removedUsers);
13387            }
13388        }
13389    }
13390
13391    /*
13392     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13393     * flag is not set, the data directory is removed as well.
13394     * make sure this flag is set for partially installed apps. If not its meaningless to
13395     * delete a partially installed application.
13396     */
13397    private void removePackageDataLI(PackageSetting ps,
13398            int[] allUserHandles, boolean[] perUserInstalled,
13399            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13400        String packageName = ps.name;
13401        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13402        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13403        // Retrieve object to delete permissions for shared user later on
13404        final PackageSetting deletedPs;
13405        // reader
13406        synchronized (mPackages) {
13407            deletedPs = mSettings.mPackages.get(packageName);
13408            if (outInfo != null) {
13409                outInfo.removedPackage = packageName;
13410                outInfo.removedUsers = deletedPs != null
13411                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13412                        : null;
13413            }
13414        }
13415        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13416            removeDataDirsLI(ps.volumeUuid, packageName);
13417            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13418        }
13419        // writer
13420        synchronized (mPackages) {
13421            if (deletedPs != null) {
13422                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13423                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13424                    clearDefaultBrowserIfNeeded(packageName);
13425                    if (outInfo != null) {
13426                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13427                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13428                    }
13429                    updatePermissionsLPw(deletedPs.name, null, 0);
13430                    if (deletedPs.sharedUser != null) {
13431                        // Remove permissions associated with package. Since runtime
13432                        // permissions are per user we have to kill the removed package
13433                        // or packages running under the shared user of the removed
13434                        // package if revoking the permissions requested only by the removed
13435                        // package is successful and this causes a change in gids.
13436                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13437                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13438                                    userId);
13439                            if (userIdToKill == UserHandle.USER_ALL
13440                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13441                                // If gids changed for this user, kill all affected packages.
13442                                mHandler.post(new Runnable() {
13443                                    @Override
13444                                    public void run() {
13445                                        // This has to happen with no lock held.
13446                                        killApplication(deletedPs.name, deletedPs.appId,
13447                                                KILL_APP_REASON_GIDS_CHANGED);
13448                                    }
13449                                });
13450                                break;
13451                            }
13452                        }
13453                    }
13454                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13455                }
13456                // make sure to preserve per-user disabled state if this removal was just
13457                // a downgrade of a system app to the factory package
13458                if (allUserHandles != null && perUserInstalled != null) {
13459                    if (DEBUG_REMOVE) {
13460                        Slog.d(TAG, "Propagating install state across downgrade");
13461                    }
13462                    for (int i = 0; i < allUserHandles.length; i++) {
13463                        if (DEBUG_REMOVE) {
13464                            Slog.d(TAG, "    user " + allUserHandles[i]
13465                                    + " => " + perUserInstalled[i]);
13466                        }
13467                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13468                    }
13469                }
13470            }
13471            // can downgrade to reader
13472            if (writeSettings) {
13473                // Save settings now
13474                mSettings.writeLPr();
13475            }
13476        }
13477        if (outInfo != null) {
13478            // A user ID was deleted here. Go through all users and remove it
13479            // from KeyStore.
13480            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13481        }
13482    }
13483
13484    static boolean locationIsPrivileged(File path) {
13485        try {
13486            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13487                    .getCanonicalPath();
13488            return path.getCanonicalPath().startsWith(privilegedAppDir);
13489        } catch (IOException e) {
13490            Slog.e(TAG, "Unable to access code path " + path);
13491        }
13492        return false;
13493    }
13494
13495    /*
13496     * Tries to delete system package.
13497     */
13498    private boolean deleteSystemPackageLI(PackageSetting newPs,
13499            int[] allUserHandles, boolean[] perUserInstalled,
13500            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13501        final boolean applyUserRestrictions
13502                = (allUserHandles != null) && (perUserInstalled != null);
13503        PackageSetting disabledPs = null;
13504        // Confirm if the system package has been updated
13505        // An updated system app can be deleted. This will also have to restore
13506        // the system pkg from system partition
13507        // reader
13508        synchronized (mPackages) {
13509            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13510        }
13511        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13512                + " disabledPs=" + disabledPs);
13513        if (disabledPs == null) {
13514            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13515            return false;
13516        } else if (DEBUG_REMOVE) {
13517            Slog.d(TAG, "Deleting system pkg from data partition");
13518        }
13519        if (DEBUG_REMOVE) {
13520            if (applyUserRestrictions) {
13521                Slog.d(TAG, "Remembering install states:");
13522                for (int i = 0; i < allUserHandles.length; i++) {
13523                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13524                }
13525            }
13526        }
13527        // Delete the updated package
13528        outInfo.isRemovedPackageSystemUpdate = true;
13529        if (disabledPs.versionCode < newPs.versionCode) {
13530            // Delete data for downgrades
13531            flags &= ~PackageManager.DELETE_KEEP_DATA;
13532        } else {
13533            // Preserve data by setting flag
13534            flags |= PackageManager.DELETE_KEEP_DATA;
13535        }
13536        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13537                allUserHandles, perUserInstalled, outInfo, writeSettings);
13538        if (!ret) {
13539            return false;
13540        }
13541        // writer
13542        synchronized (mPackages) {
13543            // Reinstate the old system package
13544            mSettings.enableSystemPackageLPw(newPs.name);
13545            // Remove any native libraries from the upgraded package.
13546            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13547        }
13548        // Install the system package
13549        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13550        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13551        if (locationIsPrivileged(disabledPs.codePath)) {
13552            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13553        }
13554
13555        final PackageParser.Package newPkg;
13556        try {
13557            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13558        } catch (PackageManagerException e) {
13559            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13560            return false;
13561        }
13562
13563        // writer
13564        synchronized (mPackages) {
13565            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13566
13567            // Propagate the permissions state as we do not want to drop on the floor
13568            // runtime permissions. The update permissions method below will take
13569            // care of removing obsolete permissions and grant install permissions.
13570            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13571            updatePermissionsLPw(newPkg.packageName, newPkg,
13572                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13573
13574            if (applyUserRestrictions) {
13575                if (DEBUG_REMOVE) {
13576                    Slog.d(TAG, "Propagating install state across reinstall");
13577                }
13578                for (int i = 0; i < allUserHandles.length; i++) {
13579                    if (DEBUG_REMOVE) {
13580                        Slog.d(TAG, "    user " + allUserHandles[i]
13581                                + " => " + perUserInstalled[i]);
13582                    }
13583                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13584
13585                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13586                }
13587                // Regardless of writeSettings we need to ensure that this restriction
13588                // state propagation is persisted
13589                mSettings.writeAllUsersPackageRestrictionsLPr();
13590            }
13591            // can downgrade to reader here
13592            if (writeSettings) {
13593                mSettings.writeLPr();
13594            }
13595        }
13596        return true;
13597    }
13598
13599    private boolean deleteInstalledPackageLI(PackageSetting ps,
13600            boolean deleteCodeAndResources, int flags,
13601            int[] allUserHandles, boolean[] perUserInstalled,
13602            PackageRemovedInfo outInfo, boolean writeSettings) {
13603        if (outInfo != null) {
13604            outInfo.uid = ps.appId;
13605        }
13606
13607        // Delete package data from internal structures and also remove data if flag is set
13608        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13609
13610        // Delete application code and resources
13611        if (deleteCodeAndResources && (outInfo != null)) {
13612            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13613                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13614            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13615        }
13616        return true;
13617    }
13618
13619    @Override
13620    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13621            int userId) {
13622        mContext.enforceCallingOrSelfPermission(
13623                android.Manifest.permission.DELETE_PACKAGES, null);
13624        synchronized (mPackages) {
13625            PackageSetting ps = mSettings.mPackages.get(packageName);
13626            if (ps == null) {
13627                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13628                return false;
13629            }
13630            if (!ps.getInstalled(userId)) {
13631                // Can't block uninstall for an app that is not installed or enabled.
13632                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13633                return false;
13634            }
13635            ps.setBlockUninstall(blockUninstall, userId);
13636            mSettings.writePackageRestrictionsLPr(userId);
13637        }
13638        return true;
13639    }
13640
13641    @Override
13642    public boolean getBlockUninstallForUser(String packageName, int userId) {
13643        synchronized (mPackages) {
13644            PackageSetting ps = mSettings.mPackages.get(packageName);
13645            if (ps == null) {
13646                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13647                return false;
13648            }
13649            return ps.getBlockUninstall(userId);
13650        }
13651    }
13652
13653    /*
13654     * This method handles package deletion in general
13655     */
13656    private boolean deletePackageLI(String packageName, UserHandle user,
13657            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13658            int flags, PackageRemovedInfo outInfo,
13659            boolean writeSettings) {
13660        if (packageName == null) {
13661            Slog.w(TAG, "Attempt to delete null packageName.");
13662            return false;
13663        }
13664        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13665        PackageSetting ps;
13666        boolean dataOnly = false;
13667        int removeUser = -1;
13668        int appId = -1;
13669        synchronized (mPackages) {
13670            ps = mSettings.mPackages.get(packageName);
13671            if (ps == null) {
13672                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13673                return false;
13674            }
13675            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13676                    && user.getIdentifier() != UserHandle.USER_ALL) {
13677                // The caller is asking that the package only be deleted for a single
13678                // user.  To do this, we just mark its uninstalled state and delete
13679                // its data.  If this is a system app, we only allow this to happen if
13680                // they have set the special DELETE_SYSTEM_APP which requests different
13681                // semantics than normal for uninstalling system apps.
13682                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13683                final int userId = user.getIdentifier();
13684                ps.setUserState(userId,
13685                        COMPONENT_ENABLED_STATE_DEFAULT,
13686                        false, //installed
13687                        true,  //stopped
13688                        true,  //notLaunched
13689                        false, //hidden
13690                        null, null, null,
13691                        false, // blockUninstall
13692                        ps.readUserState(userId).domainVerificationStatus, 0);
13693                if (!isSystemApp(ps)) {
13694                    // Do not uninstall the APK if an app should be cached
13695                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13696                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13697                        // Other user still have this package installed, so all
13698                        // we need to do is clear this user's data and save that
13699                        // it is uninstalled.
13700                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13701                        removeUser = user.getIdentifier();
13702                        appId = ps.appId;
13703                        scheduleWritePackageRestrictionsLocked(removeUser);
13704                    } else {
13705                        // We need to set it back to 'installed' so the uninstall
13706                        // broadcasts will be sent correctly.
13707                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13708                        ps.setInstalled(true, user.getIdentifier());
13709                    }
13710                } else {
13711                    // This is a system app, so we assume that the
13712                    // other users still have this package installed, so all
13713                    // we need to do is clear this user's data and save that
13714                    // it is uninstalled.
13715                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13716                    removeUser = user.getIdentifier();
13717                    appId = ps.appId;
13718                    scheduleWritePackageRestrictionsLocked(removeUser);
13719                }
13720            }
13721        }
13722
13723        if (removeUser >= 0) {
13724            // From above, we determined that we are deleting this only
13725            // for a single user.  Continue the work here.
13726            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13727            if (outInfo != null) {
13728                outInfo.removedPackage = packageName;
13729                outInfo.removedAppId = appId;
13730                outInfo.removedUsers = new int[] {removeUser};
13731            }
13732            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13733            removeKeystoreDataIfNeeded(removeUser, appId);
13734            schedulePackageCleaning(packageName, removeUser, false);
13735            synchronized (mPackages) {
13736                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13737                    scheduleWritePackageRestrictionsLocked(removeUser);
13738                }
13739                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13740            }
13741            return true;
13742        }
13743
13744        if (dataOnly) {
13745            // Delete application data first
13746            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13747            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13748            return true;
13749        }
13750
13751        boolean ret = false;
13752        if (isSystemApp(ps)) {
13753            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13754            // When an updated system application is deleted we delete the existing resources as well and
13755            // fall back to existing code in system partition
13756            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13757                    flags, outInfo, writeSettings);
13758        } else {
13759            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13760            // Kill application pre-emptively especially for apps on sd.
13761            killApplication(packageName, ps.appId, "uninstall pkg");
13762            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13763                    allUserHandles, perUserInstalled,
13764                    outInfo, writeSettings);
13765        }
13766
13767        return ret;
13768    }
13769
13770    private final class ClearStorageConnection implements ServiceConnection {
13771        IMediaContainerService mContainerService;
13772
13773        @Override
13774        public void onServiceConnected(ComponentName name, IBinder service) {
13775            synchronized (this) {
13776                mContainerService = IMediaContainerService.Stub.asInterface(service);
13777                notifyAll();
13778            }
13779        }
13780
13781        @Override
13782        public void onServiceDisconnected(ComponentName name) {
13783        }
13784    }
13785
13786    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13787        final boolean mounted;
13788        if (Environment.isExternalStorageEmulated()) {
13789            mounted = true;
13790        } else {
13791            final String status = Environment.getExternalStorageState();
13792
13793            mounted = status.equals(Environment.MEDIA_MOUNTED)
13794                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13795        }
13796
13797        if (!mounted) {
13798            return;
13799        }
13800
13801        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13802        int[] users;
13803        if (userId == UserHandle.USER_ALL) {
13804            users = sUserManager.getUserIds();
13805        } else {
13806            users = new int[] { userId };
13807        }
13808        final ClearStorageConnection conn = new ClearStorageConnection();
13809        if (mContext.bindServiceAsUser(
13810                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13811            try {
13812                for (int curUser : users) {
13813                    long timeout = SystemClock.uptimeMillis() + 5000;
13814                    synchronized (conn) {
13815                        long now = SystemClock.uptimeMillis();
13816                        while (conn.mContainerService == null && now < timeout) {
13817                            try {
13818                                conn.wait(timeout - now);
13819                            } catch (InterruptedException e) {
13820                            }
13821                        }
13822                    }
13823                    if (conn.mContainerService == null) {
13824                        return;
13825                    }
13826
13827                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13828                    clearDirectory(conn.mContainerService,
13829                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13830                    if (allData) {
13831                        clearDirectory(conn.mContainerService,
13832                                userEnv.buildExternalStorageAppDataDirs(packageName));
13833                        clearDirectory(conn.mContainerService,
13834                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13835                    }
13836                }
13837            } finally {
13838                mContext.unbindService(conn);
13839            }
13840        }
13841    }
13842
13843    @Override
13844    public void clearApplicationUserData(final String packageName,
13845            final IPackageDataObserver observer, final int userId) {
13846        mContext.enforceCallingOrSelfPermission(
13847                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13848        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13849        // Queue up an async operation since the package deletion may take a little while.
13850        mHandler.post(new Runnable() {
13851            public void run() {
13852                mHandler.removeCallbacks(this);
13853                final boolean succeeded;
13854                synchronized (mInstallLock) {
13855                    succeeded = clearApplicationUserDataLI(packageName, userId);
13856                }
13857                clearExternalStorageDataSync(packageName, userId, true);
13858                if (succeeded) {
13859                    // invoke DeviceStorageMonitor's update method to clear any notifications
13860                    DeviceStorageMonitorInternal
13861                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13862                    if (dsm != null) {
13863                        dsm.checkMemory();
13864                    }
13865                }
13866                if(observer != null) {
13867                    try {
13868                        observer.onRemoveCompleted(packageName, succeeded);
13869                    } catch (RemoteException e) {
13870                        Log.i(TAG, "Observer no longer exists.");
13871                    }
13872                } //end if observer
13873            } //end run
13874        });
13875    }
13876
13877    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13878        if (packageName == null) {
13879            Slog.w(TAG, "Attempt to delete null packageName.");
13880            return false;
13881        }
13882
13883        // Try finding details about the requested package
13884        PackageParser.Package pkg;
13885        synchronized (mPackages) {
13886            pkg = mPackages.get(packageName);
13887            if (pkg == null) {
13888                final PackageSetting ps = mSettings.mPackages.get(packageName);
13889                if (ps != null) {
13890                    pkg = ps.pkg;
13891                }
13892            }
13893
13894            if (pkg == null) {
13895                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13896                return false;
13897            }
13898
13899            PackageSetting ps = (PackageSetting) pkg.mExtras;
13900            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13901        }
13902
13903        // Always delete data directories for package, even if we found no other
13904        // record of app. This helps users recover from UID mismatches without
13905        // resorting to a full data wipe.
13906        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13907        if (retCode < 0) {
13908            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13909            return false;
13910        }
13911
13912        final int appId = pkg.applicationInfo.uid;
13913        removeKeystoreDataIfNeeded(userId, appId);
13914
13915        // Create a native library symlink only if we have native libraries
13916        // and if the native libraries are 32 bit libraries. We do not provide
13917        // this symlink for 64 bit libraries.
13918        if (pkg.applicationInfo.primaryCpuAbi != null &&
13919                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13920            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13921            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13922                    nativeLibPath, userId) < 0) {
13923                Slog.w(TAG, "Failed linking native library dir");
13924                return false;
13925            }
13926        }
13927
13928        return true;
13929    }
13930
13931    /**
13932     * Reverts user permission state changes (permissions and flags) in
13933     * all packages for a given user.
13934     *
13935     * @param userId The device user for which to do a reset.
13936     */
13937    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13938        final int packageCount = mPackages.size();
13939        for (int i = 0; i < packageCount; i++) {
13940            PackageParser.Package pkg = mPackages.valueAt(i);
13941            PackageSetting ps = (PackageSetting) pkg.mExtras;
13942            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13943        }
13944    }
13945
13946    /**
13947     * Reverts user permission state changes (permissions and flags).
13948     *
13949     * @param ps The package for which to reset.
13950     * @param userId The device user for which to do a reset.
13951     */
13952    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13953            final PackageSetting ps, final int userId) {
13954        if (ps.pkg == null) {
13955            return;
13956        }
13957
13958        // These are flags that can change base on user actions.
13959        final int userSettableMask = FLAG_PERMISSION_USER_SET
13960                | FLAG_PERMISSION_USER_FIXED
13961                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
13962                | FLAG_PERMISSION_REVIEW_REQUIRED;
13963
13964        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13965                | FLAG_PERMISSION_POLICY_FIXED;
13966
13967        boolean writeInstallPermissions = false;
13968        boolean writeRuntimePermissions = false;
13969
13970        final int permissionCount = ps.pkg.requestedPermissions.size();
13971        for (int i = 0; i < permissionCount; i++) {
13972            String permission = ps.pkg.requestedPermissions.get(i);
13973
13974            BasePermission bp = mSettings.mPermissions.get(permission);
13975            if (bp == null) {
13976                continue;
13977            }
13978
13979            // If shared user we just reset the state to which only this app contributed.
13980            if (ps.sharedUser != null) {
13981                boolean used = false;
13982                final int packageCount = ps.sharedUser.packages.size();
13983                for (int j = 0; j < packageCount; j++) {
13984                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13985                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13986                            && pkg.pkg.requestedPermissions.contains(permission)) {
13987                        used = true;
13988                        break;
13989                    }
13990                }
13991                if (used) {
13992                    continue;
13993                }
13994            }
13995
13996            PermissionsState permissionsState = ps.getPermissionsState();
13997
13998            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13999
14000            // Always clear the user settable flags.
14001            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14002                    bp.name) != null;
14003            // If permission review is enabled and this is a legacy app, mark the
14004            // permission as requiring a review as this is the initial state.
14005            int flags = 0;
14006            if (Build.PERMISSIONS_REVIEW_REQUIRED
14007                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14008                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14009            }
14010            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14011                if (hasInstallState) {
14012                    writeInstallPermissions = true;
14013                } else {
14014                    writeRuntimePermissions = true;
14015                }
14016            }
14017
14018            // Below is only runtime permission handling.
14019            if (!bp.isRuntime()) {
14020                continue;
14021            }
14022
14023            // Never clobber system or policy.
14024            if ((oldFlags & policyOrSystemFlags) != 0) {
14025                continue;
14026            }
14027
14028            // If this permission was granted by default, make sure it is.
14029            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14030                if (permissionsState.grantRuntimePermission(bp, userId)
14031                        != PERMISSION_OPERATION_FAILURE) {
14032                    writeRuntimePermissions = true;
14033                }
14034            // If permission review is enabled the permissions for a legacy apps
14035            // are represented as constantly granted runtime ones, so don't revoke.
14036            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14037                // Otherwise, reset the permission.
14038                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14039                switch (revokeResult) {
14040                    case PERMISSION_OPERATION_SUCCESS: {
14041                        writeRuntimePermissions = true;
14042                    } break;
14043
14044                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14045                        writeRuntimePermissions = true;
14046                        final int appId = ps.appId;
14047                        mHandler.post(new Runnable() {
14048                            @Override
14049                            public void run() {
14050                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14051                            }
14052                        });
14053                    } break;
14054                }
14055            }
14056        }
14057
14058        // Synchronously write as we are taking permissions away.
14059        if (writeRuntimePermissions) {
14060            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14061        }
14062
14063        // Synchronously write as we are taking permissions away.
14064        if (writeInstallPermissions) {
14065            mSettings.writeLPr();
14066        }
14067    }
14068
14069    /**
14070     * Remove entries from the keystore daemon. Will only remove it if the
14071     * {@code appId} is valid.
14072     */
14073    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14074        if (appId < 0) {
14075            return;
14076        }
14077
14078        final KeyStore keyStore = KeyStore.getInstance();
14079        if (keyStore != null) {
14080            if (userId == UserHandle.USER_ALL) {
14081                for (final int individual : sUserManager.getUserIds()) {
14082                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14083                }
14084            } else {
14085                keyStore.clearUid(UserHandle.getUid(userId, appId));
14086            }
14087        } else {
14088            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14089        }
14090    }
14091
14092    @Override
14093    public void deleteApplicationCacheFiles(final String packageName,
14094            final IPackageDataObserver observer) {
14095        mContext.enforceCallingOrSelfPermission(
14096                android.Manifest.permission.DELETE_CACHE_FILES, null);
14097        // Queue up an async operation since the package deletion may take a little while.
14098        final int userId = UserHandle.getCallingUserId();
14099        mHandler.post(new Runnable() {
14100            public void run() {
14101                mHandler.removeCallbacks(this);
14102                final boolean succeded;
14103                synchronized (mInstallLock) {
14104                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14105                }
14106                clearExternalStorageDataSync(packageName, userId, false);
14107                if (observer != null) {
14108                    try {
14109                        observer.onRemoveCompleted(packageName, succeded);
14110                    } catch (RemoteException e) {
14111                        Log.i(TAG, "Observer no longer exists.");
14112                    }
14113                } //end if observer
14114            } //end run
14115        });
14116    }
14117
14118    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14119        if (packageName == null) {
14120            Slog.w(TAG, "Attempt to delete null packageName.");
14121            return false;
14122        }
14123        PackageParser.Package p;
14124        synchronized (mPackages) {
14125            p = mPackages.get(packageName);
14126        }
14127        if (p == null) {
14128            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14129            return false;
14130        }
14131        final ApplicationInfo applicationInfo = p.applicationInfo;
14132        if (applicationInfo == null) {
14133            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14134            return false;
14135        }
14136        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14137        if (retCode < 0) {
14138            Slog.w(TAG, "Couldn't remove cache files for package: "
14139                       + packageName + " u" + userId);
14140            return false;
14141        }
14142        return true;
14143    }
14144
14145    @Override
14146    public void getPackageSizeInfo(final String packageName, int userHandle,
14147            final IPackageStatsObserver observer) {
14148        mContext.enforceCallingOrSelfPermission(
14149                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14150        if (packageName == null) {
14151            throw new IllegalArgumentException("Attempt to get size of null packageName");
14152        }
14153
14154        PackageStats stats = new PackageStats(packageName, userHandle);
14155
14156        /*
14157         * Queue up an async operation since the package measurement may take a
14158         * little while.
14159         */
14160        Message msg = mHandler.obtainMessage(INIT_COPY);
14161        msg.obj = new MeasureParams(stats, observer);
14162        mHandler.sendMessage(msg);
14163    }
14164
14165    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14166            PackageStats pStats) {
14167        if (packageName == null) {
14168            Slog.w(TAG, "Attempt to get size of null packageName.");
14169            return false;
14170        }
14171        PackageParser.Package p;
14172        boolean dataOnly = false;
14173        String libDirRoot = null;
14174        String asecPath = null;
14175        PackageSetting ps = null;
14176        synchronized (mPackages) {
14177            p = mPackages.get(packageName);
14178            ps = mSettings.mPackages.get(packageName);
14179            if(p == null) {
14180                dataOnly = true;
14181                if((ps == null) || (ps.pkg == null)) {
14182                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14183                    return false;
14184                }
14185                p = ps.pkg;
14186            }
14187            if (ps != null) {
14188                libDirRoot = ps.legacyNativeLibraryPathString;
14189            }
14190            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14191                final long token = Binder.clearCallingIdentity();
14192                try {
14193                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14194                    if (secureContainerId != null) {
14195                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14196                    }
14197                } finally {
14198                    Binder.restoreCallingIdentity(token);
14199                }
14200            }
14201        }
14202        String publicSrcDir = null;
14203        if(!dataOnly) {
14204            final ApplicationInfo applicationInfo = p.applicationInfo;
14205            if (applicationInfo == null) {
14206                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14207                return false;
14208            }
14209            if (p.isForwardLocked()) {
14210                publicSrcDir = applicationInfo.getBaseResourcePath();
14211            }
14212        }
14213        // TODO: extend to measure size of split APKs
14214        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14215        // not just the first level.
14216        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14217        // just the primary.
14218        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14219
14220        String apkPath;
14221        File packageDir = new File(p.codePath);
14222
14223        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14224            apkPath = packageDir.getAbsolutePath();
14225            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14226            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14227                libDirRoot = null;
14228            }
14229        } else {
14230            apkPath = p.baseCodePath;
14231        }
14232
14233        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14234                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14235        if (res < 0) {
14236            return false;
14237        }
14238
14239        // Fix-up for forward-locked applications in ASEC containers.
14240        if (!isExternal(p)) {
14241            pStats.codeSize += pStats.externalCodeSize;
14242            pStats.externalCodeSize = 0L;
14243        }
14244
14245        return true;
14246    }
14247
14248
14249    @Override
14250    public void addPackageToPreferred(String packageName) {
14251        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14252    }
14253
14254    @Override
14255    public void removePackageFromPreferred(String packageName) {
14256        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14257    }
14258
14259    @Override
14260    public List<PackageInfo> getPreferredPackages(int flags) {
14261        return new ArrayList<PackageInfo>();
14262    }
14263
14264    private int getUidTargetSdkVersionLockedLPr(int uid) {
14265        Object obj = mSettings.getUserIdLPr(uid);
14266        if (obj instanceof SharedUserSetting) {
14267            final SharedUserSetting sus = (SharedUserSetting) obj;
14268            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14269            final Iterator<PackageSetting> it = sus.packages.iterator();
14270            while (it.hasNext()) {
14271                final PackageSetting ps = it.next();
14272                if (ps.pkg != null) {
14273                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14274                    if (v < vers) vers = v;
14275                }
14276            }
14277            return vers;
14278        } else if (obj instanceof PackageSetting) {
14279            final PackageSetting ps = (PackageSetting) obj;
14280            if (ps.pkg != null) {
14281                return ps.pkg.applicationInfo.targetSdkVersion;
14282            }
14283        }
14284        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14285    }
14286
14287    @Override
14288    public void addPreferredActivity(IntentFilter filter, int match,
14289            ComponentName[] set, ComponentName activity, int userId) {
14290        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14291                "Adding preferred");
14292    }
14293
14294    private void addPreferredActivityInternal(IntentFilter filter, int match,
14295            ComponentName[] set, ComponentName activity, boolean always, int userId,
14296            String opname) {
14297        // writer
14298        int callingUid = Binder.getCallingUid();
14299        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14300        if (filter.countActions() == 0) {
14301            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14302            return;
14303        }
14304        synchronized (mPackages) {
14305            if (mContext.checkCallingOrSelfPermission(
14306                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14307                    != PackageManager.PERMISSION_GRANTED) {
14308                if (getUidTargetSdkVersionLockedLPr(callingUid)
14309                        < Build.VERSION_CODES.FROYO) {
14310                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14311                            + callingUid);
14312                    return;
14313                }
14314                mContext.enforceCallingOrSelfPermission(
14315                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14316            }
14317
14318            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14319            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14320                    + userId + ":");
14321            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14322            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14323            scheduleWritePackageRestrictionsLocked(userId);
14324        }
14325    }
14326
14327    @Override
14328    public void replacePreferredActivity(IntentFilter filter, int match,
14329            ComponentName[] set, ComponentName activity, int userId) {
14330        if (filter.countActions() != 1) {
14331            throw new IllegalArgumentException(
14332                    "replacePreferredActivity expects filter to have only 1 action.");
14333        }
14334        if (filter.countDataAuthorities() != 0
14335                || filter.countDataPaths() != 0
14336                || filter.countDataSchemes() > 1
14337                || filter.countDataTypes() != 0) {
14338            throw new IllegalArgumentException(
14339                    "replacePreferredActivity expects filter to have no data authorities, " +
14340                    "paths, or types; and at most one scheme.");
14341        }
14342
14343        final int callingUid = Binder.getCallingUid();
14344        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14345        synchronized (mPackages) {
14346            if (mContext.checkCallingOrSelfPermission(
14347                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14348                    != PackageManager.PERMISSION_GRANTED) {
14349                if (getUidTargetSdkVersionLockedLPr(callingUid)
14350                        < Build.VERSION_CODES.FROYO) {
14351                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14352                            + Binder.getCallingUid());
14353                    return;
14354                }
14355                mContext.enforceCallingOrSelfPermission(
14356                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14357            }
14358
14359            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14360            if (pir != null) {
14361                // Get all of the existing entries that exactly match this filter.
14362                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14363                if (existing != null && existing.size() == 1) {
14364                    PreferredActivity cur = existing.get(0);
14365                    if (DEBUG_PREFERRED) {
14366                        Slog.i(TAG, "Checking replace of preferred:");
14367                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14368                        if (!cur.mPref.mAlways) {
14369                            Slog.i(TAG, "  -- CUR; not mAlways!");
14370                        } else {
14371                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14372                            Slog.i(TAG, "  -- CUR: mSet="
14373                                    + Arrays.toString(cur.mPref.mSetComponents));
14374                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14375                            Slog.i(TAG, "  -- NEW: mMatch="
14376                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14377                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14378                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14379                        }
14380                    }
14381                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14382                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14383                            && cur.mPref.sameSet(set)) {
14384                        // Setting the preferred activity to what it happens to be already
14385                        if (DEBUG_PREFERRED) {
14386                            Slog.i(TAG, "Replacing with same preferred activity "
14387                                    + cur.mPref.mShortComponent + " for user "
14388                                    + userId + ":");
14389                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14390                        }
14391                        return;
14392                    }
14393                }
14394
14395                if (existing != null) {
14396                    if (DEBUG_PREFERRED) {
14397                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14398                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14399                    }
14400                    for (int i = 0; i < existing.size(); i++) {
14401                        PreferredActivity pa = existing.get(i);
14402                        if (DEBUG_PREFERRED) {
14403                            Slog.i(TAG, "Removing existing preferred activity "
14404                                    + pa.mPref.mComponent + ":");
14405                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14406                        }
14407                        pir.removeFilter(pa);
14408                    }
14409                }
14410            }
14411            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14412                    "Replacing preferred");
14413        }
14414    }
14415
14416    @Override
14417    public void clearPackagePreferredActivities(String packageName) {
14418        final int uid = Binder.getCallingUid();
14419        // writer
14420        synchronized (mPackages) {
14421            PackageParser.Package pkg = mPackages.get(packageName);
14422            if (pkg == null || pkg.applicationInfo.uid != uid) {
14423                if (mContext.checkCallingOrSelfPermission(
14424                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14425                        != PackageManager.PERMISSION_GRANTED) {
14426                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14427                            < Build.VERSION_CODES.FROYO) {
14428                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14429                                + Binder.getCallingUid());
14430                        return;
14431                    }
14432                    mContext.enforceCallingOrSelfPermission(
14433                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14434                }
14435            }
14436
14437            int user = UserHandle.getCallingUserId();
14438            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14439                scheduleWritePackageRestrictionsLocked(user);
14440            }
14441        }
14442    }
14443
14444    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14445    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14446        ArrayList<PreferredActivity> removed = null;
14447        boolean changed = false;
14448        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14449            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14450            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14451            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14452                continue;
14453            }
14454            Iterator<PreferredActivity> it = pir.filterIterator();
14455            while (it.hasNext()) {
14456                PreferredActivity pa = it.next();
14457                // Mark entry for removal only if it matches the package name
14458                // and the entry is of type "always".
14459                if (packageName == null ||
14460                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14461                                && pa.mPref.mAlways)) {
14462                    if (removed == null) {
14463                        removed = new ArrayList<PreferredActivity>();
14464                    }
14465                    removed.add(pa);
14466                }
14467            }
14468            if (removed != null) {
14469                for (int j=0; j<removed.size(); j++) {
14470                    PreferredActivity pa = removed.get(j);
14471                    pir.removeFilter(pa);
14472                }
14473                changed = true;
14474            }
14475        }
14476        return changed;
14477    }
14478
14479    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14480    private void clearIntentFilterVerificationsLPw(int userId) {
14481        final int packageCount = mPackages.size();
14482        for (int i = 0; i < packageCount; i++) {
14483            PackageParser.Package pkg = mPackages.valueAt(i);
14484            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14485        }
14486    }
14487
14488    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14489    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14490        if (userId == UserHandle.USER_ALL) {
14491            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14492                    sUserManager.getUserIds())) {
14493                for (int oneUserId : sUserManager.getUserIds()) {
14494                    scheduleWritePackageRestrictionsLocked(oneUserId);
14495                }
14496            }
14497        } else {
14498            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14499                scheduleWritePackageRestrictionsLocked(userId);
14500            }
14501        }
14502    }
14503
14504    void clearDefaultBrowserIfNeeded(String packageName) {
14505        for (int oneUserId : sUserManager.getUserIds()) {
14506            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14507            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14508            if (packageName.equals(defaultBrowserPackageName)) {
14509                setDefaultBrowserPackageName(null, oneUserId);
14510            }
14511        }
14512    }
14513
14514    @Override
14515    public void resetApplicationPreferences(int userId) {
14516        mContext.enforceCallingOrSelfPermission(
14517                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14518        // writer
14519        synchronized (mPackages) {
14520            final long identity = Binder.clearCallingIdentity();
14521            try {
14522                clearPackagePreferredActivitiesLPw(null, userId);
14523                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14524                // TODO: We have to reset the default SMS and Phone. This requires
14525                // significant refactoring to keep all default apps in the package
14526                // manager (cleaner but more work) or have the services provide
14527                // callbacks to the package manager to request a default app reset.
14528                applyFactoryDefaultBrowserLPw(userId);
14529                clearIntentFilterVerificationsLPw(userId);
14530                primeDomainVerificationsLPw(userId);
14531                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14532                scheduleWritePackageRestrictionsLocked(userId);
14533            } finally {
14534                Binder.restoreCallingIdentity(identity);
14535            }
14536        }
14537    }
14538
14539    @Override
14540    public int getPreferredActivities(List<IntentFilter> outFilters,
14541            List<ComponentName> outActivities, String packageName) {
14542
14543        int num = 0;
14544        final int userId = UserHandle.getCallingUserId();
14545        // reader
14546        synchronized (mPackages) {
14547            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14548            if (pir != null) {
14549                final Iterator<PreferredActivity> it = pir.filterIterator();
14550                while (it.hasNext()) {
14551                    final PreferredActivity pa = it.next();
14552                    if (packageName == null
14553                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14554                                    && pa.mPref.mAlways)) {
14555                        if (outFilters != null) {
14556                            outFilters.add(new IntentFilter(pa));
14557                        }
14558                        if (outActivities != null) {
14559                            outActivities.add(pa.mPref.mComponent);
14560                        }
14561                    }
14562                }
14563            }
14564        }
14565
14566        return num;
14567    }
14568
14569    @Override
14570    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14571            int userId) {
14572        int callingUid = Binder.getCallingUid();
14573        if (callingUid != Process.SYSTEM_UID) {
14574            throw new SecurityException(
14575                    "addPersistentPreferredActivity can only be run by the system");
14576        }
14577        if (filter.countActions() == 0) {
14578            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14579            return;
14580        }
14581        synchronized (mPackages) {
14582            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14583                    " :");
14584            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14585            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14586                    new PersistentPreferredActivity(filter, activity));
14587            scheduleWritePackageRestrictionsLocked(userId);
14588        }
14589    }
14590
14591    @Override
14592    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14593        int callingUid = Binder.getCallingUid();
14594        if (callingUid != Process.SYSTEM_UID) {
14595            throw new SecurityException(
14596                    "clearPackagePersistentPreferredActivities can only be run by the system");
14597        }
14598        ArrayList<PersistentPreferredActivity> removed = null;
14599        boolean changed = false;
14600        synchronized (mPackages) {
14601            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14602                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14603                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14604                        .valueAt(i);
14605                if (userId != thisUserId) {
14606                    continue;
14607                }
14608                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14609                while (it.hasNext()) {
14610                    PersistentPreferredActivity ppa = it.next();
14611                    // Mark entry for removal only if it matches the package name.
14612                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14613                        if (removed == null) {
14614                            removed = new ArrayList<PersistentPreferredActivity>();
14615                        }
14616                        removed.add(ppa);
14617                    }
14618                }
14619                if (removed != null) {
14620                    for (int j=0; j<removed.size(); j++) {
14621                        PersistentPreferredActivity ppa = removed.get(j);
14622                        ppir.removeFilter(ppa);
14623                    }
14624                    changed = true;
14625                }
14626            }
14627
14628            if (changed) {
14629                scheduleWritePackageRestrictionsLocked(userId);
14630            }
14631        }
14632    }
14633
14634    /**
14635     * Common machinery for picking apart a restored XML blob and passing
14636     * it to a caller-supplied functor to be applied to the running system.
14637     */
14638    private void restoreFromXml(XmlPullParser parser, int userId,
14639            String expectedStartTag, BlobXmlRestorer functor)
14640            throws IOException, XmlPullParserException {
14641        int type;
14642        while ((type = parser.next()) != XmlPullParser.START_TAG
14643                && type != XmlPullParser.END_DOCUMENT) {
14644        }
14645        if (type != XmlPullParser.START_TAG) {
14646            // oops didn't find a start tag?!
14647            if (DEBUG_BACKUP) {
14648                Slog.e(TAG, "Didn't find start tag during restore");
14649            }
14650            return;
14651        }
14652
14653        // this is supposed to be TAG_PREFERRED_BACKUP
14654        if (!expectedStartTag.equals(parser.getName())) {
14655            if (DEBUG_BACKUP) {
14656                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14657            }
14658            return;
14659        }
14660
14661        // skip interfering stuff, then we're aligned with the backing implementation
14662        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14663        functor.apply(parser, userId);
14664    }
14665
14666    private interface BlobXmlRestorer {
14667        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14668    }
14669
14670    /**
14671     * Non-Binder method, support for the backup/restore mechanism: write the
14672     * full set of preferred activities in its canonical XML format.  Returns the
14673     * XML output as a byte array, or null if there is none.
14674     */
14675    @Override
14676    public byte[] getPreferredActivityBackup(int userId) {
14677        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14678            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14679        }
14680
14681        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14682        try {
14683            final XmlSerializer serializer = new FastXmlSerializer();
14684            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14685            serializer.startDocument(null, true);
14686            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14687
14688            synchronized (mPackages) {
14689                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14690            }
14691
14692            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14693            serializer.endDocument();
14694            serializer.flush();
14695        } catch (Exception e) {
14696            if (DEBUG_BACKUP) {
14697                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14698            }
14699            return null;
14700        }
14701
14702        return dataStream.toByteArray();
14703    }
14704
14705    @Override
14706    public void restorePreferredActivities(byte[] backup, int userId) {
14707        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14708            throw new SecurityException("Only the system may call restorePreferredActivities()");
14709        }
14710
14711        try {
14712            final XmlPullParser parser = Xml.newPullParser();
14713            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14714            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14715                    new BlobXmlRestorer() {
14716                        @Override
14717                        public void apply(XmlPullParser parser, int userId)
14718                                throws XmlPullParserException, IOException {
14719                            synchronized (mPackages) {
14720                                mSettings.readPreferredActivitiesLPw(parser, userId);
14721                            }
14722                        }
14723                    } );
14724        } catch (Exception e) {
14725            if (DEBUG_BACKUP) {
14726                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14727            }
14728        }
14729    }
14730
14731    /**
14732     * Non-Binder method, support for the backup/restore mechanism: write the
14733     * default browser (etc) settings in its canonical XML format.  Returns the default
14734     * browser XML representation as a byte array, or null if there is none.
14735     */
14736    @Override
14737    public byte[] getDefaultAppsBackup(int userId) {
14738        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14739            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14740        }
14741
14742        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14743        try {
14744            final XmlSerializer serializer = new FastXmlSerializer();
14745            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14746            serializer.startDocument(null, true);
14747            serializer.startTag(null, TAG_DEFAULT_APPS);
14748
14749            synchronized (mPackages) {
14750                mSettings.writeDefaultAppsLPr(serializer, userId);
14751            }
14752
14753            serializer.endTag(null, TAG_DEFAULT_APPS);
14754            serializer.endDocument();
14755            serializer.flush();
14756        } catch (Exception e) {
14757            if (DEBUG_BACKUP) {
14758                Slog.e(TAG, "Unable to write default apps for backup", e);
14759            }
14760            return null;
14761        }
14762
14763        return dataStream.toByteArray();
14764    }
14765
14766    @Override
14767    public void restoreDefaultApps(byte[] backup, int userId) {
14768        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14769            throw new SecurityException("Only the system may call restoreDefaultApps()");
14770        }
14771
14772        try {
14773            final XmlPullParser parser = Xml.newPullParser();
14774            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14775            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14776                    new BlobXmlRestorer() {
14777                        @Override
14778                        public void apply(XmlPullParser parser, int userId)
14779                                throws XmlPullParserException, IOException {
14780                            synchronized (mPackages) {
14781                                mSettings.readDefaultAppsLPw(parser, userId);
14782                            }
14783                        }
14784                    } );
14785        } catch (Exception e) {
14786            if (DEBUG_BACKUP) {
14787                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14788            }
14789        }
14790    }
14791
14792    @Override
14793    public byte[] getIntentFilterVerificationBackup(int userId) {
14794        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14795            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14796        }
14797
14798        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14799        try {
14800            final XmlSerializer serializer = new FastXmlSerializer();
14801            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14802            serializer.startDocument(null, true);
14803            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14804
14805            synchronized (mPackages) {
14806                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14807            }
14808
14809            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14810            serializer.endDocument();
14811            serializer.flush();
14812        } catch (Exception e) {
14813            if (DEBUG_BACKUP) {
14814                Slog.e(TAG, "Unable to write default apps for backup", e);
14815            }
14816            return null;
14817        }
14818
14819        return dataStream.toByteArray();
14820    }
14821
14822    @Override
14823    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14824        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14825            throw new SecurityException("Only the system may call restorePreferredActivities()");
14826        }
14827
14828        try {
14829            final XmlPullParser parser = Xml.newPullParser();
14830            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14831            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14832                    new BlobXmlRestorer() {
14833                        @Override
14834                        public void apply(XmlPullParser parser, int userId)
14835                                throws XmlPullParserException, IOException {
14836                            synchronized (mPackages) {
14837                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14838                                mSettings.writeLPr();
14839                            }
14840                        }
14841                    } );
14842        } catch (Exception e) {
14843            if (DEBUG_BACKUP) {
14844                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14845            }
14846        }
14847    }
14848
14849    @Override
14850    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14851            int sourceUserId, int targetUserId, int flags) {
14852        mContext.enforceCallingOrSelfPermission(
14853                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14854        int callingUid = Binder.getCallingUid();
14855        enforceOwnerRights(ownerPackage, callingUid);
14856        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14857        if (intentFilter.countActions() == 0) {
14858            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14859            return;
14860        }
14861        synchronized (mPackages) {
14862            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14863                    ownerPackage, targetUserId, flags);
14864            CrossProfileIntentResolver resolver =
14865                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14866            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14867            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14868            if (existing != null) {
14869                int size = existing.size();
14870                for (int i = 0; i < size; i++) {
14871                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14872                        return;
14873                    }
14874                }
14875            }
14876            resolver.addFilter(newFilter);
14877            scheduleWritePackageRestrictionsLocked(sourceUserId);
14878        }
14879    }
14880
14881    @Override
14882    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14883        mContext.enforceCallingOrSelfPermission(
14884                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14885        int callingUid = Binder.getCallingUid();
14886        enforceOwnerRights(ownerPackage, callingUid);
14887        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14888        synchronized (mPackages) {
14889            CrossProfileIntentResolver resolver =
14890                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14891            ArraySet<CrossProfileIntentFilter> set =
14892                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14893            for (CrossProfileIntentFilter filter : set) {
14894                if (filter.getOwnerPackage().equals(ownerPackage)) {
14895                    resolver.removeFilter(filter);
14896                }
14897            }
14898            scheduleWritePackageRestrictionsLocked(sourceUserId);
14899        }
14900    }
14901
14902    // Enforcing that callingUid is owning pkg on userId
14903    private void enforceOwnerRights(String pkg, int callingUid) {
14904        // The system owns everything.
14905        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14906            return;
14907        }
14908        int callingUserId = UserHandle.getUserId(callingUid);
14909        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14910        if (pi == null) {
14911            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14912                    + callingUserId);
14913        }
14914        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14915            throw new SecurityException("Calling uid " + callingUid
14916                    + " does not own package " + pkg);
14917        }
14918    }
14919
14920    @Override
14921    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14922        Intent intent = new Intent(Intent.ACTION_MAIN);
14923        intent.addCategory(Intent.CATEGORY_HOME);
14924
14925        final int callingUserId = UserHandle.getCallingUserId();
14926        List<ResolveInfo> list = queryIntentActivities(intent, null,
14927                PackageManager.GET_META_DATA, callingUserId);
14928        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14929                true, false, false, callingUserId);
14930
14931        allHomeCandidates.clear();
14932        if (list != null) {
14933            for (ResolveInfo ri : list) {
14934                allHomeCandidates.add(ri);
14935            }
14936        }
14937        return (preferred == null || preferred.activityInfo == null)
14938                ? null
14939                : new ComponentName(preferred.activityInfo.packageName,
14940                        preferred.activityInfo.name);
14941    }
14942
14943    @Override
14944    public void setApplicationEnabledSetting(String appPackageName,
14945            int newState, int flags, int userId, String callingPackage) {
14946        if (!sUserManager.exists(userId)) return;
14947        if (callingPackage == null) {
14948            callingPackage = Integer.toString(Binder.getCallingUid());
14949        }
14950        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14951    }
14952
14953    @Override
14954    public void setComponentEnabledSetting(ComponentName componentName,
14955            int newState, int flags, int userId) {
14956        if (!sUserManager.exists(userId)) return;
14957        setEnabledSetting(componentName.getPackageName(),
14958                componentName.getClassName(), newState, flags, userId, null);
14959    }
14960
14961    private void setEnabledSetting(final String packageName, String className, int newState,
14962            final int flags, int userId, String callingPackage) {
14963        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14964              || newState == COMPONENT_ENABLED_STATE_ENABLED
14965              || newState == COMPONENT_ENABLED_STATE_DISABLED
14966              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14967              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14968            throw new IllegalArgumentException("Invalid new component state: "
14969                    + newState);
14970        }
14971        PackageSetting pkgSetting;
14972        final int uid = Binder.getCallingUid();
14973        final int permission = mContext.checkCallingOrSelfPermission(
14974                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14975        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14976        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14977        boolean sendNow = false;
14978        boolean isApp = (className == null);
14979        String componentName = isApp ? packageName : className;
14980        int packageUid = -1;
14981        ArrayList<String> components;
14982
14983        // writer
14984        synchronized (mPackages) {
14985            pkgSetting = mSettings.mPackages.get(packageName);
14986            if (pkgSetting == null) {
14987                if (className == null) {
14988                    throw new IllegalArgumentException(
14989                            "Unknown package: " + packageName);
14990                }
14991                throw new IllegalArgumentException(
14992                        "Unknown component: " + packageName
14993                        + "/" + className);
14994            }
14995            // Allow root and verify that userId is not being specified by a different user
14996            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14997                throw new SecurityException(
14998                        "Permission Denial: attempt to change component state from pid="
14999                        + Binder.getCallingPid()
15000                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15001            }
15002            if (className == null) {
15003                // We're dealing with an application/package level state change
15004                if (pkgSetting.getEnabled(userId) == newState) {
15005                    // Nothing to do
15006                    return;
15007                }
15008                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15009                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15010                    // Don't care about who enables an app.
15011                    callingPackage = null;
15012                }
15013                pkgSetting.setEnabled(newState, userId, callingPackage);
15014                // pkgSetting.pkg.mSetEnabled = newState;
15015            } else {
15016                // We're dealing with a component level state change
15017                // First, verify that this is a valid class name.
15018                PackageParser.Package pkg = pkgSetting.pkg;
15019                if (pkg == null || !pkg.hasComponentClassName(className)) {
15020                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
15021                        throw new IllegalArgumentException("Component class " + className
15022                                + " does not exist in " + packageName);
15023                    } else {
15024                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15025                                + className + " does not exist in " + packageName);
15026                    }
15027                }
15028                switch (newState) {
15029                case COMPONENT_ENABLED_STATE_ENABLED:
15030                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15031                        return;
15032                    }
15033                    break;
15034                case COMPONENT_ENABLED_STATE_DISABLED:
15035                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15036                        return;
15037                    }
15038                    break;
15039                case COMPONENT_ENABLED_STATE_DEFAULT:
15040                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15041                        return;
15042                    }
15043                    break;
15044                default:
15045                    Slog.e(TAG, "Invalid new component state: " + newState);
15046                    return;
15047                }
15048            }
15049            scheduleWritePackageRestrictionsLocked(userId);
15050            components = mPendingBroadcasts.get(userId, packageName);
15051            final boolean newPackage = components == null;
15052            if (newPackage) {
15053                components = new ArrayList<String>();
15054            }
15055            if (!components.contains(componentName)) {
15056                components.add(componentName);
15057            }
15058            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15059                sendNow = true;
15060                // Purge entry from pending broadcast list if another one exists already
15061                // since we are sending one right away.
15062                mPendingBroadcasts.remove(userId, packageName);
15063            } else {
15064                if (newPackage) {
15065                    mPendingBroadcasts.put(userId, packageName, components);
15066                }
15067                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15068                    // Schedule a message
15069                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15070                }
15071            }
15072        }
15073
15074        long callingId = Binder.clearCallingIdentity();
15075        try {
15076            if (sendNow) {
15077                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15078                sendPackageChangedBroadcast(packageName,
15079                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15080            }
15081        } finally {
15082            Binder.restoreCallingIdentity(callingId);
15083        }
15084    }
15085
15086    private void sendPackageChangedBroadcast(String packageName,
15087            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15088        if (DEBUG_INSTALL)
15089            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15090                    + componentNames);
15091        Bundle extras = new Bundle(4);
15092        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15093        String nameList[] = new String[componentNames.size()];
15094        componentNames.toArray(nameList);
15095        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15096        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15097        extras.putInt(Intent.EXTRA_UID, packageUid);
15098        // If this is not reporting a change of the overall package, then only send it
15099        // to registered receivers.  We don't want to launch a swath of apps for every
15100        // little component state change.
15101        final int flags = !componentNames.contains(packageName)
15102                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15103        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15104                new int[] {UserHandle.getUserId(packageUid)});
15105    }
15106
15107    @Override
15108    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15109        if (!sUserManager.exists(userId)) return;
15110        final int uid = Binder.getCallingUid();
15111        final int permission = mContext.checkCallingOrSelfPermission(
15112                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15113        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15114        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15115        // writer
15116        synchronized (mPackages) {
15117            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15118                    allowedByPermission, uid, userId)) {
15119                scheduleWritePackageRestrictionsLocked(userId);
15120            }
15121        }
15122    }
15123
15124    @Override
15125    public String getInstallerPackageName(String packageName) {
15126        // reader
15127        synchronized (mPackages) {
15128            return mSettings.getInstallerPackageNameLPr(packageName);
15129        }
15130    }
15131
15132    @Override
15133    public int getApplicationEnabledSetting(String packageName, int userId) {
15134        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15135        int uid = Binder.getCallingUid();
15136        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15137        // reader
15138        synchronized (mPackages) {
15139            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15140        }
15141    }
15142
15143    @Override
15144    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15145        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15146        int uid = Binder.getCallingUid();
15147        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15148        // reader
15149        synchronized (mPackages) {
15150            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15151        }
15152    }
15153
15154    @Override
15155    public void enterSafeMode() {
15156        enforceSystemOrRoot("Only the system can request entering safe mode");
15157
15158        if (!mSystemReady) {
15159            mSafeMode = true;
15160        }
15161    }
15162
15163    @Override
15164    public void systemReady() {
15165        mSystemReady = true;
15166
15167        // Read the compatibilty setting when the system is ready.
15168        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15169                mContext.getContentResolver(),
15170                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15171        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15172        if (DEBUG_SETTINGS) {
15173            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15174        }
15175
15176        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15177
15178        synchronized (mPackages) {
15179            // Verify that all of the preferred activity components actually
15180            // exist.  It is possible for applications to be updated and at
15181            // that point remove a previously declared activity component that
15182            // had been set as a preferred activity.  We try to clean this up
15183            // the next time we encounter that preferred activity, but it is
15184            // possible for the user flow to never be able to return to that
15185            // situation so here we do a sanity check to make sure we haven't
15186            // left any junk around.
15187            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15188            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15189                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15190                removed.clear();
15191                for (PreferredActivity pa : pir.filterSet()) {
15192                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15193                        removed.add(pa);
15194                    }
15195                }
15196                if (removed.size() > 0) {
15197                    for (int r=0; r<removed.size(); r++) {
15198                        PreferredActivity pa = removed.get(r);
15199                        Slog.w(TAG, "Removing dangling preferred activity: "
15200                                + pa.mPref.mComponent);
15201                        pir.removeFilter(pa);
15202                    }
15203                    mSettings.writePackageRestrictionsLPr(
15204                            mSettings.mPreferredActivities.keyAt(i));
15205                }
15206            }
15207
15208            for (int userId : UserManagerService.getInstance().getUserIds()) {
15209                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15210                    grantPermissionsUserIds = ArrayUtils.appendInt(
15211                            grantPermissionsUserIds, userId);
15212                }
15213            }
15214        }
15215        sUserManager.systemReady();
15216
15217        // If we upgraded grant all default permissions before kicking off.
15218        for (int userId : grantPermissionsUserIds) {
15219            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15220        }
15221
15222        // Kick off any messages waiting for system ready
15223        if (mPostSystemReadyMessages != null) {
15224            for (Message msg : mPostSystemReadyMessages) {
15225                msg.sendToTarget();
15226            }
15227            mPostSystemReadyMessages = null;
15228        }
15229
15230        // Watch for external volumes that come and go over time
15231        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15232        storage.registerListener(mStorageListener);
15233
15234        mInstallerService.systemReady();
15235        mPackageDexOptimizer.systemReady();
15236
15237        MountServiceInternal mountServiceInternal = LocalServices.getService(
15238                MountServiceInternal.class);
15239        mountServiceInternal.addExternalStoragePolicy(
15240                new MountServiceInternal.ExternalStorageMountPolicy() {
15241            @Override
15242            public int getMountMode(int uid, String packageName) {
15243                if (Process.isIsolated(uid)) {
15244                    return Zygote.MOUNT_EXTERNAL_NONE;
15245                }
15246                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15247                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15248                }
15249                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15250                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15251                }
15252                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15253                    return Zygote.MOUNT_EXTERNAL_READ;
15254                }
15255                return Zygote.MOUNT_EXTERNAL_WRITE;
15256            }
15257
15258            @Override
15259            public boolean hasExternalStorage(int uid, String packageName) {
15260                return true;
15261            }
15262        });
15263    }
15264
15265    @Override
15266    public boolean isSafeMode() {
15267        return mSafeMode;
15268    }
15269
15270    @Override
15271    public boolean hasSystemUidErrors() {
15272        return mHasSystemUidErrors;
15273    }
15274
15275    static String arrayToString(int[] array) {
15276        StringBuffer buf = new StringBuffer(128);
15277        buf.append('[');
15278        if (array != null) {
15279            for (int i=0; i<array.length; i++) {
15280                if (i > 0) buf.append(", ");
15281                buf.append(array[i]);
15282            }
15283        }
15284        buf.append(']');
15285        return buf.toString();
15286    }
15287
15288    static class DumpState {
15289        public static final int DUMP_LIBS = 1 << 0;
15290        public static final int DUMP_FEATURES = 1 << 1;
15291        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15292        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15293        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15294        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15295        public static final int DUMP_PERMISSIONS = 1 << 6;
15296        public static final int DUMP_PACKAGES = 1 << 7;
15297        public static final int DUMP_SHARED_USERS = 1 << 8;
15298        public static final int DUMP_MESSAGES = 1 << 9;
15299        public static final int DUMP_PROVIDERS = 1 << 10;
15300        public static final int DUMP_VERIFIERS = 1 << 11;
15301        public static final int DUMP_PREFERRED = 1 << 12;
15302        public static final int DUMP_PREFERRED_XML = 1 << 13;
15303        public static final int DUMP_KEYSETS = 1 << 14;
15304        public static final int DUMP_VERSION = 1 << 15;
15305        public static final int DUMP_INSTALLS = 1 << 16;
15306        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15307        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15308
15309        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15310
15311        private int mTypes;
15312
15313        private int mOptions;
15314
15315        private boolean mTitlePrinted;
15316
15317        private SharedUserSetting mSharedUser;
15318
15319        public boolean isDumping(int type) {
15320            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15321                return true;
15322            }
15323
15324            return (mTypes & type) != 0;
15325        }
15326
15327        public void setDump(int type) {
15328            mTypes |= type;
15329        }
15330
15331        public boolean isOptionEnabled(int option) {
15332            return (mOptions & option) != 0;
15333        }
15334
15335        public void setOptionEnabled(int option) {
15336            mOptions |= option;
15337        }
15338
15339        public boolean onTitlePrinted() {
15340            final boolean printed = mTitlePrinted;
15341            mTitlePrinted = true;
15342            return printed;
15343        }
15344
15345        public boolean getTitlePrinted() {
15346            return mTitlePrinted;
15347        }
15348
15349        public void setTitlePrinted(boolean enabled) {
15350            mTitlePrinted = enabled;
15351        }
15352
15353        public SharedUserSetting getSharedUser() {
15354            return mSharedUser;
15355        }
15356
15357        public void setSharedUser(SharedUserSetting user) {
15358            mSharedUser = user;
15359        }
15360    }
15361
15362    @Override
15363    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15364            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15365        (new PackageManagerShellCommand(this)).exec(
15366                this, in, out, err, args, resultReceiver);
15367    }
15368
15369    @Override
15370    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15371        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15372                != PackageManager.PERMISSION_GRANTED) {
15373            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15374                    + Binder.getCallingPid()
15375                    + ", uid=" + Binder.getCallingUid()
15376                    + " without permission "
15377                    + android.Manifest.permission.DUMP);
15378            return;
15379        }
15380
15381        DumpState dumpState = new DumpState();
15382        boolean fullPreferred = false;
15383        boolean checkin = false;
15384
15385        String packageName = null;
15386        ArraySet<String> permissionNames = null;
15387
15388        int opti = 0;
15389        while (opti < args.length) {
15390            String opt = args[opti];
15391            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15392                break;
15393            }
15394            opti++;
15395
15396            if ("-a".equals(opt)) {
15397                // Right now we only know how to print all.
15398            } else if ("-h".equals(opt)) {
15399                pw.println("Package manager dump options:");
15400                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15401                pw.println("    --checkin: dump for a checkin");
15402                pw.println("    -f: print details of intent filters");
15403                pw.println("    -h: print this help");
15404                pw.println("  cmd may be one of:");
15405                pw.println("    l[ibraries]: list known shared libraries");
15406                pw.println("    f[eatures]: list device features");
15407                pw.println("    k[eysets]: print known keysets");
15408                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15409                pw.println("    perm[issions]: dump permissions");
15410                pw.println("    permission [name ...]: dump declaration and use of given permission");
15411                pw.println("    pref[erred]: print preferred package settings");
15412                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15413                pw.println("    prov[iders]: dump content providers");
15414                pw.println("    p[ackages]: dump installed packages");
15415                pw.println("    s[hared-users]: dump shared user IDs");
15416                pw.println("    m[essages]: print collected runtime messages");
15417                pw.println("    v[erifiers]: print package verifier info");
15418                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15419                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15420                pw.println("    version: print database version info");
15421                pw.println("    write: write current settings now");
15422                pw.println("    installs: details about install sessions");
15423                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15424                pw.println("    <package.name>: info about given package");
15425                return;
15426            } else if ("--checkin".equals(opt)) {
15427                checkin = true;
15428            } else if ("-f".equals(opt)) {
15429                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15430            } else {
15431                pw.println("Unknown argument: " + opt + "; use -h for help");
15432            }
15433        }
15434
15435        // Is the caller requesting to dump a particular piece of data?
15436        if (opti < args.length) {
15437            String cmd = args[opti];
15438            opti++;
15439            // Is this a package name?
15440            if ("android".equals(cmd) || cmd.contains(".")) {
15441                packageName = cmd;
15442                // When dumping a single package, we always dump all of its
15443                // filter information since the amount of data will be reasonable.
15444                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15445            } else if ("check-permission".equals(cmd)) {
15446                if (opti >= args.length) {
15447                    pw.println("Error: check-permission missing permission argument");
15448                    return;
15449                }
15450                String perm = args[opti];
15451                opti++;
15452                if (opti >= args.length) {
15453                    pw.println("Error: check-permission missing package argument");
15454                    return;
15455                }
15456                String pkg = args[opti];
15457                opti++;
15458                int user = UserHandle.getUserId(Binder.getCallingUid());
15459                if (opti < args.length) {
15460                    try {
15461                        user = Integer.parseInt(args[opti]);
15462                    } catch (NumberFormatException e) {
15463                        pw.println("Error: check-permission user argument is not a number: "
15464                                + args[opti]);
15465                        return;
15466                    }
15467                }
15468                pw.println(checkPermission(perm, pkg, user));
15469                return;
15470            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15471                dumpState.setDump(DumpState.DUMP_LIBS);
15472            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15473                dumpState.setDump(DumpState.DUMP_FEATURES);
15474            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15475                if (opti >= args.length) {
15476                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15477                            | DumpState.DUMP_SERVICE_RESOLVERS
15478                            | DumpState.DUMP_RECEIVER_RESOLVERS
15479                            | DumpState.DUMP_CONTENT_RESOLVERS);
15480                } else {
15481                    while (opti < args.length) {
15482                        String name = args[opti];
15483                        if ("a".equals(name) || "activity".equals(name)) {
15484                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15485                        } else if ("s".equals(name) || "service".equals(name)) {
15486                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15487                        } else if ("r".equals(name) || "receiver".equals(name)) {
15488                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15489                        } else if ("c".equals(name) || "content".equals(name)) {
15490                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15491                        } else {
15492                            pw.println("Error: unknown resolver table type: " + name);
15493                            return;
15494                        }
15495                        opti++;
15496                    }
15497                }
15498            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15499                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15500            } else if ("permission".equals(cmd)) {
15501                if (opti >= args.length) {
15502                    pw.println("Error: permission requires permission name");
15503                    return;
15504                }
15505                permissionNames = new ArraySet<>();
15506                while (opti < args.length) {
15507                    permissionNames.add(args[opti]);
15508                    opti++;
15509                }
15510                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15511                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15512            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15513                dumpState.setDump(DumpState.DUMP_PREFERRED);
15514            } else if ("preferred-xml".equals(cmd)) {
15515                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15516                if (opti < args.length && "--full".equals(args[opti])) {
15517                    fullPreferred = true;
15518                    opti++;
15519                }
15520            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15521                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15522            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15523                dumpState.setDump(DumpState.DUMP_PACKAGES);
15524            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15525                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15526            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15527                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15528            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15529                dumpState.setDump(DumpState.DUMP_MESSAGES);
15530            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15531                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15532            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15533                    || "intent-filter-verifiers".equals(cmd)) {
15534                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15535            } else if ("version".equals(cmd)) {
15536                dumpState.setDump(DumpState.DUMP_VERSION);
15537            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15538                dumpState.setDump(DumpState.DUMP_KEYSETS);
15539            } else if ("installs".equals(cmd)) {
15540                dumpState.setDump(DumpState.DUMP_INSTALLS);
15541            } else if ("write".equals(cmd)) {
15542                synchronized (mPackages) {
15543                    mSettings.writeLPr();
15544                    pw.println("Settings written.");
15545                    return;
15546                }
15547            }
15548        }
15549
15550        if (checkin) {
15551            pw.println("vers,1");
15552        }
15553
15554        // reader
15555        synchronized (mPackages) {
15556            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15557                if (!checkin) {
15558                    if (dumpState.onTitlePrinted())
15559                        pw.println();
15560                    pw.println("Database versions:");
15561                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15562                }
15563            }
15564
15565            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15566                if (!checkin) {
15567                    if (dumpState.onTitlePrinted())
15568                        pw.println();
15569                    pw.println("Verifiers:");
15570                    pw.print("  Required: ");
15571                    pw.print(mRequiredVerifierPackage);
15572                    pw.print(" (uid=");
15573                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15574                    pw.println(")");
15575                } else if (mRequiredVerifierPackage != null) {
15576                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15577                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15578                }
15579            }
15580
15581            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15582                    packageName == null) {
15583                if (mIntentFilterVerifierComponent != null) {
15584                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15585                    if (!checkin) {
15586                        if (dumpState.onTitlePrinted())
15587                            pw.println();
15588                        pw.println("Intent Filter Verifier:");
15589                        pw.print("  Using: ");
15590                        pw.print(verifierPackageName);
15591                        pw.print(" (uid=");
15592                        pw.print(getPackageUid(verifierPackageName, 0));
15593                        pw.println(")");
15594                    } else if (verifierPackageName != null) {
15595                        pw.print("ifv,"); pw.print(verifierPackageName);
15596                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15597                    }
15598                } else {
15599                    pw.println();
15600                    pw.println("No Intent Filter Verifier available!");
15601                }
15602            }
15603
15604            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15605                boolean printedHeader = false;
15606                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15607                while (it.hasNext()) {
15608                    String name = it.next();
15609                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15610                    if (!checkin) {
15611                        if (!printedHeader) {
15612                            if (dumpState.onTitlePrinted())
15613                                pw.println();
15614                            pw.println("Libraries:");
15615                            printedHeader = true;
15616                        }
15617                        pw.print("  ");
15618                    } else {
15619                        pw.print("lib,");
15620                    }
15621                    pw.print(name);
15622                    if (!checkin) {
15623                        pw.print(" -> ");
15624                    }
15625                    if (ent.path != null) {
15626                        if (!checkin) {
15627                            pw.print("(jar) ");
15628                            pw.print(ent.path);
15629                        } else {
15630                            pw.print(",jar,");
15631                            pw.print(ent.path);
15632                        }
15633                    } else {
15634                        if (!checkin) {
15635                            pw.print("(apk) ");
15636                            pw.print(ent.apk);
15637                        } else {
15638                            pw.print(",apk,");
15639                            pw.print(ent.apk);
15640                        }
15641                    }
15642                    pw.println();
15643                }
15644            }
15645
15646            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15647                if (dumpState.onTitlePrinted())
15648                    pw.println();
15649                if (!checkin) {
15650                    pw.println("Features:");
15651                }
15652                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15653                while (it.hasNext()) {
15654                    String name = it.next();
15655                    if (!checkin) {
15656                        pw.print("  ");
15657                    } else {
15658                        pw.print("feat,");
15659                    }
15660                    pw.println(name);
15661                }
15662            }
15663
15664            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15665                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15666                        : "Activity Resolver Table:", "  ", packageName,
15667                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15668                    dumpState.setTitlePrinted(true);
15669                }
15670            }
15671            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15672                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15673                        : "Receiver Resolver Table:", "  ", packageName,
15674                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15675                    dumpState.setTitlePrinted(true);
15676                }
15677            }
15678            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15679                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15680                        : "Service Resolver Table:", "  ", packageName,
15681                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15682                    dumpState.setTitlePrinted(true);
15683                }
15684            }
15685            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15686                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15687                        : "Provider Resolver Table:", "  ", packageName,
15688                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15689                    dumpState.setTitlePrinted(true);
15690                }
15691            }
15692
15693            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15694                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15695                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15696                    int user = mSettings.mPreferredActivities.keyAt(i);
15697                    if (pir.dump(pw,
15698                            dumpState.getTitlePrinted()
15699                                ? "\nPreferred Activities User " + user + ":"
15700                                : "Preferred Activities User " + user + ":", "  ",
15701                            packageName, true, false)) {
15702                        dumpState.setTitlePrinted(true);
15703                    }
15704                }
15705            }
15706
15707            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15708                pw.flush();
15709                FileOutputStream fout = new FileOutputStream(fd);
15710                BufferedOutputStream str = new BufferedOutputStream(fout);
15711                XmlSerializer serializer = new FastXmlSerializer();
15712                try {
15713                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15714                    serializer.startDocument(null, true);
15715                    serializer.setFeature(
15716                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15717                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15718                    serializer.endDocument();
15719                    serializer.flush();
15720                } catch (IllegalArgumentException e) {
15721                    pw.println("Failed writing: " + e);
15722                } catch (IllegalStateException e) {
15723                    pw.println("Failed writing: " + e);
15724                } catch (IOException e) {
15725                    pw.println("Failed writing: " + e);
15726                }
15727            }
15728
15729            if (!checkin
15730                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15731                    && packageName == null) {
15732                pw.println();
15733                int count = mSettings.mPackages.size();
15734                if (count == 0) {
15735                    pw.println("No applications!");
15736                    pw.println();
15737                } else {
15738                    final String prefix = "  ";
15739                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15740                    if (allPackageSettings.size() == 0) {
15741                        pw.println("No domain preferred apps!");
15742                        pw.println();
15743                    } else {
15744                        pw.println("App verification status:");
15745                        pw.println();
15746                        count = 0;
15747                        for (PackageSetting ps : allPackageSettings) {
15748                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15749                            if (ivi == null || ivi.getPackageName() == null) continue;
15750                            pw.println(prefix + "Package: " + ivi.getPackageName());
15751                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15752                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15753                            pw.println();
15754                            count++;
15755                        }
15756                        if (count == 0) {
15757                            pw.println(prefix + "No app verification established.");
15758                            pw.println();
15759                        }
15760                        for (int userId : sUserManager.getUserIds()) {
15761                            pw.println("App linkages for user " + userId + ":");
15762                            pw.println();
15763                            count = 0;
15764                            for (PackageSetting ps : allPackageSettings) {
15765                                final long status = ps.getDomainVerificationStatusForUser(userId);
15766                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15767                                    continue;
15768                                }
15769                                pw.println(prefix + "Package: " + ps.name);
15770                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15771                                String statusStr = IntentFilterVerificationInfo.
15772                                        getStatusStringFromValue(status);
15773                                pw.println(prefix + "Status:  " + statusStr);
15774                                pw.println();
15775                                count++;
15776                            }
15777                            if (count == 0) {
15778                                pw.println(prefix + "No configured app linkages.");
15779                                pw.println();
15780                            }
15781                        }
15782                    }
15783                }
15784            }
15785
15786            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15787                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15788                if (packageName == null && permissionNames == null) {
15789                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15790                        if (iperm == 0) {
15791                            if (dumpState.onTitlePrinted())
15792                                pw.println();
15793                            pw.println("AppOp Permissions:");
15794                        }
15795                        pw.print("  AppOp Permission ");
15796                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15797                        pw.println(":");
15798                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15799                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15800                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15801                        }
15802                    }
15803                }
15804            }
15805
15806            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15807                boolean printedSomething = false;
15808                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15809                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15810                        continue;
15811                    }
15812                    if (!printedSomething) {
15813                        if (dumpState.onTitlePrinted())
15814                            pw.println();
15815                        pw.println("Registered ContentProviders:");
15816                        printedSomething = true;
15817                    }
15818                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15819                    pw.print("    "); pw.println(p.toString());
15820                }
15821                printedSomething = false;
15822                for (Map.Entry<String, PackageParser.Provider> entry :
15823                        mProvidersByAuthority.entrySet()) {
15824                    PackageParser.Provider p = entry.getValue();
15825                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15826                        continue;
15827                    }
15828                    if (!printedSomething) {
15829                        if (dumpState.onTitlePrinted())
15830                            pw.println();
15831                        pw.println("ContentProvider Authorities:");
15832                        printedSomething = true;
15833                    }
15834                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15835                    pw.print("    "); pw.println(p.toString());
15836                    if (p.info != null && p.info.applicationInfo != null) {
15837                        final String appInfo = p.info.applicationInfo.toString();
15838                        pw.print("      applicationInfo="); pw.println(appInfo);
15839                    }
15840                }
15841            }
15842
15843            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15844                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15845            }
15846
15847            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15848                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15849            }
15850
15851            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15852                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15853            }
15854
15855            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15856                // XXX should handle packageName != null by dumping only install data that
15857                // the given package is involved with.
15858                if (dumpState.onTitlePrinted()) pw.println();
15859                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15860            }
15861
15862            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15863                if (dumpState.onTitlePrinted()) pw.println();
15864                mSettings.dumpReadMessagesLPr(pw, dumpState);
15865
15866                pw.println();
15867                pw.println("Package warning messages:");
15868                BufferedReader in = null;
15869                String line = null;
15870                try {
15871                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15872                    while ((line = in.readLine()) != null) {
15873                        if (line.contains("ignored: updated version")) continue;
15874                        pw.println(line);
15875                    }
15876                } catch (IOException ignored) {
15877                } finally {
15878                    IoUtils.closeQuietly(in);
15879                }
15880            }
15881
15882            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15883                BufferedReader in = null;
15884                String line = null;
15885                try {
15886                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15887                    while ((line = in.readLine()) != null) {
15888                        if (line.contains("ignored: updated version")) continue;
15889                        pw.print("msg,");
15890                        pw.println(line);
15891                    }
15892                } catch (IOException ignored) {
15893                } finally {
15894                    IoUtils.closeQuietly(in);
15895                }
15896            }
15897        }
15898    }
15899
15900    private String dumpDomainString(String packageName) {
15901        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15902        List<IntentFilter> filters = getAllIntentFilters(packageName);
15903
15904        ArraySet<String> result = new ArraySet<>();
15905        if (iviList.size() > 0) {
15906            for (IntentFilterVerificationInfo ivi : iviList) {
15907                for (String host : ivi.getDomains()) {
15908                    result.add(host);
15909                }
15910            }
15911        }
15912        if (filters != null && filters.size() > 0) {
15913            for (IntentFilter filter : filters) {
15914                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15915                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15916                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15917                    result.addAll(filter.getHostsList());
15918                }
15919            }
15920        }
15921
15922        StringBuilder sb = new StringBuilder(result.size() * 16);
15923        for (String domain : result) {
15924            if (sb.length() > 0) sb.append(" ");
15925            sb.append(domain);
15926        }
15927        return sb.toString();
15928    }
15929
15930    // ------- apps on sdcard specific code -------
15931    static final boolean DEBUG_SD_INSTALL = false;
15932
15933    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15934
15935    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15936
15937    private boolean mMediaMounted = false;
15938
15939    static String getEncryptKey() {
15940        try {
15941            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15942                    SD_ENCRYPTION_KEYSTORE_NAME);
15943            if (sdEncKey == null) {
15944                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15945                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15946                if (sdEncKey == null) {
15947                    Slog.e(TAG, "Failed to create encryption keys");
15948                    return null;
15949                }
15950            }
15951            return sdEncKey;
15952        } catch (NoSuchAlgorithmException nsae) {
15953            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15954            return null;
15955        } catch (IOException ioe) {
15956            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15957            return null;
15958        }
15959    }
15960
15961    /*
15962     * Update media status on PackageManager.
15963     */
15964    @Override
15965    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15966        int callingUid = Binder.getCallingUid();
15967        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15968            throw new SecurityException("Media status can only be updated by the system");
15969        }
15970        // reader; this apparently protects mMediaMounted, but should probably
15971        // be a different lock in that case.
15972        synchronized (mPackages) {
15973            Log.i(TAG, "Updating external media status from "
15974                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15975                    + (mediaStatus ? "mounted" : "unmounted"));
15976            if (DEBUG_SD_INSTALL)
15977                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15978                        + ", mMediaMounted=" + mMediaMounted);
15979            if (mediaStatus == mMediaMounted) {
15980                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15981                        : 0, -1);
15982                mHandler.sendMessage(msg);
15983                return;
15984            }
15985            mMediaMounted = mediaStatus;
15986        }
15987        // Queue up an async operation since the package installation may take a
15988        // little while.
15989        mHandler.post(new Runnable() {
15990            public void run() {
15991                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15992            }
15993        });
15994    }
15995
15996    /**
15997     * Called by MountService when the initial ASECs to scan are available.
15998     * Should block until all the ASEC containers are finished being scanned.
15999     */
16000    public void scanAvailableAsecs() {
16001        updateExternalMediaStatusInner(true, false, false);
16002        if (mShouldRestoreconData) {
16003            SELinuxMMAC.setRestoreconDone();
16004            mShouldRestoreconData = false;
16005        }
16006    }
16007
16008    /*
16009     * Collect information of applications on external media, map them against
16010     * existing containers and update information based on current mount status.
16011     * Please note that we always have to report status if reportStatus has been
16012     * set to true especially when unloading packages.
16013     */
16014    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16015            boolean externalStorage) {
16016        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16017        int[] uidArr = EmptyArray.INT;
16018
16019        final String[] list = PackageHelper.getSecureContainerList();
16020        if (ArrayUtils.isEmpty(list)) {
16021            Log.i(TAG, "No secure containers found");
16022        } else {
16023            // Process list of secure containers and categorize them
16024            // as active or stale based on their package internal state.
16025
16026            // reader
16027            synchronized (mPackages) {
16028                for (String cid : list) {
16029                    // Leave stages untouched for now; installer service owns them
16030                    if (PackageInstallerService.isStageName(cid)) continue;
16031
16032                    if (DEBUG_SD_INSTALL)
16033                        Log.i(TAG, "Processing container " + cid);
16034                    String pkgName = getAsecPackageName(cid);
16035                    if (pkgName == null) {
16036                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16037                        continue;
16038                    }
16039                    if (DEBUG_SD_INSTALL)
16040                        Log.i(TAG, "Looking for pkg : " + pkgName);
16041
16042                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16043                    if (ps == null) {
16044                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16045                        continue;
16046                    }
16047
16048                    /*
16049                     * Skip packages that are not external if we're unmounting
16050                     * external storage.
16051                     */
16052                    if (externalStorage && !isMounted && !isExternal(ps)) {
16053                        continue;
16054                    }
16055
16056                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16057                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16058                    // The package status is changed only if the code path
16059                    // matches between settings and the container id.
16060                    if (ps.codePathString != null
16061                            && ps.codePathString.startsWith(args.getCodePath())) {
16062                        if (DEBUG_SD_INSTALL) {
16063                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16064                                    + " at code path: " + ps.codePathString);
16065                        }
16066
16067                        // We do have a valid package installed on sdcard
16068                        processCids.put(args, ps.codePathString);
16069                        final int uid = ps.appId;
16070                        if (uid != -1) {
16071                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16072                        }
16073                    } else {
16074                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16075                                + ps.codePathString);
16076                    }
16077                }
16078            }
16079
16080            Arrays.sort(uidArr);
16081        }
16082
16083        // Process packages with valid entries.
16084        if (isMounted) {
16085            if (DEBUG_SD_INSTALL)
16086                Log.i(TAG, "Loading packages");
16087            loadMediaPackages(processCids, uidArr, externalStorage);
16088            startCleaningPackages();
16089            mInstallerService.onSecureContainersAvailable();
16090        } else {
16091            if (DEBUG_SD_INSTALL)
16092                Log.i(TAG, "Unloading packages");
16093            unloadMediaPackages(processCids, uidArr, reportStatus);
16094        }
16095    }
16096
16097    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16098            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16099        final int size = infos.size();
16100        final String[] packageNames = new String[size];
16101        final int[] packageUids = new int[size];
16102        for (int i = 0; i < size; i++) {
16103            final ApplicationInfo info = infos.get(i);
16104            packageNames[i] = info.packageName;
16105            packageUids[i] = info.uid;
16106        }
16107        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16108                finishedReceiver);
16109    }
16110
16111    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16112            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16113        sendResourcesChangedBroadcast(mediaStatus, replacing,
16114                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16115    }
16116
16117    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16118            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16119        int size = pkgList.length;
16120        if (size > 0) {
16121            // Send broadcasts here
16122            Bundle extras = new Bundle();
16123            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16124            if (uidArr != null) {
16125                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16126            }
16127            if (replacing) {
16128                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16129            }
16130            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16131                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16132            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16133        }
16134    }
16135
16136   /*
16137     * Look at potentially valid container ids from processCids If package
16138     * information doesn't match the one on record or package scanning fails,
16139     * the cid is added to list of removeCids. We currently don't delete stale
16140     * containers.
16141     */
16142    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16143            boolean externalStorage) {
16144        ArrayList<String> pkgList = new ArrayList<String>();
16145        Set<AsecInstallArgs> keys = processCids.keySet();
16146
16147        for (AsecInstallArgs args : keys) {
16148            String codePath = processCids.get(args);
16149            if (DEBUG_SD_INSTALL)
16150                Log.i(TAG, "Loading container : " + args.cid);
16151            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16152            try {
16153                // Make sure there are no container errors first.
16154                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16155                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16156                            + " when installing from sdcard");
16157                    continue;
16158                }
16159                // Check code path here.
16160                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16161                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16162                            + " does not match one in settings " + codePath);
16163                    continue;
16164                }
16165                // Parse package
16166                int parseFlags = mDefParseFlags;
16167                if (args.isExternalAsec()) {
16168                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16169                }
16170                if (args.isFwdLocked()) {
16171                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16172                }
16173
16174                synchronized (mInstallLock) {
16175                    PackageParser.Package pkg = null;
16176                    try {
16177                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16178                    } catch (PackageManagerException e) {
16179                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16180                    }
16181                    // Scan the package
16182                    if (pkg != null) {
16183                        /*
16184                         * TODO why is the lock being held? doPostInstall is
16185                         * called in other places without the lock. This needs
16186                         * to be straightened out.
16187                         */
16188                        // writer
16189                        synchronized (mPackages) {
16190                            retCode = PackageManager.INSTALL_SUCCEEDED;
16191                            pkgList.add(pkg.packageName);
16192                            // Post process args
16193                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16194                                    pkg.applicationInfo.uid);
16195                        }
16196                    } else {
16197                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16198                    }
16199                }
16200
16201            } finally {
16202                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16203                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16204                }
16205            }
16206        }
16207        // writer
16208        synchronized (mPackages) {
16209            // If the platform SDK has changed since the last time we booted,
16210            // we need to re-grant app permission to catch any new ones that
16211            // appear. This is really a hack, and means that apps can in some
16212            // cases get permissions that the user didn't initially explicitly
16213            // allow... it would be nice to have some better way to handle
16214            // this situation.
16215            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16216                    : mSettings.getInternalVersion();
16217            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16218                    : StorageManager.UUID_PRIVATE_INTERNAL;
16219
16220            int updateFlags = UPDATE_PERMISSIONS_ALL;
16221            if (ver.sdkVersion != mSdkVersion) {
16222                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16223                        + mSdkVersion + "; regranting permissions for external");
16224                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16225            }
16226            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16227
16228            // Yay, everything is now upgraded
16229            ver.forceCurrent();
16230
16231            // can downgrade to reader
16232            // Persist settings
16233            mSettings.writeLPr();
16234        }
16235        // Send a broadcast to let everyone know we are done processing
16236        if (pkgList.size() > 0) {
16237            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16238        }
16239    }
16240
16241   /*
16242     * Utility method to unload a list of specified containers
16243     */
16244    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16245        // Just unmount all valid containers.
16246        for (AsecInstallArgs arg : cidArgs) {
16247            synchronized (mInstallLock) {
16248                arg.doPostDeleteLI(false);
16249           }
16250       }
16251   }
16252
16253    /*
16254     * Unload packages mounted on external media. This involves deleting package
16255     * data from internal structures, sending broadcasts about diabled packages,
16256     * gc'ing to free up references, unmounting all secure containers
16257     * corresponding to packages on external media, and posting a
16258     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16259     * that we always have to post this message if status has been requested no
16260     * matter what.
16261     */
16262    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16263            final boolean reportStatus) {
16264        if (DEBUG_SD_INSTALL)
16265            Log.i(TAG, "unloading media packages");
16266        ArrayList<String> pkgList = new ArrayList<String>();
16267        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16268        final Set<AsecInstallArgs> keys = processCids.keySet();
16269        for (AsecInstallArgs args : keys) {
16270            String pkgName = args.getPackageName();
16271            if (DEBUG_SD_INSTALL)
16272                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16273            // Delete package internally
16274            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16275            synchronized (mInstallLock) {
16276                boolean res = deletePackageLI(pkgName, null, false, null, null,
16277                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16278                if (res) {
16279                    pkgList.add(pkgName);
16280                } else {
16281                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16282                    failedList.add(args);
16283                }
16284            }
16285        }
16286
16287        // reader
16288        synchronized (mPackages) {
16289            // We didn't update the settings after removing each package;
16290            // write them now for all packages.
16291            mSettings.writeLPr();
16292        }
16293
16294        // We have to absolutely send UPDATED_MEDIA_STATUS only
16295        // after confirming that all the receivers processed the ordered
16296        // broadcast when packages get disabled, force a gc to clean things up.
16297        // and unload all the containers.
16298        if (pkgList.size() > 0) {
16299            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16300                    new IIntentReceiver.Stub() {
16301                public void performReceive(Intent intent, int resultCode, String data,
16302                        Bundle extras, boolean ordered, boolean sticky,
16303                        int sendingUser) throws RemoteException {
16304                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16305                            reportStatus ? 1 : 0, 1, keys);
16306                    mHandler.sendMessage(msg);
16307                }
16308            });
16309        } else {
16310            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16311                    keys);
16312            mHandler.sendMessage(msg);
16313        }
16314    }
16315
16316    private void loadPrivatePackages(final VolumeInfo vol) {
16317        mHandler.post(new Runnable() {
16318            @Override
16319            public void run() {
16320                loadPrivatePackagesInner(vol);
16321            }
16322        });
16323    }
16324
16325    private void loadPrivatePackagesInner(VolumeInfo vol) {
16326        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16327        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16328
16329        final VersionInfo ver;
16330        final List<PackageSetting> packages;
16331        synchronized (mPackages) {
16332            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16333            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16334        }
16335
16336        for (PackageSetting ps : packages) {
16337            synchronized (mInstallLock) {
16338                final PackageParser.Package pkg;
16339                try {
16340                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16341                    loaded.add(pkg.applicationInfo);
16342                } catch (PackageManagerException e) {
16343                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16344                }
16345
16346                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16347                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16348                }
16349            }
16350        }
16351
16352        synchronized (mPackages) {
16353            int updateFlags = UPDATE_PERMISSIONS_ALL;
16354            if (ver.sdkVersion != mSdkVersion) {
16355                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16356                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16357                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16358            }
16359            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16360
16361            // Yay, everything is now upgraded
16362            ver.forceCurrent();
16363
16364            mSettings.writeLPr();
16365        }
16366
16367        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16368        sendResourcesChangedBroadcast(true, false, loaded, null);
16369    }
16370
16371    private void unloadPrivatePackages(final VolumeInfo vol) {
16372        mHandler.post(new Runnable() {
16373            @Override
16374            public void run() {
16375                unloadPrivatePackagesInner(vol);
16376            }
16377        });
16378    }
16379
16380    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16381        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16382        synchronized (mInstallLock) {
16383        synchronized (mPackages) {
16384            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16385            for (PackageSetting ps : packages) {
16386                if (ps.pkg == null) continue;
16387
16388                final ApplicationInfo info = ps.pkg.applicationInfo;
16389                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16390                if (deletePackageLI(ps.name, null, false, null, null,
16391                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16392                    unloaded.add(info);
16393                } else {
16394                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16395                }
16396            }
16397
16398            mSettings.writeLPr();
16399        }
16400        }
16401
16402        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16403        sendResourcesChangedBroadcast(false, false, unloaded, null);
16404    }
16405
16406    /**
16407     * Examine all users present on given mounted volume, and destroy data
16408     * belonging to users that are no longer valid, or whose user ID has been
16409     * recycled.
16410     */
16411    private void reconcileUsers(String volumeUuid) {
16412        final File[] files = FileUtils
16413                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16414        for (File file : files) {
16415            if (!file.isDirectory()) continue;
16416
16417            final int userId;
16418            final UserInfo info;
16419            try {
16420                userId = Integer.parseInt(file.getName());
16421                info = sUserManager.getUserInfo(userId);
16422            } catch (NumberFormatException e) {
16423                Slog.w(TAG, "Invalid user directory " + file);
16424                continue;
16425            }
16426
16427            boolean destroyUser = false;
16428            if (info == null) {
16429                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16430                        + " because no matching user was found");
16431                destroyUser = true;
16432            } else {
16433                try {
16434                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16435                } catch (IOException e) {
16436                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16437                            + " because we failed to enforce serial number: " + e);
16438                    destroyUser = true;
16439                }
16440            }
16441
16442            if (destroyUser) {
16443                synchronized (mInstallLock) {
16444                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16445                }
16446            }
16447        }
16448
16449        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16450        final UserManager um = mContext.getSystemService(UserManager.class);
16451        for (UserInfo user : um.getUsers()) {
16452            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16453            if (userDir.exists()) continue;
16454
16455            try {
16456                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber);
16457                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16458            } catch (IOException e) {
16459                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16460            }
16461        }
16462    }
16463
16464    /**
16465     * Examine all apps present on given mounted volume, and destroy apps that
16466     * aren't expected, either due to uninstallation or reinstallation on
16467     * another volume.
16468     */
16469    private void reconcileApps(String volumeUuid) {
16470        final File[] files = FileUtils
16471                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16472        for (File file : files) {
16473            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16474                    && !PackageInstallerService.isStageName(file.getName());
16475            if (!isPackage) {
16476                // Ignore entries which are not packages
16477                continue;
16478            }
16479
16480            boolean destroyApp = false;
16481            String packageName = null;
16482            try {
16483                final PackageLite pkg = PackageParser.parsePackageLite(file,
16484                        PackageParser.PARSE_MUST_BE_APK);
16485                packageName = pkg.packageName;
16486
16487                synchronized (mPackages) {
16488                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16489                    if (ps == null) {
16490                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16491                                + volumeUuid + " because we found no install record");
16492                        destroyApp = true;
16493                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16494                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16495                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16496                        destroyApp = true;
16497                    }
16498                }
16499
16500            } catch (PackageParserException e) {
16501                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16502                destroyApp = true;
16503            }
16504
16505            if (destroyApp) {
16506                synchronized (mInstallLock) {
16507                    if (packageName != null) {
16508                        removeDataDirsLI(volumeUuid, packageName);
16509                    }
16510                    if (file.isDirectory()) {
16511                        mInstaller.rmPackageDir(file.getAbsolutePath());
16512                    } else {
16513                        file.delete();
16514                    }
16515                }
16516            }
16517        }
16518    }
16519
16520    private void unfreezePackage(String packageName) {
16521        synchronized (mPackages) {
16522            final PackageSetting ps = mSettings.mPackages.get(packageName);
16523            if (ps != null) {
16524                ps.frozen = false;
16525            }
16526        }
16527    }
16528
16529    @Override
16530    public int movePackage(final String packageName, final String volumeUuid) {
16531        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16532
16533        final int moveId = mNextMoveId.getAndIncrement();
16534        mHandler.post(new Runnable() {
16535            @Override
16536            public void run() {
16537                try {
16538                    movePackageInternal(packageName, volumeUuid, moveId);
16539                } catch (PackageManagerException e) {
16540                    Slog.w(TAG, "Failed to move " + packageName, e);
16541                    mMoveCallbacks.notifyStatusChanged(moveId,
16542                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16543                }
16544            }
16545        });
16546        return moveId;
16547    }
16548
16549    private void movePackageInternal(final String packageName, final String volumeUuid,
16550            final int moveId) throws PackageManagerException {
16551        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16552        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16553        final PackageManager pm = mContext.getPackageManager();
16554
16555        final boolean currentAsec;
16556        final String currentVolumeUuid;
16557        final File codeFile;
16558        final String installerPackageName;
16559        final String packageAbiOverride;
16560        final int appId;
16561        final String seinfo;
16562        final String label;
16563
16564        // reader
16565        synchronized (mPackages) {
16566            final PackageParser.Package pkg = mPackages.get(packageName);
16567            final PackageSetting ps = mSettings.mPackages.get(packageName);
16568            if (pkg == null || ps == null) {
16569                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16570            }
16571
16572            if (pkg.applicationInfo.isSystemApp()) {
16573                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16574                        "Cannot move system application");
16575            }
16576
16577            if (pkg.applicationInfo.isExternalAsec()) {
16578                currentAsec = true;
16579                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16580            } else if (pkg.applicationInfo.isForwardLocked()) {
16581                currentAsec = true;
16582                currentVolumeUuid = "forward_locked";
16583            } else {
16584                currentAsec = false;
16585                currentVolumeUuid = ps.volumeUuid;
16586
16587                final File probe = new File(pkg.codePath);
16588                final File probeOat = new File(probe, "oat");
16589                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16590                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16591                            "Move only supported for modern cluster style installs");
16592                }
16593            }
16594
16595            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16596                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16597                        "Package already moved to " + volumeUuid);
16598            }
16599
16600            if (ps.frozen) {
16601                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16602                        "Failed to move already frozen package");
16603            }
16604            ps.frozen = true;
16605
16606            codeFile = new File(pkg.codePath);
16607            installerPackageName = ps.installerPackageName;
16608            packageAbiOverride = ps.cpuAbiOverrideString;
16609            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16610            seinfo = pkg.applicationInfo.seinfo;
16611            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16612        }
16613
16614        // Now that we're guarded by frozen state, kill app during move
16615        final long token = Binder.clearCallingIdentity();
16616        try {
16617            killApplication(packageName, appId, "move pkg");
16618        } finally {
16619            Binder.restoreCallingIdentity(token);
16620        }
16621
16622        final Bundle extras = new Bundle();
16623        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16624        extras.putString(Intent.EXTRA_TITLE, label);
16625        mMoveCallbacks.notifyCreated(moveId, extras);
16626
16627        int installFlags;
16628        final boolean moveCompleteApp;
16629        final File measurePath;
16630
16631        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16632            installFlags = INSTALL_INTERNAL;
16633            moveCompleteApp = !currentAsec;
16634            measurePath = Environment.getDataAppDirectory(volumeUuid);
16635        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16636            installFlags = INSTALL_EXTERNAL;
16637            moveCompleteApp = false;
16638            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16639        } else {
16640            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16641            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16642                    || !volume.isMountedWritable()) {
16643                unfreezePackage(packageName);
16644                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16645                        "Move location not mounted private volume");
16646            }
16647
16648            Preconditions.checkState(!currentAsec);
16649
16650            installFlags = INSTALL_INTERNAL;
16651            moveCompleteApp = true;
16652            measurePath = Environment.getDataAppDirectory(volumeUuid);
16653        }
16654
16655        final PackageStats stats = new PackageStats(null, -1);
16656        synchronized (mInstaller) {
16657            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16658                unfreezePackage(packageName);
16659                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16660                        "Failed to measure package size");
16661            }
16662        }
16663
16664        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16665                + stats.dataSize);
16666
16667        final long startFreeBytes = measurePath.getFreeSpace();
16668        final long sizeBytes;
16669        if (moveCompleteApp) {
16670            sizeBytes = stats.codeSize + stats.dataSize;
16671        } else {
16672            sizeBytes = stats.codeSize;
16673        }
16674
16675        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16676            unfreezePackage(packageName);
16677            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16678                    "Not enough free space to move");
16679        }
16680
16681        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16682
16683        final CountDownLatch installedLatch = new CountDownLatch(1);
16684        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16685            @Override
16686            public void onUserActionRequired(Intent intent) throws RemoteException {
16687                throw new IllegalStateException();
16688            }
16689
16690            @Override
16691            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16692                    Bundle extras) throws RemoteException {
16693                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16694                        + PackageManager.installStatusToString(returnCode, msg));
16695
16696                installedLatch.countDown();
16697
16698                // Regardless of success or failure of the move operation,
16699                // always unfreeze the package
16700                unfreezePackage(packageName);
16701
16702                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16703                switch (status) {
16704                    case PackageInstaller.STATUS_SUCCESS:
16705                        mMoveCallbacks.notifyStatusChanged(moveId,
16706                                PackageManager.MOVE_SUCCEEDED);
16707                        break;
16708                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16709                        mMoveCallbacks.notifyStatusChanged(moveId,
16710                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16711                        break;
16712                    default:
16713                        mMoveCallbacks.notifyStatusChanged(moveId,
16714                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16715                        break;
16716                }
16717            }
16718        };
16719
16720        final MoveInfo move;
16721        if (moveCompleteApp) {
16722            // Kick off a thread to report progress estimates
16723            new Thread() {
16724                @Override
16725                public void run() {
16726                    while (true) {
16727                        try {
16728                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16729                                break;
16730                            }
16731                        } catch (InterruptedException ignored) {
16732                        }
16733
16734                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16735                        final int progress = 10 + (int) MathUtils.constrain(
16736                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16737                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16738                    }
16739                }
16740            }.start();
16741
16742            final String dataAppName = codeFile.getName();
16743            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16744                    dataAppName, appId, seinfo);
16745        } else {
16746            move = null;
16747        }
16748
16749        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16750
16751        final Message msg = mHandler.obtainMessage(INIT_COPY);
16752        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16753        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16754                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16755        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16756        msg.obj = params;
16757
16758        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16759                System.identityHashCode(msg.obj));
16760        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16761                System.identityHashCode(msg.obj));
16762
16763        mHandler.sendMessage(msg);
16764    }
16765
16766    @Override
16767    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16768        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16769
16770        final int realMoveId = mNextMoveId.getAndIncrement();
16771        final Bundle extras = new Bundle();
16772        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16773        mMoveCallbacks.notifyCreated(realMoveId, extras);
16774
16775        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16776            @Override
16777            public void onCreated(int moveId, Bundle extras) {
16778                // Ignored
16779            }
16780
16781            @Override
16782            public void onStatusChanged(int moveId, int status, long estMillis) {
16783                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16784            }
16785        };
16786
16787        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16788        storage.setPrimaryStorageUuid(volumeUuid, callback);
16789        return realMoveId;
16790    }
16791
16792    @Override
16793    public int getMoveStatus(int moveId) {
16794        mContext.enforceCallingOrSelfPermission(
16795                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16796        return mMoveCallbacks.mLastStatus.get(moveId);
16797    }
16798
16799    @Override
16800    public void registerMoveCallback(IPackageMoveObserver callback) {
16801        mContext.enforceCallingOrSelfPermission(
16802                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16803        mMoveCallbacks.register(callback);
16804    }
16805
16806    @Override
16807    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16808        mContext.enforceCallingOrSelfPermission(
16809                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16810        mMoveCallbacks.unregister(callback);
16811    }
16812
16813    @Override
16814    public boolean setInstallLocation(int loc) {
16815        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16816                null);
16817        if (getInstallLocation() == loc) {
16818            return true;
16819        }
16820        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16821                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16822            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16823                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16824            return true;
16825        }
16826        return false;
16827   }
16828
16829    @Override
16830    public int getInstallLocation() {
16831        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16832                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16833                PackageHelper.APP_INSTALL_AUTO);
16834    }
16835
16836    /** Called by UserManagerService */
16837    void cleanUpUser(UserManagerService userManager, int userHandle) {
16838        synchronized (mPackages) {
16839            mDirtyUsers.remove(userHandle);
16840            mUserNeedsBadging.delete(userHandle);
16841            mSettings.removeUserLPw(userHandle);
16842            mPendingBroadcasts.remove(userHandle);
16843        }
16844        synchronized (mInstallLock) {
16845            if (mInstaller != null) {
16846                final StorageManager storage = mContext.getSystemService(StorageManager.class);
16847                for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16848                    final String volumeUuid = vol.getFsUuid();
16849                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16850                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16851                }
16852            }
16853            synchronized (mPackages) {
16854                removeUnusedPackagesLILPw(userManager, userHandle);
16855            }
16856        }
16857    }
16858
16859    /**
16860     * We're removing userHandle and would like to remove any downloaded packages
16861     * that are no longer in use by any other user.
16862     * @param userHandle the user being removed
16863     */
16864    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16865        final boolean DEBUG_CLEAN_APKS = false;
16866        int [] users = userManager.getUserIds();
16867        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16868        while (psit.hasNext()) {
16869            PackageSetting ps = psit.next();
16870            if (ps.pkg == null) {
16871                continue;
16872            }
16873            final String packageName = ps.pkg.packageName;
16874            // Skip over if system app
16875            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16876                continue;
16877            }
16878            if (DEBUG_CLEAN_APKS) {
16879                Slog.i(TAG, "Checking package " + packageName);
16880            }
16881            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16882            if (keep) {
16883                if (DEBUG_CLEAN_APKS) {
16884                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16885                }
16886            } else {
16887                for (int i = 0; i < users.length; i++) {
16888                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16889                        keep = true;
16890                        if (DEBUG_CLEAN_APKS) {
16891                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
16892                                    + users[i]);
16893                        }
16894                        break;
16895                    }
16896                }
16897            }
16898            if (!keep) {
16899                if (DEBUG_CLEAN_APKS) {
16900                    Slog.i(TAG, "  Removing package " + packageName);
16901                }
16902                mHandler.post(new Runnable() {
16903                    public void run() {
16904                        deletePackageX(packageName, userHandle, 0);
16905                    } //end run
16906                });
16907            }
16908        }
16909    }
16910
16911    /** Called by UserManagerService */
16912    void createNewUser(int userHandle) {
16913        if (mInstaller != null) {
16914            synchronized (mInstallLock) {
16915                synchronized (mPackages) {
16916                    mInstaller.createUserConfig(userHandle);
16917                    mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16918                }
16919            }
16920            synchronized (mPackages) {
16921                applyFactoryDefaultBrowserLPw(userHandle);
16922                primeDomainVerificationsLPw(userHandle);
16923            }
16924        }
16925    }
16926
16927    void newUserCreated(final int userHandle) {
16928        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16929        // If permission review for legacy apps is required, we represent
16930        // dagerous permissions for such apps as always granted runtime
16931        // permissions to keep per user flag state whether review is needed.
16932        // Hence, if a new user is added we have to propagate dangerous
16933        // permission grants for these legacy apps.
16934        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
16935            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
16936                    | UPDATE_PERMISSIONS_REPLACE_ALL);
16937        }
16938    }
16939
16940    @Override
16941    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16942        mContext.enforceCallingOrSelfPermission(
16943                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16944                "Only package verification agents can read the verifier device identity");
16945
16946        synchronized (mPackages) {
16947            return mSettings.getVerifierDeviceIdentityLPw();
16948        }
16949    }
16950
16951    @Override
16952    public void setPermissionEnforced(String permission, boolean enforced) {
16953        // TODO: Now that we no longer change GID for storage, this should to away.
16954        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16955                "setPermissionEnforced");
16956        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16957            synchronized (mPackages) {
16958                if (mSettings.mReadExternalStorageEnforced == null
16959                        || mSettings.mReadExternalStorageEnforced != enforced) {
16960                    mSettings.mReadExternalStorageEnforced = enforced;
16961                    mSettings.writeLPr();
16962                }
16963            }
16964            // kill any non-foreground processes so we restart them and
16965            // grant/revoke the GID.
16966            final IActivityManager am = ActivityManagerNative.getDefault();
16967            if (am != null) {
16968                final long token = Binder.clearCallingIdentity();
16969                try {
16970                    am.killProcessesBelowForeground("setPermissionEnforcement");
16971                } catch (RemoteException e) {
16972                } finally {
16973                    Binder.restoreCallingIdentity(token);
16974                }
16975            }
16976        } else {
16977            throw new IllegalArgumentException("No selective enforcement for " + permission);
16978        }
16979    }
16980
16981    @Override
16982    @Deprecated
16983    public boolean isPermissionEnforced(String permission) {
16984        return true;
16985    }
16986
16987    @Override
16988    public boolean isStorageLow() {
16989        final long token = Binder.clearCallingIdentity();
16990        try {
16991            final DeviceStorageMonitorInternal
16992                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16993            if (dsm != null) {
16994                return dsm.isMemoryLow();
16995            } else {
16996                return false;
16997            }
16998        } finally {
16999            Binder.restoreCallingIdentity(token);
17000        }
17001    }
17002
17003    @Override
17004    public IPackageInstaller getPackageInstaller() {
17005        return mInstallerService;
17006    }
17007
17008    private boolean userNeedsBadging(int userId) {
17009        int index = mUserNeedsBadging.indexOfKey(userId);
17010        if (index < 0) {
17011            final UserInfo userInfo;
17012            final long token = Binder.clearCallingIdentity();
17013            try {
17014                userInfo = sUserManager.getUserInfo(userId);
17015            } finally {
17016                Binder.restoreCallingIdentity(token);
17017            }
17018            final boolean b;
17019            if (userInfo != null && userInfo.isManagedProfile()) {
17020                b = true;
17021            } else {
17022                b = false;
17023            }
17024            mUserNeedsBadging.put(userId, b);
17025            return b;
17026        }
17027        return mUserNeedsBadging.valueAt(index);
17028    }
17029
17030    @Override
17031    public KeySet getKeySetByAlias(String packageName, String alias) {
17032        if (packageName == null || alias == null) {
17033            return null;
17034        }
17035        synchronized(mPackages) {
17036            final PackageParser.Package pkg = mPackages.get(packageName);
17037            if (pkg == null) {
17038                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17039                throw new IllegalArgumentException("Unknown package: " + packageName);
17040            }
17041            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17042            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17043        }
17044    }
17045
17046    @Override
17047    public KeySet getSigningKeySet(String packageName) {
17048        if (packageName == null) {
17049            return null;
17050        }
17051        synchronized(mPackages) {
17052            final PackageParser.Package pkg = mPackages.get(packageName);
17053            if (pkg == null) {
17054                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17055                throw new IllegalArgumentException("Unknown package: " + packageName);
17056            }
17057            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17058                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17059                throw new SecurityException("May not access signing KeySet of other apps.");
17060            }
17061            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17062            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17063        }
17064    }
17065
17066    @Override
17067    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17068        if (packageName == null || ks == null) {
17069            return false;
17070        }
17071        synchronized(mPackages) {
17072            final PackageParser.Package pkg = mPackages.get(packageName);
17073            if (pkg == null) {
17074                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17075                throw new IllegalArgumentException("Unknown package: " + packageName);
17076            }
17077            IBinder ksh = ks.getToken();
17078            if (ksh instanceof KeySetHandle) {
17079                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17080                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17081            }
17082            return false;
17083        }
17084    }
17085
17086    @Override
17087    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17088        if (packageName == null || ks == null) {
17089            return false;
17090        }
17091        synchronized(mPackages) {
17092            final PackageParser.Package pkg = mPackages.get(packageName);
17093            if (pkg == null) {
17094                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17095                throw new IllegalArgumentException("Unknown package: " + packageName);
17096            }
17097            IBinder ksh = ks.getToken();
17098            if (ksh instanceof KeySetHandle) {
17099                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17100                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17101            }
17102            return false;
17103        }
17104    }
17105
17106    private void deletePackageIfUnusedLPr(final String packageName) {
17107        PackageSetting ps = mSettings.mPackages.get(packageName);
17108        if (ps == null) {
17109            return;
17110        }
17111        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17112            // TODO Implement atomic delete if package is unused
17113            // It is currently possible that the package will be deleted even if it is installed
17114            // after this method returns.
17115            mHandler.post(new Runnable() {
17116                public void run() {
17117                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17118                }
17119            });
17120        }
17121    }
17122
17123    /**
17124     * Check and throw if the given before/after packages would be considered a
17125     * downgrade.
17126     */
17127    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17128            throws PackageManagerException {
17129        if (after.versionCode < before.mVersionCode) {
17130            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17131                    "Update version code " + after.versionCode + " is older than current "
17132                    + before.mVersionCode);
17133        } else if (after.versionCode == before.mVersionCode) {
17134            if (after.baseRevisionCode < before.baseRevisionCode) {
17135                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17136                        "Update base revision code " + after.baseRevisionCode
17137                        + " is older than current " + before.baseRevisionCode);
17138            }
17139
17140            if (!ArrayUtils.isEmpty(after.splitNames)) {
17141                for (int i = 0; i < after.splitNames.length; i++) {
17142                    final String splitName = after.splitNames[i];
17143                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17144                    if (j != -1) {
17145                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17146                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17147                                    "Update split " + splitName + " revision code "
17148                                    + after.splitRevisionCodes[i] + " is older than current "
17149                                    + before.splitRevisionCodes[j]);
17150                        }
17151                    }
17152                }
17153            }
17154        }
17155    }
17156
17157    private static class MoveCallbacks extends Handler {
17158        private static final int MSG_CREATED = 1;
17159        private static final int MSG_STATUS_CHANGED = 2;
17160
17161        private final RemoteCallbackList<IPackageMoveObserver>
17162                mCallbacks = new RemoteCallbackList<>();
17163
17164        private final SparseIntArray mLastStatus = new SparseIntArray();
17165
17166        public MoveCallbacks(Looper looper) {
17167            super(looper);
17168        }
17169
17170        public void register(IPackageMoveObserver callback) {
17171            mCallbacks.register(callback);
17172        }
17173
17174        public void unregister(IPackageMoveObserver callback) {
17175            mCallbacks.unregister(callback);
17176        }
17177
17178        @Override
17179        public void handleMessage(Message msg) {
17180            final SomeArgs args = (SomeArgs) msg.obj;
17181            final int n = mCallbacks.beginBroadcast();
17182            for (int i = 0; i < n; i++) {
17183                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17184                try {
17185                    invokeCallback(callback, msg.what, args);
17186                } catch (RemoteException ignored) {
17187                }
17188            }
17189            mCallbacks.finishBroadcast();
17190            args.recycle();
17191        }
17192
17193        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17194                throws RemoteException {
17195            switch (what) {
17196                case MSG_CREATED: {
17197                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17198                    break;
17199                }
17200                case MSG_STATUS_CHANGED: {
17201                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17202                    break;
17203                }
17204            }
17205        }
17206
17207        private void notifyCreated(int moveId, Bundle extras) {
17208            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17209
17210            final SomeArgs args = SomeArgs.obtain();
17211            args.argi1 = moveId;
17212            args.arg2 = extras;
17213            obtainMessage(MSG_CREATED, args).sendToTarget();
17214        }
17215
17216        private void notifyStatusChanged(int moveId, int status) {
17217            notifyStatusChanged(moveId, status, -1);
17218        }
17219
17220        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17221            Slog.v(TAG, "Move " + moveId + " status " + status);
17222
17223            final SomeArgs args = SomeArgs.obtain();
17224            args.argi1 = moveId;
17225            args.argi2 = status;
17226            args.arg3 = estMillis;
17227            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17228
17229            synchronized (mLastStatus) {
17230                mLastStatus.put(moveId, status);
17231            }
17232        }
17233    }
17234
17235    private final class OnPermissionChangeListeners extends Handler {
17236        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17237
17238        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17239                new RemoteCallbackList<>();
17240
17241        public OnPermissionChangeListeners(Looper looper) {
17242            super(looper);
17243        }
17244
17245        @Override
17246        public void handleMessage(Message msg) {
17247            switch (msg.what) {
17248                case MSG_ON_PERMISSIONS_CHANGED: {
17249                    final int uid = msg.arg1;
17250                    handleOnPermissionsChanged(uid);
17251                } break;
17252            }
17253        }
17254
17255        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17256            mPermissionListeners.register(listener);
17257
17258        }
17259
17260        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17261            mPermissionListeners.unregister(listener);
17262        }
17263
17264        public void onPermissionsChanged(int uid) {
17265            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17266                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17267            }
17268        }
17269
17270        private void handleOnPermissionsChanged(int uid) {
17271            final int count = mPermissionListeners.beginBroadcast();
17272            try {
17273                for (int i = 0; i < count; i++) {
17274                    IOnPermissionsChangeListener callback = mPermissionListeners
17275                            .getBroadcastItem(i);
17276                    try {
17277                        callback.onPermissionsChanged(uid);
17278                    } catch (RemoteException e) {
17279                        Log.e(TAG, "Permission listener is dead", e);
17280                    }
17281                }
17282            } finally {
17283                mPermissionListeners.finishBroadcast();
17284            }
17285        }
17286    }
17287
17288    private class PackageManagerInternalImpl extends PackageManagerInternal {
17289        @Override
17290        public void setLocationPackagesProvider(PackagesProvider provider) {
17291            synchronized (mPackages) {
17292                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17293            }
17294        }
17295
17296        @Override
17297        public void setImePackagesProvider(PackagesProvider provider) {
17298            synchronized (mPackages) {
17299                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17300            }
17301        }
17302
17303        @Override
17304        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17305            synchronized (mPackages) {
17306                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17307            }
17308        }
17309
17310        @Override
17311        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17312            synchronized (mPackages) {
17313                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17314            }
17315        }
17316
17317        @Override
17318        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17319            synchronized (mPackages) {
17320                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17321            }
17322        }
17323
17324        @Override
17325        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17326            synchronized (mPackages) {
17327                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17328            }
17329        }
17330
17331        @Override
17332        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17333            synchronized (mPackages) {
17334                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17335            }
17336        }
17337
17338        @Override
17339        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17340            synchronized (mPackages) {
17341                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17342                        packageName, userId);
17343            }
17344        }
17345
17346        @Override
17347        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17348            synchronized (mPackages) {
17349                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17350                        packageName, userId);
17351            }
17352        }
17353
17354        @Override
17355        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17356            synchronized (mPackages) {
17357                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17358                        packageName, userId);
17359            }
17360        }
17361
17362        @Override
17363        public void setKeepUninstalledPackages(final List<String> packageList) {
17364            Preconditions.checkNotNull(packageList);
17365            List<String> removedFromList = null;
17366            synchronized (mPackages) {
17367                if (mKeepUninstalledPackages != null) {
17368                    final int packagesCount = mKeepUninstalledPackages.size();
17369                    for (int i = 0; i < packagesCount; i++) {
17370                        String oldPackage = mKeepUninstalledPackages.get(i);
17371                        if (packageList != null && packageList.contains(oldPackage)) {
17372                            continue;
17373                        }
17374                        if (removedFromList == null) {
17375                            removedFromList = new ArrayList<>();
17376                        }
17377                        removedFromList.add(oldPackage);
17378                    }
17379                }
17380                mKeepUninstalledPackages = new ArrayList<>(packageList);
17381                if (removedFromList != null) {
17382                    final int removedCount = removedFromList.size();
17383                    for (int i = 0; i < removedCount; i++) {
17384                        deletePackageIfUnusedLPr(removedFromList.get(i));
17385                    }
17386                }
17387            }
17388        }
17389
17390        @Override
17391        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17392            synchronized (mPackages) {
17393                // If we do not support permission review, done.
17394                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17395                    return false;
17396                }
17397
17398                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17399                if (packageSetting == null) {
17400                    return false;
17401                }
17402
17403                // Permission review applies only to apps not supporting the new permission model.
17404                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17405                    return false;
17406                }
17407
17408                // Legacy apps have the permission and get user consent on launch.
17409                PermissionsState permissionsState = packageSetting.getPermissionsState();
17410                return permissionsState.isPermissionReviewRequired(userId);
17411            }
17412        }
17413    }
17414
17415    @Override
17416    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17417        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17418        synchronized (mPackages) {
17419            final long identity = Binder.clearCallingIdentity();
17420            try {
17421                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17422                        packageNames, userId);
17423            } finally {
17424                Binder.restoreCallingIdentity(identity);
17425            }
17426        }
17427    }
17428
17429    private static void enforceSystemOrPhoneCaller(String tag) {
17430        int callingUid = Binder.getCallingUid();
17431        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17432            throw new SecurityException(
17433                    "Cannot call " + tag + " from UID " + callingUid);
17434        }
17435    }
17436}
17437