PackageManagerService.java revision 9c165d76010d9f79f5cd71978742a335b6b8d1b4
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_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
63import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
64import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
65import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
66import static android.content.pm.PackageManager.PERMISSION_DENIED;
67import static android.content.pm.PackageManager.PERMISSION_GRANTED;
68import static android.content.pm.PackageParser.isApkFile;
69import static android.os.Process.PACKAGE_INFO_GID;
70import static android.os.Process.SYSTEM_UID;
71import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
72import static android.system.OsConstants.O_CREAT;
73import static android.system.OsConstants.O_RDWR;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
76import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
77import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
78import static com.android.internal.util.ArrayUtils.appendInt;
79import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
80import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
83import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
84import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
88
89import android.Manifest;
90import android.app.ActivityManager;
91import android.app.ActivityManagerNative;
92import android.app.AppGlobals;
93import android.app.IActivityManager;
94import android.app.admin.IDevicePolicyManager;
95import android.app.backup.IBackupManager;
96import android.app.usage.UsageStats;
97import android.app.usage.UsageStatsManager;
98import android.content.BroadcastReceiver;
99import android.content.ComponentName;
100import android.content.Context;
101import android.content.IIntentReceiver;
102import android.content.Intent;
103import android.content.IntentFilter;
104import android.content.IntentSender;
105import android.content.IntentSender.SendIntentException;
106import android.content.ServiceConnection;
107import android.content.pm.ActivityInfo;
108import android.content.pm.ApplicationInfo;
109import android.content.pm.AppsQueryHelper;
110import android.content.pm.FeatureInfo;
111import android.content.pm.IOnPermissionsChangeListener;
112import android.content.pm.IPackageDataObserver;
113import android.content.pm.IPackageDeleteObserver;
114import android.content.pm.IPackageDeleteObserver2;
115import android.content.pm.IPackageInstallObserver2;
116import android.content.pm.IPackageInstaller;
117import android.content.pm.IPackageManager;
118import android.content.pm.IPackageMoveObserver;
119import android.content.pm.IPackageStatsObserver;
120import android.content.pm.InstrumentationInfo;
121import android.content.pm.IntentFilterVerificationInfo;
122import android.content.pm.KeySet;
123import android.content.pm.ManifestDigest;
124import android.content.pm.PackageCleanItem;
125import android.content.pm.PackageInfo;
126import android.content.pm.PackageInfoLite;
127import android.content.pm.PackageInstaller;
128import android.content.pm.PackageManager;
129import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
130import android.content.pm.PackageManagerInternal;
131import android.content.pm.PackageParser;
132import android.content.pm.PackageParser.ActivityIntentInfo;
133import android.content.pm.PackageParser.PackageLite;
134import android.content.pm.PackageParser.PackageParserException;
135import android.content.pm.PackageStats;
136import android.content.pm.PackageUserState;
137import android.content.pm.ParceledListSlice;
138import android.content.pm.PermissionGroupInfo;
139import android.content.pm.PermissionInfo;
140import android.content.pm.ProviderInfo;
141import android.content.pm.ResolveInfo;
142import android.content.pm.ServiceInfo;
143import android.content.pm.Signature;
144import android.content.pm.UserInfo;
145import android.content.pm.VerificationParams;
146import android.content.pm.VerifierDeviceIdentity;
147import android.content.pm.VerifierInfo;
148import android.content.res.Resources;
149import android.hardware.display.DisplayManager;
150import android.net.Uri;
151import android.os.Debug;
152import android.os.Binder;
153import android.os.Build;
154import android.os.Bundle;
155import android.os.Environment;
156import android.os.Environment.UserEnvironment;
157import android.os.FileUtils;
158import android.os.Handler;
159import android.os.IBinder;
160import android.os.Looper;
161import android.os.Message;
162import android.os.Parcel;
163import android.os.ParcelFileDescriptor;
164import android.os.Process;
165import android.os.RemoteCallbackList;
166import android.os.RemoteException;
167import android.os.ResultReceiver;
168import android.os.SELinux;
169import android.os.ServiceManager;
170import android.os.SystemClock;
171import android.os.SystemProperties;
172import android.os.Trace;
173import android.os.UserHandle;
174import android.os.UserManager;
175import android.os.storage.IMountService;
176import android.os.storage.MountServiceInternal;
177import android.os.storage.StorageEventListener;
178import android.os.storage.StorageManager;
179import android.os.storage.VolumeInfo;
180import android.os.storage.VolumeRecord;
181import android.security.KeyStore;
182import android.security.SystemKeyStore;
183import android.system.ErrnoException;
184import android.system.Os;
185import android.system.StructStat;
186import android.text.TextUtils;
187import android.text.format.DateUtils;
188import android.util.ArrayMap;
189import android.util.ArraySet;
190import android.util.AtomicFile;
191import android.util.DisplayMetrics;
192import android.util.EventLog;
193import android.util.ExceptionUtils;
194import android.util.Log;
195import android.util.LogPrinter;
196import android.util.MathUtils;
197import android.util.PrintStreamPrinter;
198import android.util.Slog;
199import android.util.SparseArray;
200import android.util.SparseBooleanArray;
201import android.util.SparseIntArray;
202import android.util.Xml;
203import android.view.Display;
204
205import dalvik.system.DexFile;
206import dalvik.system.VMRuntime;
207
208import libcore.io.IoUtils;
209import libcore.util.EmptyArray;
210
211import com.android.internal.R;
212import com.android.internal.annotations.GuardedBy;
213import com.android.internal.app.EphemeralResolveInfo;
214import com.android.internal.app.IMediaContainerService;
215import com.android.internal.app.ResolverActivity;
216import com.android.internal.content.NativeLibraryHelper;
217import com.android.internal.content.PackageHelper;
218import com.android.internal.os.IParcelFileDescriptorFactory;
219import com.android.internal.os.SomeArgs;
220import com.android.internal.os.Zygote;
221import com.android.internal.util.ArrayUtils;
222import com.android.internal.util.FastPrintWriter;
223import com.android.internal.util.FastXmlSerializer;
224import com.android.internal.util.IndentingPrintWriter;
225import com.android.internal.util.Preconditions;
226import com.android.server.EventLogTags;
227import com.android.server.FgThread;
228import com.android.server.IntentResolver;
229import com.android.server.LocalServices;
230import com.android.server.ServiceThread;
231import com.android.server.SystemConfig;
232import com.android.server.Watchdog;
233import com.android.server.pm.PermissionsState.PermissionState;
234import com.android.server.pm.Settings.DatabaseVersion;
235import com.android.server.pm.Settings.VersionInfo;
236import com.android.server.storage.DeviceStorageMonitorInternal;
237
238import org.xmlpull.v1.XmlPullParser;
239import org.xmlpull.v1.XmlPullParserException;
240import org.xmlpull.v1.XmlSerializer;
241
242import java.io.BufferedInputStream;
243import java.io.BufferedOutputStream;
244import java.io.BufferedReader;
245import java.io.ByteArrayInputStream;
246import java.io.ByteArrayOutputStream;
247import java.io.File;
248import java.io.FileDescriptor;
249import java.io.FileNotFoundException;
250import java.io.FileOutputStream;
251import java.io.FileReader;
252import java.io.FilenameFilter;
253import java.io.IOException;
254import java.io.InputStream;
255import java.io.PrintWriter;
256import java.nio.charset.StandardCharsets;
257import java.security.MessageDigest;
258import java.security.NoSuchAlgorithmException;
259import java.security.PublicKey;
260import java.security.cert.CertificateEncodingException;
261import java.security.cert.CertificateException;
262import java.text.SimpleDateFormat;
263import java.util.ArrayList;
264import java.util.Arrays;
265import java.util.Collection;
266import java.util.Collections;
267import java.util.Comparator;
268import java.util.Date;
269import java.util.Iterator;
270import java.util.List;
271import java.util.Map;
272import java.util.Objects;
273import java.util.Set;
274import java.util.concurrent.CountDownLatch;
275import java.util.concurrent.TimeUnit;
276import java.util.concurrent.atomic.AtomicBoolean;
277import java.util.concurrent.atomic.AtomicInteger;
278import java.util.concurrent.atomic.AtomicLong;
279
280/**
281 * Keep track of all those .apks everywhere.
282 *
283 * This is very central to the platform's security; please run the unit
284 * tests whenever making modifications here:
285 *
286runtest -c android.content.pm.PackageManagerTests frameworks-core
287 *
288 * {@hide}
289 */
290public class PackageManagerService extends IPackageManager.Stub {
291    static final String TAG = "PackageManager";
292    static final boolean DEBUG_SETTINGS = false;
293    static final boolean DEBUG_PREFERRED = false;
294    static final boolean DEBUG_UPGRADE = false;
295    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
296    private static final boolean DEBUG_BACKUP = false;
297    private static final boolean DEBUG_INSTALL = false;
298    private static final boolean DEBUG_REMOVE = false;
299    private static final boolean DEBUG_BROADCASTS = false;
300    private static final boolean DEBUG_SHOW_INFO = false;
301    private static final boolean DEBUG_PACKAGE_INFO = false;
302    private static final boolean DEBUG_INTENT_MATCHING = false;
303    private static final boolean DEBUG_PACKAGE_SCANNING = false;
304    private static final boolean DEBUG_VERIFY = false;
305    private static final boolean DEBUG_DEXOPT = false;
306    private static final boolean DEBUG_ABI_SELECTION = false;
307    private static final boolean DEBUG_EPHEMERAL = false;
308
309    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
310
311    private static final int RADIO_UID = Process.PHONE_UID;
312    private static final int LOG_UID = Process.LOG_UID;
313    private static final int NFC_UID = Process.NFC_UID;
314    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
315    private static final int SHELL_UID = Process.SHELL_UID;
316
317    // Cap the size of permission trees that 3rd party apps can define
318    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
319
320    // Suffix used during package installation when copying/moving
321    // package apks to install directory.
322    private static final String INSTALL_PACKAGE_SUFFIX = "-";
323
324    static final int SCAN_NO_DEX = 1<<1;
325    static final int SCAN_FORCE_DEX = 1<<2;
326    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
327    static final int SCAN_NEW_INSTALL = 1<<4;
328    static final int SCAN_NO_PATHS = 1<<5;
329    static final int SCAN_UPDATE_TIME = 1<<6;
330    static final int SCAN_DEFER_DEX = 1<<7;
331    static final int SCAN_BOOTING = 1<<8;
332    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
333    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
334    static final int SCAN_REPLACING = 1<<11;
335    static final int SCAN_REQUIRE_KNOWN = 1<<12;
336    static final int SCAN_MOVE = 1<<13;
337    static final int SCAN_INITIAL = 1<<14;
338
339    static final int REMOVE_CHATTY = 1<<16;
340
341    private static final int[] EMPTY_INT_ARRAY = new int[0];
342
343    /**
344     * Timeout (in milliseconds) after which the watchdog should declare that
345     * our handler thread is wedged.  The usual default for such things is one
346     * minute but we sometimes do very lengthy I/O operations on this thread,
347     * such as installing multi-gigabyte applications, so ours needs to be longer.
348     */
349    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
350
351    /**
352     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
353     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
354     * settings entry if available, otherwise we use the hardcoded default.  If it's been
355     * more than this long since the last fstrim, we force one during the boot sequence.
356     *
357     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
358     * one gets run at the next available charging+idle time.  This final mandatory
359     * no-fstrim check kicks in only of the other scheduling criteria is never met.
360     */
361    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
362
363    /**
364     * Whether verification is enabled by default.
365     */
366    private static final boolean DEFAULT_VERIFY_ENABLE = true;
367
368    /**
369     * The default maximum time to wait for the verification agent to return in
370     * milliseconds.
371     */
372    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
373
374    /**
375     * The default response for package verification timeout.
376     *
377     * This can be either PackageManager.VERIFICATION_ALLOW or
378     * PackageManager.VERIFICATION_REJECT.
379     */
380    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
381
382    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
383
384    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
385            DEFAULT_CONTAINER_PACKAGE,
386            "com.android.defcontainer.DefaultContainerService");
387
388    private static final String KILL_APP_REASON_GIDS_CHANGED =
389            "permission grant or revoke changed gids";
390
391    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
392            "permissions revoked";
393
394    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
395
396    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
397
398    /** Permission grant: not grant the permission. */
399    private static final int GRANT_DENIED = 1;
400
401    /** Permission grant: grant the permission as an install permission. */
402    private static final int GRANT_INSTALL = 2;
403
404    /** Permission grant: grant the permission as a runtime one. */
405    private static final int GRANT_RUNTIME = 3;
406
407    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
408    private static final int GRANT_UPGRADE = 4;
409
410    /** Canonical intent used to identify what counts as a "web browser" app */
411    private static final Intent sBrowserIntent;
412    static {
413        sBrowserIntent = new Intent();
414        sBrowserIntent.setAction(Intent.ACTION_VIEW);
415        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
416        sBrowserIntent.setData(Uri.parse("http:"));
417    }
418
419    final ServiceThread mHandlerThread;
420
421    final PackageHandler mHandler;
422
423    /**
424     * Messages for {@link #mHandler} that need to wait for system ready before
425     * being dispatched.
426     */
427    private ArrayList<Message> mPostSystemReadyMessages;
428
429    final int mSdkVersion = Build.VERSION.SDK_INT;
430
431    final Context mContext;
432    final boolean mFactoryTest;
433    final boolean mOnlyCore;
434    final DisplayMetrics mMetrics;
435    final int mDefParseFlags;
436    final String[] mSeparateProcesses;
437    final boolean mIsUpgrade;
438
439    // This is where all application persistent data goes.
440    final File mAppDataDir;
441
442    // This is where all application persistent data goes for secondary users.
443    final File mUserAppDataDir;
444
445    /** The location for ASEC container files on internal storage. */
446    final String mAsecInternalPath;
447
448    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
449    // LOCK HELD.  Can be called with mInstallLock held.
450    @GuardedBy("mInstallLock")
451    final Installer mInstaller;
452
453    /** Directory where installed third-party apps stored */
454    final File mAppInstallDir;
455
456    /**
457     * Directory to which applications installed internally have their
458     * 32 bit native libraries copied.
459     */
460    private File mAppLib32InstallDir;
461
462    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
463    // apps.
464    final File mDrmAppPrivateInstallDir;
465
466    // ----------------------------------------------------------------
467
468    // Lock for state used when installing and doing other long running
469    // operations.  Methods that must be called with this lock held have
470    // the suffix "LI".
471    final Object mInstallLock = new Object();
472
473    // ----------------------------------------------------------------
474
475    // Keys are String (package name), values are Package.  This also serves
476    // as the lock for the global state.  Methods that must be called with
477    // this lock held have the prefix "LP".
478    @GuardedBy("mPackages")
479    final ArrayMap<String, PackageParser.Package> mPackages =
480            new ArrayMap<String, PackageParser.Package>();
481
482    // Tracks available target package names -> overlay package paths.
483    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
484        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
485
486    /**
487     * Tracks new system packages [received in an OTA] that we expect to
488     * find updated user-installed versions. Keys are package name, values
489     * are package location.
490     */
491    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
492
493    /**
494     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
495     */
496    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
497    /**
498     * Whether or not system app permissions should be promoted from install to runtime.
499     */
500    boolean mPromoteSystemApps;
501
502    final Settings mSettings;
503    boolean mRestoredSettings;
504
505    // System configuration read by SystemConfig.
506    final int[] mGlobalGids;
507    final SparseArray<ArraySet<String>> mSystemPermissions;
508    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
509
510    // If mac_permissions.xml was found for seinfo labeling.
511    boolean mFoundPolicyFile;
512
513    // If a recursive restorecon of /data/data/<pkg> is needed.
514    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
515
516    public static final class SharedLibraryEntry {
517        public final String path;
518        public final String apk;
519
520        SharedLibraryEntry(String _path, String _apk) {
521            path = _path;
522            apk = _apk;
523        }
524    }
525
526    // Currently known shared libraries.
527    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
528            new ArrayMap<String, SharedLibraryEntry>();
529
530    // All available activities, for your resolving pleasure.
531    final ActivityIntentResolver mActivities =
532            new ActivityIntentResolver();
533
534    // All available receivers, for your resolving pleasure.
535    final ActivityIntentResolver mReceivers =
536            new ActivityIntentResolver();
537
538    // All available services, for your resolving pleasure.
539    final ServiceIntentResolver mServices = new ServiceIntentResolver();
540
541    // All available providers, for your resolving pleasure.
542    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
543
544    // Mapping from provider base names (first directory in content URI codePath)
545    // to the provider information.
546    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
547            new ArrayMap<String, PackageParser.Provider>();
548
549    // Mapping from instrumentation class names to info about them.
550    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
551            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
552
553    // Mapping from permission names to info about them.
554    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
555            new ArrayMap<String, PackageParser.PermissionGroup>();
556
557    // Packages whose data we have transfered into another package, thus
558    // should no longer exist.
559    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
560
561    // Broadcast actions that are only available to the system.
562    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
563
564    /** List of packages waiting for verification. */
565    final SparseArray<PackageVerificationState> mPendingVerification
566            = new SparseArray<PackageVerificationState>();
567
568    /** Set of packages associated with each app op permission. */
569    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
570
571    final PackageInstallerService mInstallerService;
572
573    private final PackageDexOptimizer mPackageDexOptimizer;
574
575    private AtomicInteger mNextMoveId = new AtomicInteger();
576    private final MoveCallbacks mMoveCallbacks;
577
578    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
579
580    // Cache of users who need badging.
581    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
582
583    /** Token for keys in mPendingVerification. */
584    private int mPendingVerificationToken = 0;
585
586    volatile boolean mSystemReady;
587    volatile boolean mSafeMode;
588    volatile boolean mHasSystemUidErrors;
589
590    ApplicationInfo mAndroidApplication;
591    final ActivityInfo mResolveActivity = new ActivityInfo();
592    final ResolveInfo mResolveInfo = new ResolveInfo();
593    ComponentName mResolveComponentName;
594    PackageParser.Package mPlatformPackage;
595    ComponentName mCustomResolverComponentName;
596
597    boolean mResolverReplaced = false;
598
599    private final ComponentName mIntentFilterVerifierComponent;
600    private int mIntentFilterVerificationToken = 0;
601
602    /** Component that knows whether or not an ephemeral application exists */
603    final ComponentName mEphemeralResolverComponent;
604    /** The service connection to the ephemeral resolver */
605    final EphemeralResolverConnection mEphemeralResolverConnection;
606
607    /** Component used to install ephemeral applications */
608    final ComponentName mEphemeralInstallerComponent;
609    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
610    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
611
612    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
613            = new SparseArray<IntentFilterVerificationState>();
614
615    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
616            new DefaultPermissionGrantPolicy(this);
617
618    // List of packages names to keep cached, even if they are uninstalled for all users
619    private List<String> mKeepUninstalledPackages;
620
621    private static class IFVerificationParams {
622        PackageParser.Package pkg;
623        boolean replacing;
624        int userId;
625        int verifierUid;
626
627        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
628                int _userId, int _verifierUid) {
629            pkg = _pkg;
630            replacing = _replacing;
631            userId = _userId;
632            replacing = _replacing;
633            verifierUid = _verifierUid;
634        }
635    }
636
637    private interface IntentFilterVerifier<T extends IntentFilter> {
638        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
639                                               T filter, String packageName);
640        void startVerifications(int userId);
641        void receiveVerificationResponse(int verificationId);
642    }
643
644    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
645        private Context mContext;
646        private ComponentName mIntentFilterVerifierComponent;
647        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
648
649        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
650            mContext = context;
651            mIntentFilterVerifierComponent = verifierComponent;
652        }
653
654        private String getDefaultScheme() {
655            return IntentFilter.SCHEME_HTTPS;
656        }
657
658        @Override
659        public void startVerifications(int userId) {
660            // Launch verifications requests
661            int count = mCurrentIntentFilterVerifications.size();
662            for (int n=0; n<count; n++) {
663                int verificationId = mCurrentIntentFilterVerifications.get(n);
664                final IntentFilterVerificationState ivs =
665                        mIntentFilterVerificationStates.get(verificationId);
666
667                String packageName = ivs.getPackageName();
668
669                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
670                final int filterCount = filters.size();
671                ArraySet<String> domainsSet = new ArraySet<>();
672                for (int m=0; m<filterCount; m++) {
673                    PackageParser.ActivityIntentInfo filter = filters.get(m);
674                    domainsSet.addAll(filter.getHostsList());
675                }
676                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
677                synchronized (mPackages) {
678                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
679                            packageName, domainsList) != null) {
680                        scheduleWriteSettingsLocked();
681                    }
682                }
683                sendVerificationRequest(userId, verificationId, ivs);
684            }
685            mCurrentIntentFilterVerifications.clear();
686        }
687
688        private void sendVerificationRequest(int userId, int verificationId,
689                IntentFilterVerificationState ivs) {
690
691            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
692            verificationIntent.putExtra(
693                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
694                    verificationId);
695            verificationIntent.putExtra(
696                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
697                    getDefaultScheme());
698            verificationIntent.putExtra(
699                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
700                    ivs.getHostsString());
701            verificationIntent.putExtra(
702                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
703                    ivs.getPackageName());
704            verificationIntent.setComponent(mIntentFilterVerifierComponent);
705            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
706
707            UserHandle user = new UserHandle(userId);
708            mContext.sendBroadcastAsUser(verificationIntent, user);
709            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
710                    "Sending IntentFilter verification broadcast");
711        }
712
713        public void receiveVerificationResponse(int verificationId) {
714            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
715
716            final boolean verified = ivs.isVerified();
717
718            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
719            final int count = filters.size();
720            if (DEBUG_DOMAIN_VERIFICATION) {
721                Slog.i(TAG, "Received verification response " + verificationId
722                        + " for " + count + " filters, verified=" + verified);
723            }
724            for (int n=0; n<count; n++) {
725                PackageParser.ActivityIntentInfo filter = filters.get(n);
726                filter.setVerified(verified);
727
728                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
729                        + " verified with result:" + verified + " and hosts:"
730                        + ivs.getHostsString());
731            }
732
733            mIntentFilterVerificationStates.remove(verificationId);
734
735            final String packageName = ivs.getPackageName();
736            IntentFilterVerificationInfo ivi = null;
737
738            synchronized (mPackages) {
739                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
740            }
741            if (ivi == null) {
742                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
743                        + verificationId + " packageName:" + packageName);
744                return;
745            }
746            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
747                    "Updating IntentFilterVerificationInfo for package " + packageName
748                            +" verificationId:" + verificationId);
749
750            synchronized (mPackages) {
751                if (verified) {
752                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
753                } else {
754                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
755                }
756                scheduleWriteSettingsLocked();
757
758                final int userId = ivs.getUserId();
759                if (userId != UserHandle.USER_ALL) {
760                    final int userStatus =
761                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
762
763                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
764                    boolean needUpdate = false;
765
766                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
767                    // already been set by the User thru the Disambiguation dialog
768                    switch (userStatus) {
769                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
770                            if (verified) {
771                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
772                            } else {
773                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
774                            }
775                            needUpdate = true;
776                            break;
777
778                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
779                            if (verified) {
780                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
781                                needUpdate = true;
782                            }
783                            break;
784
785                        default:
786                            // Nothing to do
787                    }
788
789                    if (needUpdate) {
790                        mSettings.updateIntentFilterVerificationStatusLPw(
791                                packageName, updatedStatus, userId);
792                        scheduleWritePackageRestrictionsLocked(userId);
793                    }
794                }
795            }
796        }
797
798        @Override
799        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
800                    ActivityIntentInfo filter, String packageName) {
801            if (!hasValidDomains(filter)) {
802                return false;
803            }
804            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
805            if (ivs == null) {
806                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
807                        packageName);
808            }
809            if (DEBUG_DOMAIN_VERIFICATION) {
810                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
811            }
812            ivs.addFilter(filter);
813            return true;
814        }
815
816        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
817                int userId, int verificationId, String packageName) {
818            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
819                    verifierUid, userId, packageName);
820            ivs.setPendingState();
821            synchronized (mPackages) {
822                mIntentFilterVerificationStates.append(verificationId, ivs);
823                mCurrentIntentFilterVerifications.add(verificationId);
824            }
825            return ivs;
826        }
827    }
828
829    private static boolean hasValidDomains(ActivityIntentInfo filter) {
830        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
831                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
832                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
833    }
834
835    private IntentFilterVerifier mIntentFilterVerifier;
836
837    // Set of pending broadcasts for aggregating enable/disable of components.
838    static class PendingPackageBroadcasts {
839        // for each user id, a map of <package name -> components within that package>
840        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
841
842        public PendingPackageBroadcasts() {
843            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
844        }
845
846        public ArrayList<String> get(int userId, String packageName) {
847            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
848            return packages.get(packageName);
849        }
850
851        public void put(int userId, String packageName, ArrayList<String> components) {
852            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
853            packages.put(packageName, components);
854        }
855
856        public void remove(int userId, String packageName) {
857            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
858            if (packages != null) {
859                packages.remove(packageName);
860            }
861        }
862
863        public void remove(int userId) {
864            mUidMap.remove(userId);
865        }
866
867        public int userIdCount() {
868            return mUidMap.size();
869        }
870
871        public int userIdAt(int n) {
872            return mUidMap.keyAt(n);
873        }
874
875        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
876            return mUidMap.get(userId);
877        }
878
879        public int size() {
880            // total number of pending broadcast entries across all userIds
881            int num = 0;
882            for (int i = 0; i< mUidMap.size(); i++) {
883                num += mUidMap.valueAt(i).size();
884            }
885            return num;
886        }
887
888        public void clear() {
889            mUidMap.clear();
890        }
891
892        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
893            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
894            if (map == null) {
895                map = new ArrayMap<String, ArrayList<String>>();
896                mUidMap.put(userId, map);
897            }
898            return map;
899        }
900    }
901    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
902
903    // Service Connection to remote media container service to copy
904    // package uri's from external media onto secure containers
905    // or internal storage.
906    private IMediaContainerService mContainerService = null;
907
908    static final int SEND_PENDING_BROADCAST = 1;
909    static final int MCS_BOUND = 3;
910    static final int END_COPY = 4;
911    static final int INIT_COPY = 5;
912    static final int MCS_UNBIND = 6;
913    static final int START_CLEANING_PACKAGE = 7;
914    static final int FIND_INSTALL_LOC = 8;
915    static final int POST_INSTALL = 9;
916    static final int MCS_RECONNECT = 10;
917    static final int MCS_GIVE_UP = 11;
918    static final int UPDATED_MEDIA_STATUS = 12;
919    static final int WRITE_SETTINGS = 13;
920    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
921    static final int PACKAGE_VERIFIED = 15;
922    static final int CHECK_PENDING_VERIFICATION = 16;
923    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
924    static final int INTENT_FILTER_VERIFIED = 18;
925
926    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
927
928    // Delay time in millisecs
929    static final int BROADCAST_DELAY = 10 * 1000;
930
931    static UserManagerService sUserManager;
932
933    // Stores a list of users whose package restrictions file needs to be updated
934    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
935
936    final private DefaultContainerConnection mDefContainerConn =
937            new DefaultContainerConnection();
938    class DefaultContainerConnection implements ServiceConnection {
939        public void onServiceConnected(ComponentName name, IBinder service) {
940            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
941            IMediaContainerService imcs =
942                IMediaContainerService.Stub.asInterface(service);
943            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
944        }
945
946        public void onServiceDisconnected(ComponentName name) {
947            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
948        }
949    }
950
951    // Recordkeeping of restore-after-install operations that are currently in flight
952    // between the Package Manager and the Backup Manager
953    class PostInstallData {
954        public InstallArgs args;
955        public PackageInstalledInfo res;
956
957        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
958            args = _a;
959            res = _r;
960        }
961    }
962
963    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
964    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
965
966    // XML tags for backup/restore of various bits of state
967    private static final String TAG_PREFERRED_BACKUP = "pa";
968    private static final String TAG_DEFAULT_APPS = "da";
969    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
970
971    final String mRequiredVerifierPackage;
972    final String mRequiredInstallerPackage;
973
974    private final PackageUsage mPackageUsage = new PackageUsage();
975
976    private class PackageUsage {
977        private static final int WRITE_INTERVAL
978            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
979
980        private final Object mFileLock = new Object();
981        private final AtomicLong mLastWritten = new AtomicLong(0);
982        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
983
984        private boolean mIsHistoricalPackageUsageAvailable = true;
985
986        boolean isHistoricalPackageUsageAvailable() {
987            return mIsHistoricalPackageUsageAvailable;
988        }
989
990        void write(boolean force) {
991            if (force) {
992                writeInternal();
993                return;
994            }
995            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
996                && !DEBUG_DEXOPT) {
997                return;
998            }
999            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1000                new Thread("PackageUsage_DiskWriter") {
1001                    @Override
1002                    public void run() {
1003                        try {
1004                            writeInternal();
1005                        } finally {
1006                            mBackgroundWriteRunning.set(false);
1007                        }
1008                    }
1009                }.start();
1010            }
1011        }
1012
1013        private void writeInternal() {
1014            synchronized (mPackages) {
1015                synchronized (mFileLock) {
1016                    AtomicFile file = getFile();
1017                    FileOutputStream f = null;
1018                    try {
1019                        f = file.startWrite();
1020                        BufferedOutputStream out = new BufferedOutputStream(f);
1021                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1022                        StringBuilder sb = new StringBuilder();
1023                        for (PackageParser.Package pkg : mPackages.values()) {
1024                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1025                                continue;
1026                            }
1027                            sb.setLength(0);
1028                            sb.append(pkg.packageName);
1029                            sb.append(' ');
1030                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1031                            sb.append('\n');
1032                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1033                        }
1034                        out.flush();
1035                        file.finishWrite(f);
1036                    } catch (IOException e) {
1037                        if (f != null) {
1038                            file.failWrite(f);
1039                        }
1040                        Log.e(TAG, "Failed to write package usage times", e);
1041                    }
1042                }
1043            }
1044            mLastWritten.set(SystemClock.elapsedRealtime());
1045        }
1046
1047        void readLP() {
1048            synchronized (mFileLock) {
1049                AtomicFile file = getFile();
1050                BufferedInputStream in = null;
1051                try {
1052                    in = new BufferedInputStream(file.openRead());
1053                    StringBuffer sb = new StringBuffer();
1054                    while (true) {
1055                        String packageName = readToken(in, sb, ' ');
1056                        if (packageName == null) {
1057                            break;
1058                        }
1059                        String timeInMillisString = readToken(in, sb, '\n');
1060                        if (timeInMillisString == null) {
1061                            throw new IOException("Failed to find last usage time for package "
1062                                                  + packageName);
1063                        }
1064                        PackageParser.Package pkg = mPackages.get(packageName);
1065                        if (pkg == null) {
1066                            continue;
1067                        }
1068                        long timeInMillis;
1069                        try {
1070                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1071                        } catch (NumberFormatException e) {
1072                            throw new IOException("Failed to parse " + timeInMillisString
1073                                                  + " as a long.", e);
1074                        }
1075                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1076                    }
1077                } catch (FileNotFoundException expected) {
1078                    mIsHistoricalPackageUsageAvailable = false;
1079                } catch (IOException e) {
1080                    Log.w(TAG, "Failed to read package usage times", e);
1081                } finally {
1082                    IoUtils.closeQuietly(in);
1083                }
1084            }
1085            mLastWritten.set(SystemClock.elapsedRealtime());
1086        }
1087
1088        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1089                throws IOException {
1090            sb.setLength(0);
1091            while (true) {
1092                int ch = in.read();
1093                if (ch == -1) {
1094                    if (sb.length() == 0) {
1095                        return null;
1096                    }
1097                    throw new IOException("Unexpected EOF");
1098                }
1099                if (ch == endOfToken) {
1100                    return sb.toString();
1101                }
1102                sb.append((char)ch);
1103            }
1104        }
1105
1106        private AtomicFile getFile() {
1107            File dataDir = Environment.getDataDirectory();
1108            File systemDir = new File(dataDir, "system");
1109            File fname = new File(systemDir, "package-usage.list");
1110            return new AtomicFile(fname);
1111        }
1112    }
1113
1114    class PackageHandler extends Handler {
1115        private boolean mBound = false;
1116        final ArrayList<HandlerParams> mPendingInstalls =
1117            new ArrayList<HandlerParams>();
1118
1119        private boolean connectToService() {
1120            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1121                    " DefaultContainerService");
1122            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1123            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1125                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1126                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1127                mBound = true;
1128                return true;
1129            }
1130            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1131            return false;
1132        }
1133
1134        private void disconnectService() {
1135            mContainerService = null;
1136            mBound = false;
1137            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1138            mContext.unbindService(mDefContainerConn);
1139            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1140        }
1141
1142        PackageHandler(Looper looper) {
1143            super(looper);
1144        }
1145
1146        public void handleMessage(Message msg) {
1147            try {
1148                doHandleMessage(msg);
1149            } finally {
1150                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1151            }
1152        }
1153
1154        void doHandleMessage(Message msg) {
1155            switch (msg.what) {
1156                case INIT_COPY: {
1157                    HandlerParams params = (HandlerParams) msg.obj;
1158                    int idx = mPendingInstalls.size();
1159                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1160                    // If a bind was already initiated we dont really
1161                    // need to do anything. The pending install
1162                    // will be processed later on.
1163                    if (!mBound) {
1164                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1165                                System.identityHashCode(mHandler));
1166                        // If this is the only one pending we might
1167                        // have to bind to the service again.
1168                        if (!connectToService()) {
1169                            Slog.e(TAG, "Failed to bind to media container service");
1170                            params.serviceError();
1171                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1172                                    System.identityHashCode(mHandler));
1173                            if (params.traceMethod != null) {
1174                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1175                                        params.traceCookie);
1176                            }
1177                            return;
1178                        } else {
1179                            // Once we bind to the service, the first
1180                            // pending request will be processed.
1181                            mPendingInstalls.add(idx, params);
1182                        }
1183                    } else {
1184                        mPendingInstalls.add(idx, params);
1185                        // Already bound to the service. Just make
1186                        // sure we trigger off processing the first request.
1187                        if (idx == 0) {
1188                            mHandler.sendEmptyMessage(MCS_BOUND);
1189                        }
1190                    }
1191                    break;
1192                }
1193                case MCS_BOUND: {
1194                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1195                    if (msg.obj != null) {
1196                        mContainerService = (IMediaContainerService) msg.obj;
1197                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1198                                System.identityHashCode(mHandler));
1199                    }
1200                    if (mContainerService == null) {
1201                        if (!mBound) {
1202                            // Something seriously wrong since we are not bound and we are not
1203                            // waiting for connection. Bail out.
1204                            Slog.e(TAG, "Cannot bind to media container service");
1205                            for (HandlerParams params : mPendingInstalls) {
1206                                // Indicate service bind error
1207                                params.serviceError();
1208                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1209                                        System.identityHashCode(params));
1210                                if (params.traceMethod != null) {
1211                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1212                                            params.traceMethod, params.traceCookie);
1213                                }
1214                                return;
1215                            }
1216                            mPendingInstalls.clear();
1217                        } else {
1218                            Slog.w(TAG, "Waiting to connect to media container service");
1219                        }
1220                    } else if (mPendingInstalls.size() > 0) {
1221                        HandlerParams params = mPendingInstalls.get(0);
1222                        if (params != null) {
1223                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1224                                    System.identityHashCode(params));
1225                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1226                            if (params.startCopy()) {
1227                                // We are done...  look for more work or to
1228                                // go idle.
1229                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1230                                        "Checking for more work or unbind...");
1231                                // Delete pending install
1232                                if (mPendingInstalls.size() > 0) {
1233                                    mPendingInstalls.remove(0);
1234                                }
1235                                if (mPendingInstalls.size() == 0) {
1236                                    if (mBound) {
1237                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1238                                                "Posting delayed MCS_UNBIND");
1239                                        removeMessages(MCS_UNBIND);
1240                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1241                                        // Unbind after a little delay, to avoid
1242                                        // continual thrashing.
1243                                        sendMessageDelayed(ubmsg, 10000);
1244                                    }
1245                                } else {
1246                                    // There are more pending requests in queue.
1247                                    // Just post MCS_BOUND message to trigger processing
1248                                    // of next pending install.
1249                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1250                                            "Posting MCS_BOUND for next work");
1251                                    mHandler.sendEmptyMessage(MCS_BOUND);
1252                                }
1253                            }
1254                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1255                        }
1256                    } else {
1257                        // Should never happen ideally.
1258                        Slog.w(TAG, "Empty queue");
1259                    }
1260                    break;
1261                }
1262                case MCS_RECONNECT: {
1263                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1264                    if (mPendingInstalls.size() > 0) {
1265                        if (mBound) {
1266                            disconnectService();
1267                        }
1268                        if (!connectToService()) {
1269                            Slog.e(TAG, "Failed to bind to media container service");
1270                            for (HandlerParams params : mPendingInstalls) {
1271                                // Indicate service bind error
1272                                params.serviceError();
1273                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1274                                        System.identityHashCode(params));
1275                            }
1276                            mPendingInstalls.clear();
1277                        }
1278                    }
1279                    break;
1280                }
1281                case MCS_UNBIND: {
1282                    // If there is no actual work left, then time to unbind.
1283                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1284
1285                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1286                        if (mBound) {
1287                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1288
1289                            disconnectService();
1290                        }
1291                    } else if (mPendingInstalls.size() > 0) {
1292                        // There are more pending requests in queue.
1293                        // Just post MCS_BOUND message to trigger processing
1294                        // of next pending install.
1295                        mHandler.sendEmptyMessage(MCS_BOUND);
1296                    }
1297
1298                    break;
1299                }
1300                case MCS_GIVE_UP: {
1301                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1302                    HandlerParams params = mPendingInstalls.remove(0);
1303                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1304                            System.identityHashCode(params));
1305                    break;
1306                }
1307                case SEND_PENDING_BROADCAST: {
1308                    String packages[];
1309                    ArrayList<String> components[];
1310                    int size = 0;
1311                    int uids[];
1312                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1313                    synchronized (mPackages) {
1314                        if (mPendingBroadcasts == null) {
1315                            return;
1316                        }
1317                        size = mPendingBroadcasts.size();
1318                        if (size <= 0) {
1319                            // Nothing to be done. Just return
1320                            return;
1321                        }
1322                        packages = new String[size];
1323                        components = new ArrayList[size];
1324                        uids = new int[size];
1325                        int i = 0;  // filling out the above arrays
1326
1327                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1328                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1329                            Iterator<Map.Entry<String, ArrayList<String>>> it
1330                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1331                                            .entrySet().iterator();
1332                            while (it.hasNext() && i < size) {
1333                                Map.Entry<String, ArrayList<String>> ent = it.next();
1334                                packages[i] = ent.getKey();
1335                                components[i] = ent.getValue();
1336                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1337                                uids[i] = (ps != null)
1338                                        ? UserHandle.getUid(packageUserId, ps.appId)
1339                                        : -1;
1340                                i++;
1341                            }
1342                        }
1343                        size = i;
1344                        mPendingBroadcasts.clear();
1345                    }
1346                    // Send broadcasts
1347                    for (int i = 0; i < size; i++) {
1348                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1349                    }
1350                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1351                    break;
1352                }
1353                case START_CLEANING_PACKAGE: {
1354                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1355                    final String packageName = (String)msg.obj;
1356                    final int userId = msg.arg1;
1357                    final boolean andCode = msg.arg2 != 0;
1358                    synchronized (mPackages) {
1359                        if (userId == UserHandle.USER_ALL) {
1360                            int[] users = sUserManager.getUserIds();
1361                            for (int user : users) {
1362                                mSettings.addPackageToCleanLPw(
1363                                        new PackageCleanItem(user, packageName, andCode));
1364                            }
1365                        } else {
1366                            mSettings.addPackageToCleanLPw(
1367                                    new PackageCleanItem(userId, packageName, andCode));
1368                        }
1369                    }
1370                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1371                    startCleaningPackages();
1372                } break;
1373                case POST_INSTALL: {
1374                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1375                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1376                    mRunningInstalls.delete(msg.arg1);
1377                    boolean deleteOld = false;
1378
1379                    if (data != null) {
1380                        InstallArgs args = data.args;
1381                        PackageInstalledInfo res = data.res;
1382
1383                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1384                            final String packageName = res.pkg.applicationInfo.packageName;
1385                            res.removedInfo.sendBroadcast(false, true, false);
1386                            Bundle extras = new Bundle(1);
1387                            extras.putInt(Intent.EXTRA_UID, res.uid);
1388
1389                            // Now that we successfully installed the package, grant runtime
1390                            // permissions if requested before broadcasting the install.
1391                            if ((args.installFlags
1392                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1393                                    && res.pkg.applicationInfo.targetSdkVersion
1394                                            >= Build.VERSION_CODES.M) {
1395                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1396                                        args.installGrantPermissions);
1397                            }
1398
1399                            // Determine the set of users who are adding this
1400                            // package for the first time vs. those who are seeing
1401                            // an update.
1402                            int[] firstUsers;
1403                            int[] updateUsers = new int[0];
1404                            if (res.origUsers == null || res.origUsers.length == 0) {
1405                                firstUsers = res.newUsers;
1406                            } else {
1407                                firstUsers = new int[0];
1408                                for (int i=0; i<res.newUsers.length; i++) {
1409                                    int user = res.newUsers[i];
1410                                    boolean isNew = true;
1411                                    for (int j=0; j<res.origUsers.length; j++) {
1412                                        if (res.origUsers[j] == user) {
1413                                            isNew = false;
1414                                            break;
1415                                        }
1416                                    }
1417                                    if (isNew) {
1418                                        int[] newFirst = new int[firstUsers.length+1];
1419                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1420                                                firstUsers.length);
1421                                        newFirst[firstUsers.length] = user;
1422                                        firstUsers = newFirst;
1423                                    } else {
1424                                        int[] newUpdate = new int[updateUsers.length+1];
1425                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1426                                                updateUsers.length);
1427                                        newUpdate[updateUsers.length] = user;
1428                                        updateUsers = newUpdate;
1429                                    }
1430                                }
1431                            }
1432                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1433                                    packageName, extras, 0, null, null, firstUsers);
1434                            final boolean update = res.removedInfo.removedPackage != null;
1435                            if (update) {
1436                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1437                            }
1438                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1439                                    packageName, extras, 0, null, null, updateUsers);
1440                            if (update) {
1441                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1442                                        packageName, extras, 0, null, null, updateUsers);
1443                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1444                                        null, null, 0, packageName, null, updateUsers);
1445
1446                                // treat asec-hosted packages like removable media on upgrade
1447                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1448                                    if (DEBUG_INSTALL) {
1449                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1450                                                + " is ASEC-hosted -> AVAILABLE");
1451                                    }
1452                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1453                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1454                                    pkgList.add(packageName);
1455                                    sendResourcesChangedBroadcast(true, true,
1456                                            pkgList,uidArray, null);
1457                                }
1458                            }
1459                            if (res.removedInfo.args != null) {
1460                                // Remove the replaced package's older resources safely now
1461                                deleteOld = true;
1462                            }
1463
1464                            // If this app is a browser and it's newly-installed for some
1465                            // users, clear any default-browser state in those users
1466                            if (firstUsers.length > 0) {
1467                                // the app's nature doesn't depend on the user, so we can just
1468                                // check its browser nature in any user and generalize.
1469                                if (packageIsBrowser(packageName, firstUsers[0])) {
1470                                    synchronized (mPackages) {
1471                                        for (int userId : firstUsers) {
1472                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1473                                        }
1474                                    }
1475                                }
1476                            }
1477                            // Log current value of "unknown sources" setting
1478                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1479                                getUnknownSourcesSettings());
1480                        }
1481                        // Force a gc to clear up things
1482                        Runtime.getRuntime().gc();
1483                        // We delete after a gc for applications  on sdcard.
1484                        if (deleteOld) {
1485                            synchronized (mInstallLock) {
1486                                res.removedInfo.args.doPostDeleteLI(true);
1487                            }
1488                        }
1489                        if (args.observer != null) {
1490                            try {
1491                                Bundle extras = extrasForInstallResult(res);
1492                                args.observer.onPackageInstalled(res.name, res.returnCode,
1493                                        res.returnMsg, extras);
1494                            } catch (RemoteException e) {
1495                                Slog.i(TAG, "Observer no longer exists.");
1496                            }
1497                        }
1498                        if (args.traceMethod != null) {
1499                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1500                                    args.traceCookie);
1501                        }
1502                        return;
1503                    } else {
1504                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1505                    }
1506
1507                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1508                } break;
1509                case UPDATED_MEDIA_STATUS: {
1510                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1511                    boolean reportStatus = msg.arg1 == 1;
1512                    boolean doGc = msg.arg2 == 1;
1513                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1514                    if (doGc) {
1515                        // Force a gc to clear up stale containers.
1516                        Runtime.getRuntime().gc();
1517                    }
1518                    if (msg.obj != null) {
1519                        @SuppressWarnings("unchecked")
1520                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1521                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1522                        // Unload containers
1523                        unloadAllContainers(args);
1524                    }
1525                    if (reportStatus) {
1526                        try {
1527                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1528                            PackageHelper.getMountService().finishMediaUpdate();
1529                        } catch (RemoteException e) {
1530                            Log.e(TAG, "MountService not running?");
1531                        }
1532                    }
1533                } break;
1534                case WRITE_SETTINGS: {
1535                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1536                    synchronized (mPackages) {
1537                        removeMessages(WRITE_SETTINGS);
1538                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1539                        mSettings.writeLPr();
1540                        mDirtyUsers.clear();
1541                    }
1542                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1543                } break;
1544                case WRITE_PACKAGE_RESTRICTIONS: {
1545                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1546                    synchronized (mPackages) {
1547                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1548                        for (int userId : mDirtyUsers) {
1549                            mSettings.writePackageRestrictionsLPr(userId);
1550                        }
1551                        mDirtyUsers.clear();
1552                    }
1553                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1554                } break;
1555                case CHECK_PENDING_VERIFICATION: {
1556                    final int verificationId = msg.arg1;
1557                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1558
1559                    if ((state != null) && !state.timeoutExtended()) {
1560                        final InstallArgs args = state.getInstallArgs();
1561                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1562
1563                        Slog.i(TAG, "Verification timed out for " + originUri);
1564                        mPendingVerification.remove(verificationId);
1565
1566                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1567
1568                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1569                            Slog.i(TAG, "Continuing with installation of " + originUri);
1570                            state.setVerifierResponse(Binder.getCallingUid(),
1571                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1572                            broadcastPackageVerified(verificationId, originUri,
1573                                    PackageManager.VERIFICATION_ALLOW,
1574                                    state.getInstallArgs().getUser());
1575                            try {
1576                                ret = args.copyApk(mContainerService, true);
1577                            } catch (RemoteException e) {
1578                                Slog.e(TAG, "Could not contact the ContainerService");
1579                            }
1580                        } else {
1581                            broadcastPackageVerified(verificationId, originUri,
1582                                    PackageManager.VERIFICATION_REJECT,
1583                                    state.getInstallArgs().getUser());
1584                        }
1585
1586                        Trace.asyncTraceEnd(
1587                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1588
1589                        processPendingInstall(args, ret);
1590                        mHandler.sendEmptyMessage(MCS_UNBIND);
1591                    }
1592                    break;
1593                }
1594                case PACKAGE_VERIFIED: {
1595                    final int verificationId = msg.arg1;
1596
1597                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1598                    if (state == null) {
1599                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1600                        break;
1601                    }
1602
1603                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1604
1605                    state.setVerifierResponse(response.callerUid, response.code);
1606
1607                    if (state.isVerificationComplete()) {
1608                        mPendingVerification.remove(verificationId);
1609
1610                        final InstallArgs args = state.getInstallArgs();
1611                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1612
1613                        int ret;
1614                        if (state.isInstallAllowed()) {
1615                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1616                            broadcastPackageVerified(verificationId, originUri,
1617                                    response.code, state.getInstallArgs().getUser());
1618                            try {
1619                                ret = args.copyApk(mContainerService, true);
1620                            } catch (RemoteException e) {
1621                                Slog.e(TAG, "Could not contact the ContainerService");
1622                            }
1623                        } else {
1624                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1625                        }
1626
1627                        Trace.asyncTraceEnd(
1628                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1629
1630                        processPendingInstall(args, ret);
1631                        mHandler.sendEmptyMessage(MCS_UNBIND);
1632                    }
1633
1634                    break;
1635                }
1636                case START_INTENT_FILTER_VERIFICATIONS: {
1637                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1638                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1639                            params.replacing, params.pkg);
1640                    break;
1641                }
1642                case INTENT_FILTER_VERIFIED: {
1643                    final int verificationId = msg.arg1;
1644
1645                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1646                            verificationId);
1647                    if (state == null) {
1648                        Slog.w(TAG, "Invalid IntentFilter verification token "
1649                                + verificationId + " received");
1650                        break;
1651                    }
1652
1653                    final int userId = state.getUserId();
1654
1655                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1656                            "Processing IntentFilter verification with token:"
1657                            + verificationId + " and userId:" + userId);
1658
1659                    final IntentFilterVerificationResponse response =
1660                            (IntentFilterVerificationResponse) msg.obj;
1661
1662                    state.setVerifierResponse(response.callerUid, response.code);
1663
1664                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1665                            "IntentFilter verification with token:" + verificationId
1666                            + " and userId:" + userId
1667                            + " is settings verifier response with response code:"
1668                            + response.code);
1669
1670                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1671                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1672                                + response.getFailedDomainsString());
1673                    }
1674
1675                    if (state.isVerificationComplete()) {
1676                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1677                    } else {
1678                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1679                                "IntentFilter verification with token:" + verificationId
1680                                + " was not said to be complete");
1681                    }
1682
1683                    break;
1684                }
1685            }
1686        }
1687    }
1688
1689    private StorageEventListener mStorageListener = new StorageEventListener() {
1690        @Override
1691        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1692            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1693                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1694                    final String volumeUuid = vol.getFsUuid();
1695
1696                    // Clean up any users or apps that were removed or recreated
1697                    // while this volume was missing
1698                    reconcileUsers(volumeUuid);
1699                    reconcileApps(volumeUuid);
1700
1701                    // Clean up any install sessions that expired or were
1702                    // cancelled while this volume was missing
1703                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1704
1705                    loadPrivatePackages(vol);
1706
1707                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1708                    unloadPrivatePackages(vol);
1709                }
1710            }
1711
1712            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1713                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1714                    updateExternalMediaStatus(true, false);
1715                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1716                    updateExternalMediaStatus(false, false);
1717                }
1718            }
1719        }
1720
1721        @Override
1722        public void onVolumeForgotten(String fsUuid) {
1723            if (TextUtils.isEmpty(fsUuid)) {
1724                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1725                return;
1726            }
1727
1728            // Remove any apps installed on the forgotten volume
1729            synchronized (mPackages) {
1730                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1731                for (PackageSetting ps : packages) {
1732                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1733                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1734                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1735                }
1736
1737                mSettings.onVolumeForgotten(fsUuid);
1738                mSettings.writeLPr();
1739            }
1740        }
1741    };
1742
1743    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1744            String[] grantedPermissions) {
1745        if (userId >= UserHandle.USER_SYSTEM) {
1746            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1747        } else if (userId == UserHandle.USER_ALL) {
1748            final int[] userIds;
1749            synchronized (mPackages) {
1750                userIds = UserManagerService.getInstance().getUserIds();
1751            }
1752            for (int someUserId : userIds) {
1753                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1754            }
1755        }
1756
1757        // We could have touched GID membership, so flush out packages.list
1758        synchronized (mPackages) {
1759            mSettings.writePackageListLPr();
1760        }
1761    }
1762
1763    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1764            String[] grantedPermissions) {
1765        SettingBase sb = (SettingBase) pkg.mExtras;
1766        if (sb == null) {
1767            return;
1768        }
1769
1770        PermissionsState permissionsState = sb.getPermissionsState();
1771
1772        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1773                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1774
1775        synchronized (mPackages) {
1776            for (String permission : pkg.requestedPermissions) {
1777                BasePermission bp = mSettings.mPermissions.get(permission);
1778                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1779                        && (grantedPermissions == null
1780                               || ArrayUtils.contains(grantedPermissions, permission))) {
1781                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1782                    // Installer cannot change immutable permissions.
1783                    if ((flags & immutableFlags) == 0) {
1784                        grantRuntimePermission(pkg.packageName, permission, userId);
1785                    }
1786                }
1787            }
1788        }
1789    }
1790
1791    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1792        Bundle extras = null;
1793        switch (res.returnCode) {
1794            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1795                extras = new Bundle();
1796                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1797                        res.origPermission);
1798                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1799                        res.origPackage);
1800                break;
1801            }
1802            case PackageManager.INSTALL_SUCCEEDED: {
1803                extras = new Bundle();
1804                extras.putBoolean(Intent.EXTRA_REPLACING,
1805                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1806                break;
1807            }
1808        }
1809        return extras;
1810    }
1811
1812    void scheduleWriteSettingsLocked() {
1813        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1814            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1815        }
1816    }
1817
1818    void scheduleWritePackageRestrictionsLocked(int userId) {
1819        if (!sUserManager.exists(userId)) return;
1820        mDirtyUsers.add(userId);
1821        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1822            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1823        }
1824    }
1825
1826    public static PackageManagerService main(Context context, Installer installer,
1827            boolean factoryTest, boolean onlyCore) {
1828        PackageManagerService m = new PackageManagerService(context, installer,
1829                factoryTest, onlyCore);
1830        m.enableSystemUserApps();
1831        ServiceManager.addService("package", m);
1832        return m;
1833    }
1834
1835    private void enableSystemUserApps() {
1836        if (!UserManager.isSplitSystemUser()) {
1837            return;
1838        }
1839        // For system user, enable apps based on the following conditions:
1840        // - app is whitelisted or belong to one of these groups:
1841        //   -- system app which has no launcher icons
1842        //   -- system app which has INTERACT_ACROSS_USERS permission
1843        //   -- system IME app
1844        // - app is not in the blacklist
1845        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1846        Set<String> enableApps = new ArraySet<>();
1847        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1848                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1849                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1850        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1851        enableApps.addAll(wlApps);
1852        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1853        enableApps.removeAll(blApps);
1854
1855        List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true,
1856                UserHandle.SYSTEM);
1857        final int systemAppsSize = systemApps.size();
1858        synchronized (mPackages) {
1859            for (int i = 0; i < systemAppsSize; i++) {
1860                String pName = systemApps.get(i);
1861                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1862                // Should not happen, but we shouldn't be failing if it does
1863                if (pkgSetting == null) {
1864                    continue;
1865                }
1866                boolean installed = enableApps.contains(pName);
1867                pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM);
1868            }
1869        }
1870    }
1871
1872    static String[] splitString(String str, char sep) {
1873        int count = 1;
1874        int i = 0;
1875        while ((i=str.indexOf(sep, i)) >= 0) {
1876            count++;
1877            i++;
1878        }
1879
1880        String[] res = new String[count];
1881        i=0;
1882        count = 0;
1883        int lastI=0;
1884        while ((i=str.indexOf(sep, i)) >= 0) {
1885            res[count] = str.substring(lastI, i);
1886            count++;
1887            i++;
1888            lastI = i;
1889        }
1890        res[count] = str.substring(lastI, str.length());
1891        return res;
1892    }
1893
1894    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1895        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1896                Context.DISPLAY_SERVICE);
1897        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1898    }
1899
1900    public PackageManagerService(Context context, Installer installer,
1901            boolean factoryTest, boolean onlyCore) {
1902        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1903                SystemClock.uptimeMillis());
1904
1905        if (mSdkVersion <= 0) {
1906            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1907        }
1908
1909        mContext = context;
1910        mFactoryTest = factoryTest;
1911        mOnlyCore = onlyCore;
1912        mMetrics = new DisplayMetrics();
1913        mSettings = new Settings(mPackages);
1914        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1915                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1916        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1917                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1918        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1919                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1920        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1921                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1922        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1923                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1924        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1925                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1926
1927        String separateProcesses = SystemProperties.get("debug.separate_processes");
1928        if (separateProcesses != null && separateProcesses.length() > 0) {
1929            if ("*".equals(separateProcesses)) {
1930                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1931                mSeparateProcesses = null;
1932                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1933            } else {
1934                mDefParseFlags = 0;
1935                mSeparateProcesses = separateProcesses.split(",");
1936                Slog.w(TAG, "Running with debug.separate_processes: "
1937                        + separateProcesses);
1938            }
1939        } else {
1940            mDefParseFlags = 0;
1941            mSeparateProcesses = null;
1942        }
1943
1944        mInstaller = installer;
1945        mPackageDexOptimizer = new PackageDexOptimizer(this);
1946        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1947
1948        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1949                FgThread.get().getLooper());
1950
1951        getDefaultDisplayMetrics(context, mMetrics);
1952
1953        SystemConfig systemConfig = SystemConfig.getInstance();
1954        mGlobalGids = systemConfig.getGlobalGids();
1955        mSystemPermissions = systemConfig.getSystemPermissions();
1956        mAvailableFeatures = systemConfig.getAvailableFeatures();
1957
1958        synchronized (mInstallLock) {
1959        // writer
1960        synchronized (mPackages) {
1961            mHandlerThread = new ServiceThread(TAG,
1962                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1963            mHandlerThread.start();
1964            mHandler = new PackageHandler(mHandlerThread.getLooper());
1965            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1966
1967            File dataDir = Environment.getDataDirectory();
1968            mAppDataDir = new File(dataDir, "data");
1969            mAppInstallDir = new File(dataDir, "app");
1970            mAppLib32InstallDir = new File(dataDir, "app-lib");
1971            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1972            mUserAppDataDir = new File(dataDir, "user");
1973            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1974
1975            sUserManager = new UserManagerService(context, this, mPackages);
1976
1977            // Propagate permission configuration in to package manager.
1978            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1979                    = systemConfig.getPermissions();
1980            for (int i=0; i<permConfig.size(); i++) {
1981                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1982                BasePermission bp = mSettings.mPermissions.get(perm.name);
1983                if (bp == null) {
1984                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1985                    mSettings.mPermissions.put(perm.name, bp);
1986                }
1987                if (perm.gids != null) {
1988                    bp.setGids(perm.gids, perm.perUser);
1989                }
1990            }
1991
1992            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1993            for (int i=0; i<libConfig.size(); i++) {
1994                mSharedLibraries.put(libConfig.keyAt(i),
1995                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1996            }
1997
1998            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1999
2000            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2001
2002            String customResolverActivity = Resources.getSystem().getString(
2003                    R.string.config_customResolverActivity);
2004            if (TextUtils.isEmpty(customResolverActivity)) {
2005                customResolverActivity = null;
2006            } else {
2007                mCustomResolverComponentName = ComponentName.unflattenFromString(
2008                        customResolverActivity);
2009            }
2010
2011            long startTime = SystemClock.uptimeMillis();
2012
2013            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2014                    startTime);
2015
2016            // Set flag to monitor and not change apk file paths when
2017            // scanning install directories.
2018            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2019
2020            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2021            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2022
2023            if (bootClassPath == null) {
2024                Slog.w(TAG, "No BOOTCLASSPATH found!");
2025            }
2026
2027            if (systemServerClassPath == null) {
2028                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2029            }
2030
2031            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2032            final String[] dexCodeInstructionSets =
2033                    getDexCodeInstructionSets(
2034                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2035
2036            /**
2037             * Ensure all external libraries have had dexopt run on them.
2038             */
2039            if (mSharedLibraries.size() > 0) {
2040                // NOTE: For now, we're compiling these system "shared libraries"
2041                // (and framework jars) into all available architectures. It's possible
2042                // to compile them only when we come across an app that uses them (there's
2043                // already logic for that in scanPackageLI) but that adds some complexity.
2044                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2045                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2046                        final String lib = libEntry.path;
2047                        if (lib == null) {
2048                            continue;
2049                        }
2050
2051                        try {
2052                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2053                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2054                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2055                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2056                            }
2057                        } catch (FileNotFoundException e) {
2058                            Slog.w(TAG, "Library not found: " + lib);
2059                        } catch (IOException e) {
2060                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2061                                    + e.getMessage());
2062                        }
2063                    }
2064                }
2065            }
2066
2067            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2068
2069            final VersionInfo ver = mSettings.getInternalVersion();
2070            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2071            // when upgrading from pre-M, promote system app permissions from install to runtime
2072            mPromoteSystemApps =
2073                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2074
2075            // save off the names of pre-existing system packages prior to scanning; we don't
2076            // want to automatically grant runtime permissions for new system apps
2077            if (mPromoteSystemApps) {
2078                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2079                while (pkgSettingIter.hasNext()) {
2080                    PackageSetting ps = pkgSettingIter.next();
2081                    if (isSystemApp(ps)) {
2082                        mExistingSystemPackages.add(ps.name);
2083                    }
2084                }
2085            }
2086
2087            // Collect vendor overlay packages.
2088            // (Do this before scanning any apps.)
2089            // For security and version matching reason, only consider
2090            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2091            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2092            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2093                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2094
2095            // Find base frameworks (resource packages without code).
2096            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2097                    | PackageParser.PARSE_IS_SYSTEM_DIR
2098                    | PackageParser.PARSE_IS_PRIVILEGED,
2099                    scanFlags | SCAN_NO_DEX, 0);
2100
2101            // Collected privileged system packages.
2102            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2103            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2104                    | PackageParser.PARSE_IS_SYSTEM_DIR
2105                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2106
2107            // Collect ordinary system packages.
2108            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2109            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2110                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2111
2112            // Collect all vendor packages.
2113            File vendorAppDir = new File("/vendor/app");
2114            try {
2115                vendorAppDir = vendorAppDir.getCanonicalFile();
2116            } catch (IOException e) {
2117                // failed to look up canonical path, continue with original one
2118            }
2119            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2120                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2121
2122            // Collect all OEM packages.
2123            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2124            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2125                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2126
2127            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2128            mInstaller.moveFiles();
2129
2130            // Prune any system packages that no longer exist.
2131            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2132            if (!mOnlyCore) {
2133                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2134                while (psit.hasNext()) {
2135                    PackageSetting ps = psit.next();
2136
2137                    /*
2138                     * If this is not a system app, it can't be a
2139                     * disable system app.
2140                     */
2141                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2142                        continue;
2143                    }
2144
2145                    /*
2146                     * If the package is scanned, it's not erased.
2147                     */
2148                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2149                    if (scannedPkg != null) {
2150                        /*
2151                         * If the system app is both scanned and in the
2152                         * disabled packages list, then it must have been
2153                         * added via OTA. Remove it from the currently
2154                         * scanned package so the previously user-installed
2155                         * application can be scanned.
2156                         */
2157                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2158                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2159                                    + ps.name + "; removing system app.  Last known codePath="
2160                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2161                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2162                                    + scannedPkg.mVersionCode);
2163                            removePackageLI(ps, true);
2164                            mExpectingBetter.put(ps.name, ps.codePath);
2165                        }
2166
2167                        continue;
2168                    }
2169
2170                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2171                        psit.remove();
2172                        logCriticalInfo(Log.WARN, "System package " + ps.name
2173                                + " no longer exists; wiping its data");
2174                        removeDataDirsLI(null, ps.name);
2175                    } else {
2176                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2177                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2178                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2179                        }
2180                    }
2181                }
2182            }
2183
2184            //look for any incomplete package installations
2185            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2186            //clean up list
2187            for(int i = 0; i < deletePkgsList.size(); i++) {
2188                //clean up here
2189                cleanupInstallFailedPackage(deletePkgsList.get(i));
2190            }
2191            //delete tmp files
2192            deleteTempPackageFiles();
2193
2194            // Remove any shared userIDs that have no associated packages
2195            mSettings.pruneSharedUsersLPw();
2196
2197            if (!mOnlyCore) {
2198                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2199                        SystemClock.uptimeMillis());
2200                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2201
2202                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2203                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2204
2205                /**
2206                 * Remove disable package settings for any updated system
2207                 * apps that were removed via an OTA. If they're not a
2208                 * previously-updated app, remove them completely.
2209                 * Otherwise, just revoke their system-level permissions.
2210                 */
2211                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2212                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2213                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2214
2215                    String msg;
2216                    if (deletedPkg == null) {
2217                        msg = "Updated system package " + deletedAppName
2218                                + " no longer exists; wiping its data";
2219                        removeDataDirsLI(null, deletedAppName);
2220                    } else {
2221                        msg = "Updated system app + " + deletedAppName
2222                                + " no longer present; removing system privileges for "
2223                                + deletedAppName;
2224
2225                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2226
2227                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2228                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2229                    }
2230                    logCriticalInfo(Log.WARN, msg);
2231                }
2232
2233                /**
2234                 * Make sure all system apps that we expected to appear on
2235                 * the userdata partition actually showed up. If they never
2236                 * appeared, crawl back and revive the system version.
2237                 */
2238                for (int i = 0; i < mExpectingBetter.size(); i++) {
2239                    final String packageName = mExpectingBetter.keyAt(i);
2240                    if (!mPackages.containsKey(packageName)) {
2241                        final File scanFile = mExpectingBetter.valueAt(i);
2242
2243                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2244                                + " but never showed up; reverting to system");
2245
2246                        final int reparseFlags;
2247                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2248                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2249                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2250                                    | PackageParser.PARSE_IS_PRIVILEGED;
2251                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2252                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2253                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2254                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2255                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2256                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2257                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2258                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2259                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2260                        } else {
2261                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2262                            continue;
2263                        }
2264
2265                        mSettings.enableSystemPackageLPw(packageName);
2266
2267                        try {
2268                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2269                        } catch (PackageManagerException e) {
2270                            Slog.e(TAG, "Failed to parse original system package: "
2271                                    + e.getMessage());
2272                        }
2273                    }
2274                }
2275            }
2276            mExpectingBetter.clear();
2277
2278            // Now that we know all of the shared libraries, update all clients to have
2279            // the correct library paths.
2280            updateAllSharedLibrariesLPw();
2281
2282            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2283                // NOTE: We ignore potential failures here during a system scan (like
2284                // the rest of the commands above) because there's precious little we
2285                // can do about it. A settings error is reported, though.
2286                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2287                        false /* boot complete */);
2288            }
2289
2290            // Now that we know all the packages we are keeping,
2291            // read and update their last usage times.
2292            mPackageUsage.readLP();
2293
2294            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2295                    SystemClock.uptimeMillis());
2296            Slog.i(TAG, "Time to scan packages: "
2297                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2298                    + " seconds");
2299
2300            // If the platform SDK has changed since the last time we booted,
2301            // we need to re-grant app permission to catch any new ones that
2302            // appear.  This is really a hack, and means that apps can in some
2303            // cases get permissions that the user didn't initially explicitly
2304            // allow...  it would be nice to have some better way to handle
2305            // this situation.
2306            int updateFlags = UPDATE_PERMISSIONS_ALL;
2307            if (ver.sdkVersion != mSdkVersion) {
2308                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2309                        + mSdkVersion + "; regranting permissions for internal storage");
2310                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2311            }
2312            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2313            ver.sdkVersion = mSdkVersion;
2314
2315            // If this is the first boot or an update from pre-M, and it is a normal
2316            // boot, then we need to initialize the default preferred apps across
2317            // all defined users.
2318            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2319                for (UserInfo user : sUserManager.getUsers(true)) {
2320                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2321                    applyFactoryDefaultBrowserLPw(user.id);
2322                    primeDomainVerificationsLPw(user.id);
2323                }
2324            }
2325
2326            // If this is first boot after an OTA, and a normal boot, then
2327            // we need to clear code cache directories.
2328            if (mIsUpgrade && !onlyCore) {
2329                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2330                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2331                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2332                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2333                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2334                    }
2335                }
2336                ver.fingerprint = Build.FINGERPRINT;
2337            }
2338
2339            checkDefaultBrowser();
2340
2341            // clear only after permissions and other defaults have been updated
2342            mExistingSystemPackages.clear();
2343            mPromoteSystemApps = false;
2344
2345            // All the changes are done during package scanning.
2346            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2347
2348            // can downgrade to reader
2349            mSettings.writeLPr();
2350
2351            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2352                    SystemClock.uptimeMillis());
2353
2354            mRequiredVerifierPackage = getRequiredVerifierLPr();
2355            mRequiredInstallerPackage = getRequiredInstallerLPr();
2356
2357            mInstallerService = new PackageInstallerService(context, this);
2358
2359            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2360            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2361                    mIntentFilterVerifierComponent);
2362
2363            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2364            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2365            // both the installer and resolver must be present to enable ephemeral
2366            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2367                if (DEBUG_EPHEMERAL) {
2368                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2369                            + " installer:" + ephemeralInstallerComponent);
2370                }
2371                mEphemeralResolverComponent = ephemeralResolverComponent;
2372                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2373                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2374                mEphemeralResolverConnection =
2375                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2376            } else {
2377                if (DEBUG_EPHEMERAL) {
2378                    final String missingComponent =
2379                            (ephemeralResolverComponent == null)
2380                            ? (ephemeralInstallerComponent == null)
2381                                    ? "resolver and installer"
2382                                    : "resolver"
2383                            : "installer";
2384                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2385                }
2386                mEphemeralResolverComponent = null;
2387                mEphemeralInstallerComponent = null;
2388                mEphemeralResolverConnection = null;
2389            }
2390        } // synchronized (mPackages)
2391        } // synchronized (mInstallLock)
2392
2393        // Now after opening every single application zip, make sure they
2394        // are all flushed.  Not really needed, but keeps things nice and
2395        // tidy.
2396        Runtime.getRuntime().gc();
2397
2398        // The initial scanning above does many calls into installd while
2399        // holding the mPackages lock, but we're mostly interested in yelling
2400        // once we have a booted system.
2401        mInstaller.setWarnIfHeld(mPackages);
2402
2403        // Expose private service for system components to use.
2404        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2405    }
2406
2407    @Override
2408    public boolean isFirstBoot() {
2409        return !mRestoredSettings;
2410    }
2411
2412    @Override
2413    public boolean isOnlyCoreApps() {
2414        return mOnlyCore;
2415    }
2416
2417    @Override
2418    public boolean isUpgrade() {
2419        return mIsUpgrade;
2420    }
2421
2422    private String getRequiredVerifierLPr() {
2423        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2424        // We only care about verifier that's installed under system user.
2425        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2426                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2427
2428        String requiredVerifier = null;
2429
2430        final int N = receivers.size();
2431        for (int i = 0; i < N; i++) {
2432            final ResolveInfo info = receivers.get(i);
2433
2434            if (info.activityInfo == null) {
2435                continue;
2436            }
2437
2438            final String packageName = info.activityInfo.packageName;
2439
2440            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2441                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2442                continue;
2443            }
2444
2445            if (requiredVerifier != null) {
2446                throw new RuntimeException("There can be only one required verifier");
2447            }
2448
2449            requiredVerifier = packageName;
2450        }
2451
2452        return requiredVerifier;
2453    }
2454
2455    private String getRequiredInstallerLPr() {
2456        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2457        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2458        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2459
2460        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2461                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2462
2463        String requiredInstaller = null;
2464
2465        final int N = installers.size();
2466        for (int i = 0; i < N; i++) {
2467            final ResolveInfo info = installers.get(i);
2468            final String packageName = info.activityInfo.packageName;
2469
2470            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2471                continue;
2472            }
2473
2474            if (requiredInstaller != null) {
2475                throw new RuntimeException("There must be one required installer");
2476            }
2477
2478            requiredInstaller = packageName;
2479        }
2480
2481        if (requiredInstaller == null) {
2482            throw new RuntimeException("There must be one required installer");
2483        }
2484
2485        return requiredInstaller;
2486    }
2487
2488    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2489        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2490        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2491                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2492
2493        ComponentName verifierComponentName = null;
2494
2495        int priority = -1000;
2496        final int N = receivers.size();
2497        for (int i = 0; i < N; i++) {
2498            final ResolveInfo info = receivers.get(i);
2499
2500            if (info.activityInfo == null) {
2501                continue;
2502            }
2503
2504            final String packageName = info.activityInfo.packageName;
2505
2506            final PackageSetting ps = mSettings.mPackages.get(packageName);
2507            if (ps == null) {
2508                continue;
2509            }
2510
2511            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2512                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2513                continue;
2514            }
2515
2516            // Select the IntentFilterVerifier with the highest priority
2517            if (priority < info.priority) {
2518                priority = info.priority;
2519                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2520                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2521                        + verifierComponentName + " with priority: " + info.priority);
2522            }
2523        }
2524
2525        return verifierComponentName;
2526    }
2527
2528    private ComponentName getEphemeralResolverLPr() {
2529        final String[] packageArray =
2530                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2531        if (packageArray.length == 0) {
2532            if (DEBUG_EPHEMERAL) {
2533                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2534            }
2535            return null;
2536        }
2537
2538        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2539        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2540                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2541
2542        final int N = resolvers.size();
2543        if (N == 0) {
2544            if (DEBUG_EPHEMERAL) {
2545                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2546            }
2547            return null;
2548        }
2549
2550        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2551        for (int i = 0; i < N; i++) {
2552            final ResolveInfo info = resolvers.get(i);
2553
2554            if (info.serviceInfo == null) {
2555                continue;
2556            }
2557
2558            final String packageName = info.serviceInfo.packageName;
2559            if (!possiblePackages.contains(packageName)) {
2560                if (DEBUG_EPHEMERAL) {
2561                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2562                            + " pkg: " + packageName + ", info:" + info);
2563                }
2564                continue;
2565            }
2566
2567            if (DEBUG_EPHEMERAL) {
2568                Slog.v(TAG, "Ephemeral resolver found;"
2569                        + " pkg: " + packageName + ", info:" + info);
2570            }
2571            return new ComponentName(packageName, info.serviceInfo.name);
2572        }
2573        if (DEBUG_EPHEMERAL) {
2574            Slog.v(TAG, "Ephemeral resolver NOT found");
2575        }
2576        return null;
2577    }
2578
2579    private ComponentName getEphemeralInstallerLPr() {
2580        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2581        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2582        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2583        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2584                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2585
2586        ComponentName ephemeralInstaller = null;
2587
2588        final int N = installers.size();
2589        for (int i = 0; i < N; i++) {
2590            final ResolveInfo info = installers.get(i);
2591            final String packageName = info.activityInfo.packageName;
2592
2593            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2594                if (DEBUG_EPHEMERAL) {
2595                    Slog.d(TAG, "Ephemeral installer is not system app;"
2596                            + " pkg: " + packageName + ", info:" + info);
2597                }
2598                continue;
2599            }
2600
2601            if (ephemeralInstaller != null) {
2602                throw new RuntimeException("There must only be one ephemeral installer");
2603            }
2604
2605            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2606        }
2607
2608        return ephemeralInstaller;
2609    }
2610
2611    private void primeDomainVerificationsLPw(int userId) {
2612        if (DEBUG_DOMAIN_VERIFICATION) {
2613            Slog.d(TAG, "Priming domain verifications in user " + userId);
2614        }
2615
2616        SystemConfig systemConfig = SystemConfig.getInstance();
2617        ArraySet<String> packages = systemConfig.getLinkedApps();
2618        ArraySet<String> domains = new ArraySet<String>();
2619
2620        for (String packageName : packages) {
2621            PackageParser.Package pkg = mPackages.get(packageName);
2622            if (pkg != null) {
2623                if (!pkg.isSystemApp()) {
2624                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2625                    continue;
2626                }
2627
2628                domains.clear();
2629                for (PackageParser.Activity a : pkg.activities) {
2630                    for (ActivityIntentInfo filter : a.intents) {
2631                        if (hasValidDomains(filter)) {
2632                            domains.addAll(filter.getHostsList());
2633                        }
2634                    }
2635                }
2636
2637                if (domains.size() > 0) {
2638                    if (DEBUG_DOMAIN_VERIFICATION) {
2639                        Slog.v(TAG, "      + " + packageName);
2640                    }
2641                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2642                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2643                    // and then 'always' in the per-user state actually used for intent resolution.
2644                    final IntentFilterVerificationInfo ivi;
2645                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2646                            new ArrayList<String>(domains));
2647                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2648                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2649                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2650                } else {
2651                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2652                            + "' does not handle web links");
2653                }
2654            } else {
2655                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2656            }
2657        }
2658
2659        scheduleWritePackageRestrictionsLocked(userId);
2660        scheduleWriteSettingsLocked();
2661    }
2662
2663    private void applyFactoryDefaultBrowserLPw(int userId) {
2664        // The default browser app's package name is stored in a string resource,
2665        // with a product-specific overlay used for vendor customization.
2666        String browserPkg = mContext.getResources().getString(
2667                com.android.internal.R.string.default_browser);
2668        if (!TextUtils.isEmpty(browserPkg)) {
2669            // non-empty string => required to be a known package
2670            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2671            if (ps == null) {
2672                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2673                browserPkg = null;
2674            } else {
2675                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2676            }
2677        }
2678
2679        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2680        // default.  If there's more than one, just leave everything alone.
2681        if (browserPkg == null) {
2682            calculateDefaultBrowserLPw(userId);
2683        }
2684    }
2685
2686    private void calculateDefaultBrowserLPw(int userId) {
2687        List<String> allBrowsers = resolveAllBrowserApps(userId);
2688        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2689        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2690    }
2691
2692    private List<String> resolveAllBrowserApps(int userId) {
2693        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2694        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2695                PackageManager.MATCH_ALL, userId);
2696
2697        final int count = list.size();
2698        List<String> result = new ArrayList<String>(count);
2699        for (int i=0; i<count; i++) {
2700            ResolveInfo info = list.get(i);
2701            if (info.activityInfo == null
2702                    || !info.handleAllWebDataURI
2703                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2704                    || result.contains(info.activityInfo.packageName)) {
2705                continue;
2706            }
2707            result.add(info.activityInfo.packageName);
2708        }
2709
2710        return result;
2711    }
2712
2713    private boolean packageIsBrowser(String packageName, int userId) {
2714        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2715                PackageManager.MATCH_ALL, userId);
2716        final int N = list.size();
2717        for (int i = 0; i < N; i++) {
2718            ResolveInfo info = list.get(i);
2719            if (packageName.equals(info.activityInfo.packageName)) {
2720                return true;
2721            }
2722        }
2723        return false;
2724    }
2725
2726    private void checkDefaultBrowser() {
2727        final int myUserId = UserHandle.myUserId();
2728        final String packageName = getDefaultBrowserPackageName(myUserId);
2729        if (packageName != null) {
2730            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2731            if (info == null) {
2732                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2733                synchronized (mPackages) {
2734                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2735                }
2736            }
2737        }
2738    }
2739
2740    @Override
2741    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2742            throws RemoteException {
2743        try {
2744            return super.onTransact(code, data, reply, flags);
2745        } catch (RuntimeException e) {
2746            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2747                Slog.wtf(TAG, "Package Manager Crash", e);
2748            }
2749            throw e;
2750        }
2751    }
2752
2753    void cleanupInstallFailedPackage(PackageSetting ps) {
2754        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2755
2756        removeDataDirsLI(ps.volumeUuid, ps.name);
2757        if (ps.codePath != null) {
2758            if (ps.codePath.isDirectory()) {
2759                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2760            } else {
2761                ps.codePath.delete();
2762            }
2763        }
2764        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2765            if (ps.resourcePath.isDirectory()) {
2766                FileUtils.deleteContents(ps.resourcePath);
2767            }
2768            ps.resourcePath.delete();
2769        }
2770        mSettings.removePackageLPw(ps.name);
2771    }
2772
2773    static int[] appendInts(int[] cur, int[] add) {
2774        if (add == null) return cur;
2775        if (cur == null) return add;
2776        final int N = add.length;
2777        for (int i=0; i<N; i++) {
2778            cur = appendInt(cur, add[i]);
2779        }
2780        return cur;
2781    }
2782
2783    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2784        if (!sUserManager.exists(userId)) return null;
2785        final PackageSetting ps = (PackageSetting) p.mExtras;
2786        if (ps == null) {
2787            return null;
2788        }
2789
2790        final PermissionsState permissionsState = ps.getPermissionsState();
2791
2792        final int[] gids = permissionsState.computeGids(userId);
2793        final Set<String> permissions = permissionsState.getPermissions(userId);
2794        final PackageUserState state = ps.readUserState(userId);
2795
2796        return PackageParser.generatePackageInfo(p, gids, flags,
2797                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2798    }
2799
2800    @Override
2801    public void checkPackageStartable(String packageName, int userId) {
2802        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2803
2804        synchronized (mPackages) {
2805            final PackageSetting ps = mSettings.mPackages.get(packageName);
2806            if (ps == null) {
2807                throw new SecurityException("Package " + packageName + " was not found!");
2808            }
2809
2810            if (ps.frozen) {
2811                throw new SecurityException("Package " + packageName + " is currently frozen!");
2812            }
2813
2814            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2815                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2816                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2817            }
2818        }
2819    }
2820
2821    @Override
2822    public boolean isPackageAvailable(String packageName, int userId) {
2823        if (!sUserManager.exists(userId)) return false;
2824        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2825        synchronized (mPackages) {
2826            PackageParser.Package p = mPackages.get(packageName);
2827            if (p != null) {
2828                final PackageSetting ps = (PackageSetting) p.mExtras;
2829                if (ps != null) {
2830                    final PackageUserState state = ps.readUserState(userId);
2831                    if (state != null) {
2832                        return PackageParser.isAvailable(state);
2833                    }
2834                }
2835            }
2836        }
2837        return false;
2838    }
2839
2840    @Override
2841    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2842        if (!sUserManager.exists(userId)) return null;
2843        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2844        // reader
2845        synchronized (mPackages) {
2846            PackageParser.Package p = mPackages.get(packageName);
2847            if (DEBUG_PACKAGE_INFO)
2848                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2849            if (p != null) {
2850                return generatePackageInfo(p, flags, userId);
2851            }
2852            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2853                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2854            }
2855        }
2856        return null;
2857    }
2858
2859    @Override
2860    public String[] currentToCanonicalPackageNames(String[] names) {
2861        String[] out = new String[names.length];
2862        // reader
2863        synchronized (mPackages) {
2864            for (int i=names.length-1; i>=0; i--) {
2865                PackageSetting ps = mSettings.mPackages.get(names[i]);
2866                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2867            }
2868        }
2869        return out;
2870    }
2871
2872    @Override
2873    public String[] canonicalToCurrentPackageNames(String[] names) {
2874        String[] out = new String[names.length];
2875        // reader
2876        synchronized (mPackages) {
2877            for (int i=names.length-1; i>=0; i--) {
2878                String cur = mSettings.mRenamedPackages.get(names[i]);
2879                out[i] = cur != null ? cur : names[i];
2880            }
2881        }
2882        return out;
2883    }
2884
2885    @Override
2886    public int getPackageUid(String packageName, int userId) {
2887        return getPackageUidEtc(packageName, 0, userId);
2888    }
2889
2890    @Override
2891    public int getPackageUidEtc(String packageName, int flags, int userId) {
2892        if (!sUserManager.exists(userId)) return -1;
2893        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2894
2895        // reader
2896        synchronized (mPackages) {
2897            final PackageParser.Package p = mPackages.get(packageName);
2898            if (p != null) {
2899                return UserHandle.getUid(userId, p.applicationInfo.uid);
2900            }
2901            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2902                final PackageSetting ps = mSettings.mPackages.get(packageName);
2903                if (ps != null) {
2904                    return UserHandle.getUid(userId, ps.appId);
2905                }
2906            }
2907        }
2908
2909        return -1;
2910    }
2911
2912    @Override
2913    public int[] getPackageGids(String packageName, int userId) {
2914        return getPackageGidsEtc(packageName, 0, userId);
2915    }
2916
2917    @Override
2918    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2919        if (!sUserManager.exists(userId)) {
2920            return null;
2921        }
2922
2923        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2924                "getPackageGids");
2925
2926        // reader
2927        synchronized (mPackages) {
2928            final PackageParser.Package p = mPackages.get(packageName);
2929            if (p != null) {
2930                PackageSetting ps = (PackageSetting) p.mExtras;
2931                return ps.getPermissionsState().computeGids(userId);
2932            }
2933            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2934                final PackageSetting ps = mSettings.mPackages.get(packageName);
2935                if (ps != null) {
2936                    return ps.getPermissionsState().computeGids(userId);
2937                }
2938            }
2939        }
2940
2941        return null;
2942    }
2943
2944    static PermissionInfo generatePermissionInfo(
2945            BasePermission bp, int flags) {
2946        if (bp.perm != null) {
2947            return PackageParser.generatePermissionInfo(bp.perm, flags);
2948        }
2949        PermissionInfo pi = new PermissionInfo();
2950        pi.name = bp.name;
2951        pi.packageName = bp.sourcePackage;
2952        pi.nonLocalizedLabel = bp.name;
2953        pi.protectionLevel = bp.protectionLevel;
2954        return pi;
2955    }
2956
2957    @Override
2958    public PermissionInfo getPermissionInfo(String name, int flags) {
2959        // reader
2960        synchronized (mPackages) {
2961            final BasePermission p = mSettings.mPermissions.get(name);
2962            if (p != null) {
2963                return generatePermissionInfo(p, flags);
2964            }
2965            return null;
2966        }
2967    }
2968
2969    @Override
2970    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2971        // reader
2972        synchronized (mPackages) {
2973            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2974            for (BasePermission p : mSettings.mPermissions.values()) {
2975                if (group == null) {
2976                    if (p.perm == null || p.perm.info.group == null) {
2977                        out.add(generatePermissionInfo(p, flags));
2978                    }
2979                } else {
2980                    if (p.perm != null && group.equals(p.perm.info.group)) {
2981                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2982                    }
2983                }
2984            }
2985
2986            if (out.size() > 0) {
2987                return out;
2988            }
2989            return mPermissionGroups.containsKey(group) ? out : null;
2990        }
2991    }
2992
2993    @Override
2994    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2995        // reader
2996        synchronized (mPackages) {
2997            return PackageParser.generatePermissionGroupInfo(
2998                    mPermissionGroups.get(name), flags);
2999        }
3000    }
3001
3002    @Override
3003    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3004        // reader
3005        synchronized (mPackages) {
3006            final int N = mPermissionGroups.size();
3007            ArrayList<PermissionGroupInfo> out
3008                    = new ArrayList<PermissionGroupInfo>(N);
3009            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3010                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3011            }
3012            return out;
3013        }
3014    }
3015
3016    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3017            int userId) {
3018        if (!sUserManager.exists(userId)) return null;
3019        PackageSetting ps = mSettings.mPackages.get(packageName);
3020        if (ps != null) {
3021            if (ps.pkg == null) {
3022                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3023                        flags, userId);
3024                if (pInfo != null) {
3025                    return pInfo.applicationInfo;
3026                }
3027                return null;
3028            }
3029            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3030                    ps.readUserState(userId), userId);
3031        }
3032        return null;
3033    }
3034
3035    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3036            int userId) {
3037        if (!sUserManager.exists(userId)) return null;
3038        PackageSetting ps = mSettings.mPackages.get(packageName);
3039        if (ps != null) {
3040            PackageParser.Package pkg = ps.pkg;
3041            if (pkg == null) {
3042                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3043                    return null;
3044                }
3045                // Only data remains, so we aren't worried about code paths
3046                pkg = new PackageParser.Package(packageName);
3047                pkg.applicationInfo.packageName = packageName;
3048                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3049                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3050                pkg.applicationInfo.uid = ps.appId;
3051                pkg.applicationInfo.initForUser(userId);
3052                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3053                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3054            }
3055            return generatePackageInfo(pkg, flags, userId);
3056        }
3057        return null;
3058    }
3059
3060    @Override
3061    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3062        if (!sUserManager.exists(userId)) return null;
3063        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3064        // writer
3065        synchronized (mPackages) {
3066            PackageParser.Package p = mPackages.get(packageName);
3067            if (DEBUG_PACKAGE_INFO) Log.v(
3068                    TAG, "getApplicationInfo " + packageName
3069                    + ": " + p);
3070            if (p != null) {
3071                PackageSetting ps = mSettings.mPackages.get(packageName);
3072                if (ps == null) return null;
3073                // Note: isEnabledLP() does not apply here - always return info
3074                return PackageParser.generateApplicationInfo(
3075                        p, flags, ps.readUserState(userId), userId);
3076            }
3077            if ("android".equals(packageName)||"system".equals(packageName)) {
3078                return mAndroidApplication;
3079            }
3080            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3081                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3082            }
3083        }
3084        return null;
3085    }
3086
3087    @Override
3088    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3089            final IPackageDataObserver observer) {
3090        mContext.enforceCallingOrSelfPermission(
3091                android.Manifest.permission.CLEAR_APP_CACHE, null);
3092        // Queue up an async operation since clearing cache may take a little while.
3093        mHandler.post(new Runnable() {
3094            public void run() {
3095                mHandler.removeCallbacks(this);
3096                int retCode = -1;
3097                synchronized (mInstallLock) {
3098                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3099                    if (retCode < 0) {
3100                        Slog.w(TAG, "Couldn't clear application caches");
3101                    }
3102                }
3103                if (observer != null) {
3104                    try {
3105                        observer.onRemoveCompleted(null, (retCode >= 0));
3106                    } catch (RemoteException e) {
3107                        Slog.w(TAG, "RemoveException when invoking call back");
3108                    }
3109                }
3110            }
3111        });
3112    }
3113
3114    @Override
3115    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3116            final IntentSender pi) {
3117        mContext.enforceCallingOrSelfPermission(
3118                android.Manifest.permission.CLEAR_APP_CACHE, null);
3119        // Queue up an async operation since clearing cache may take a little while.
3120        mHandler.post(new Runnable() {
3121            public void run() {
3122                mHandler.removeCallbacks(this);
3123                int retCode = -1;
3124                synchronized (mInstallLock) {
3125                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3126                    if (retCode < 0) {
3127                        Slog.w(TAG, "Couldn't clear application caches");
3128                    }
3129                }
3130                if(pi != null) {
3131                    try {
3132                        // Callback via pending intent
3133                        int code = (retCode >= 0) ? 1 : 0;
3134                        pi.sendIntent(null, code, null,
3135                                null, null);
3136                    } catch (SendIntentException e1) {
3137                        Slog.i(TAG, "Failed to send pending intent");
3138                    }
3139                }
3140            }
3141        });
3142    }
3143
3144    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3145        synchronized (mInstallLock) {
3146            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3147                throw new IOException("Failed to free enough space");
3148            }
3149        }
3150    }
3151
3152    /**
3153     * Return if the user key is currently unlocked.
3154     */
3155    private boolean isUserKeyUnlocked(int userId) {
3156        if (StorageManager.isFileBasedEncryptionEnabled()) {
3157            final IMountService mount = IMountService.Stub
3158                    .asInterface(ServiceManager.getService("mount"));
3159            if (mount == null) {
3160                Slog.w(TAG, "Early during boot, assuming locked");
3161                return false;
3162            }
3163            final long token = Binder.clearCallingIdentity();
3164            try {
3165                return mount.isUserKeyUnlocked(userId);
3166            } catch (RemoteException e) {
3167                throw e.rethrowAsRuntimeException();
3168            } finally {
3169                Binder.restoreCallingIdentity(token);
3170            }
3171        } else {
3172            return true;
3173        }
3174    }
3175
3176    /**
3177     * Augment the given flags depending on current user running state. This is
3178     * purposefully done before acquiring {@link #mPackages} lock.
3179     */
3180    private int augmentFlagsForUser(int flags, int userId) {
3181        if (!isUserKeyUnlocked(userId)) {
3182            flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3183        }
3184        return flags;
3185    }
3186
3187    @Override
3188    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3189        if (!sUserManager.exists(userId)) return null;
3190        flags = augmentFlagsForUser(flags, userId);
3191        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3192        synchronized (mPackages) {
3193            PackageParser.Activity a = mActivities.mActivities.get(component);
3194
3195            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3196            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3197                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3198                if (ps == null) return null;
3199                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3200                        userId);
3201            }
3202            if (mResolveComponentName.equals(component)) {
3203                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3204                        new PackageUserState(), userId);
3205            }
3206        }
3207        return null;
3208    }
3209
3210    @Override
3211    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3212            String resolvedType) {
3213        synchronized (mPackages) {
3214            if (component.equals(mResolveComponentName)) {
3215                // The resolver supports EVERYTHING!
3216                return true;
3217            }
3218            PackageParser.Activity a = mActivities.mActivities.get(component);
3219            if (a == null) {
3220                return false;
3221            }
3222            for (int i=0; i<a.intents.size(); i++) {
3223                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3224                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3225                    return true;
3226                }
3227            }
3228            return false;
3229        }
3230    }
3231
3232    @Override
3233    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3234        if (!sUserManager.exists(userId)) return null;
3235        flags = augmentFlagsForUser(flags, userId);
3236        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3237        synchronized (mPackages) {
3238            PackageParser.Activity a = mReceivers.mActivities.get(component);
3239            if (DEBUG_PACKAGE_INFO) Log.v(
3240                TAG, "getReceiverInfo " + component + ": " + a);
3241            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3242                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3243                if (ps == null) return null;
3244                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3245                        userId);
3246            }
3247        }
3248        return null;
3249    }
3250
3251    @Override
3252    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3253        if (!sUserManager.exists(userId)) return null;
3254        flags = augmentFlagsForUser(flags, userId);
3255        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3256        synchronized (mPackages) {
3257            PackageParser.Service s = mServices.mServices.get(component);
3258            if (DEBUG_PACKAGE_INFO) Log.v(
3259                TAG, "getServiceInfo " + component + ": " + s);
3260            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3261                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3262                if (ps == null) return null;
3263                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3264                        userId);
3265            }
3266        }
3267        return null;
3268    }
3269
3270    @Override
3271    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3272        if (!sUserManager.exists(userId)) return null;
3273        flags = augmentFlagsForUser(flags, userId);
3274        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3275        synchronized (mPackages) {
3276            PackageParser.Provider p = mProviders.mProviders.get(component);
3277            if (DEBUG_PACKAGE_INFO) Log.v(
3278                TAG, "getProviderInfo " + component + ": " + p);
3279            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3280                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3281                if (ps == null) return null;
3282                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3283                        userId);
3284            }
3285        }
3286        return null;
3287    }
3288
3289    @Override
3290    public String[] getSystemSharedLibraryNames() {
3291        Set<String> libSet;
3292        synchronized (mPackages) {
3293            libSet = mSharedLibraries.keySet();
3294            int size = libSet.size();
3295            if (size > 0) {
3296                String[] libs = new String[size];
3297                libSet.toArray(libs);
3298                return libs;
3299            }
3300        }
3301        return null;
3302    }
3303
3304    /**
3305     * @hide
3306     */
3307    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3308        synchronized (mPackages) {
3309            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3310            if (lib != null && lib.apk != null) {
3311                return mPackages.get(lib.apk);
3312            }
3313        }
3314        return null;
3315    }
3316
3317    @Override
3318    public FeatureInfo[] getSystemAvailableFeatures() {
3319        Collection<FeatureInfo> featSet;
3320        synchronized (mPackages) {
3321            featSet = mAvailableFeatures.values();
3322            int size = featSet.size();
3323            if (size > 0) {
3324                FeatureInfo[] features = new FeatureInfo[size+1];
3325                featSet.toArray(features);
3326                FeatureInfo fi = new FeatureInfo();
3327                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3328                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3329                features[size] = fi;
3330                return features;
3331            }
3332        }
3333        return null;
3334    }
3335
3336    @Override
3337    public boolean hasSystemFeature(String name) {
3338        synchronized (mPackages) {
3339            return mAvailableFeatures.containsKey(name);
3340        }
3341    }
3342
3343    private void checkValidCaller(int uid, int userId) {
3344        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3345            return;
3346
3347        throw new SecurityException("Caller uid=" + uid
3348                + " is not privileged to communicate with user=" + userId);
3349    }
3350
3351    @Override
3352    public int checkPermission(String permName, String pkgName, int userId) {
3353        if (!sUserManager.exists(userId)) {
3354            return PackageManager.PERMISSION_DENIED;
3355        }
3356
3357        synchronized (mPackages) {
3358            final PackageParser.Package p = mPackages.get(pkgName);
3359            if (p != null && p.mExtras != null) {
3360                final PackageSetting ps = (PackageSetting) p.mExtras;
3361                final PermissionsState permissionsState = ps.getPermissionsState();
3362                if (permissionsState.hasPermission(permName, userId)) {
3363                    return PackageManager.PERMISSION_GRANTED;
3364                }
3365                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3366                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3367                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3368                    return PackageManager.PERMISSION_GRANTED;
3369                }
3370            }
3371        }
3372
3373        return PackageManager.PERMISSION_DENIED;
3374    }
3375
3376    @Override
3377    public int checkUidPermission(String permName, int uid) {
3378        final int userId = UserHandle.getUserId(uid);
3379
3380        if (!sUserManager.exists(userId)) {
3381            return PackageManager.PERMISSION_DENIED;
3382        }
3383
3384        synchronized (mPackages) {
3385            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3386            if (obj != null) {
3387                final SettingBase ps = (SettingBase) obj;
3388                final PermissionsState permissionsState = ps.getPermissionsState();
3389                if (permissionsState.hasPermission(permName, userId)) {
3390                    return PackageManager.PERMISSION_GRANTED;
3391                }
3392                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3393                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3394                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3395                    return PackageManager.PERMISSION_GRANTED;
3396                }
3397            } else {
3398                ArraySet<String> perms = mSystemPermissions.get(uid);
3399                if (perms != null) {
3400                    if (perms.contains(permName)) {
3401                        return PackageManager.PERMISSION_GRANTED;
3402                    }
3403                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3404                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3405                        return PackageManager.PERMISSION_GRANTED;
3406                    }
3407                }
3408            }
3409        }
3410
3411        return PackageManager.PERMISSION_DENIED;
3412    }
3413
3414    @Override
3415    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3416        if (UserHandle.getCallingUserId() != userId) {
3417            mContext.enforceCallingPermission(
3418                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3419                    "isPermissionRevokedByPolicy for user " + userId);
3420        }
3421
3422        if (checkPermission(permission, packageName, userId)
3423                == PackageManager.PERMISSION_GRANTED) {
3424            return false;
3425        }
3426
3427        final long identity = Binder.clearCallingIdentity();
3428        try {
3429            final int flags = getPermissionFlags(permission, packageName, userId);
3430            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3431        } finally {
3432            Binder.restoreCallingIdentity(identity);
3433        }
3434    }
3435
3436    @Override
3437    public String getPermissionControllerPackageName() {
3438        synchronized (mPackages) {
3439            return mRequiredInstallerPackage;
3440        }
3441    }
3442
3443    /**
3444     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3445     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3446     * @param checkShell TODO(yamasani):
3447     * @param message the message to log on security exception
3448     */
3449    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3450            boolean checkShell, String message) {
3451        if (userId < 0) {
3452            throw new IllegalArgumentException("Invalid userId " + userId);
3453        }
3454        if (checkShell) {
3455            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3456        }
3457        if (userId == UserHandle.getUserId(callingUid)) return;
3458        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3459            if (requireFullPermission) {
3460                mContext.enforceCallingOrSelfPermission(
3461                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3462            } else {
3463                try {
3464                    mContext.enforceCallingOrSelfPermission(
3465                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3466                } catch (SecurityException se) {
3467                    mContext.enforceCallingOrSelfPermission(
3468                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3469                }
3470            }
3471        }
3472    }
3473
3474    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3475        if (callingUid == Process.SHELL_UID) {
3476            if (userHandle >= 0
3477                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3478                throw new SecurityException("Shell does not have permission to access user "
3479                        + userHandle);
3480            } else if (userHandle < 0) {
3481                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3482                        + Debug.getCallers(3));
3483            }
3484        }
3485    }
3486
3487    private BasePermission findPermissionTreeLP(String permName) {
3488        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3489            if (permName.startsWith(bp.name) &&
3490                    permName.length() > bp.name.length() &&
3491                    permName.charAt(bp.name.length()) == '.') {
3492                return bp;
3493            }
3494        }
3495        return null;
3496    }
3497
3498    private BasePermission checkPermissionTreeLP(String permName) {
3499        if (permName != null) {
3500            BasePermission bp = findPermissionTreeLP(permName);
3501            if (bp != null) {
3502                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3503                    return bp;
3504                }
3505                throw new SecurityException("Calling uid "
3506                        + Binder.getCallingUid()
3507                        + " is not allowed to add to permission tree "
3508                        + bp.name + " owned by uid " + bp.uid);
3509            }
3510        }
3511        throw new SecurityException("No permission tree found for " + permName);
3512    }
3513
3514    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3515        if (s1 == null) {
3516            return s2 == null;
3517        }
3518        if (s2 == null) {
3519            return false;
3520        }
3521        if (s1.getClass() != s2.getClass()) {
3522            return false;
3523        }
3524        return s1.equals(s2);
3525    }
3526
3527    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3528        if (pi1.icon != pi2.icon) return false;
3529        if (pi1.logo != pi2.logo) return false;
3530        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3531        if (!compareStrings(pi1.name, pi2.name)) return false;
3532        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3533        // We'll take care of setting this one.
3534        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3535        // These are not currently stored in settings.
3536        //if (!compareStrings(pi1.group, pi2.group)) return false;
3537        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3538        //if (pi1.labelRes != pi2.labelRes) return false;
3539        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3540        return true;
3541    }
3542
3543    int permissionInfoFootprint(PermissionInfo info) {
3544        int size = info.name.length();
3545        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3546        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3547        return size;
3548    }
3549
3550    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3551        int size = 0;
3552        for (BasePermission perm : mSettings.mPermissions.values()) {
3553            if (perm.uid == tree.uid) {
3554                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3555            }
3556        }
3557        return size;
3558    }
3559
3560    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3561        // We calculate the max size of permissions defined by this uid and throw
3562        // if that plus the size of 'info' would exceed our stated maximum.
3563        if (tree.uid != Process.SYSTEM_UID) {
3564            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3565            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3566                throw new SecurityException("Permission tree size cap exceeded");
3567            }
3568        }
3569    }
3570
3571    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3572        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3573            throw new SecurityException("Label must be specified in permission");
3574        }
3575        BasePermission tree = checkPermissionTreeLP(info.name);
3576        BasePermission bp = mSettings.mPermissions.get(info.name);
3577        boolean added = bp == null;
3578        boolean changed = true;
3579        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3580        if (added) {
3581            enforcePermissionCapLocked(info, tree);
3582            bp = new BasePermission(info.name, tree.sourcePackage,
3583                    BasePermission.TYPE_DYNAMIC);
3584        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3585            throw new SecurityException(
3586                    "Not allowed to modify non-dynamic permission "
3587                    + info.name);
3588        } else {
3589            if (bp.protectionLevel == fixedLevel
3590                    && bp.perm.owner.equals(tree.perm.owner)
3591                    && bp.uid == tree.uid
3592                    && comparePermissionInfos(bp.perm.info, info)) {
3593                changed = false;
3594            }
3595        }
3596        bp.protectionLevel = fixedLevel;
3597        info = new PermissionInfo(info);
3598        info.protectionLevel = fixedLevel;
3599        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3600        bp.perm.info.packageName = tree.perm.info.packageName;
3601        bp.uid = tree.uid;
3602        if (added) {
3603            mSettings.mPermissions.put(info.name, bp);
3604        }
3605        if (changed) {
3606            if (!async) {
3607                mSettings.writeLPr();
3608            } else {
3609                scheduleWriteSettingsLocked();
3610            }
3611        }
3612        return added;
3613    }
3614
3615    @Override
3616    public boolean addPermission(PermissionInfo info) {
3617        synchronized (mPackages) {
3618            return addPermissionLocked(info, false);
3619        }
3620    }
3621
3622    @Override
3623    public boolean addPermissionAsync(PermissionInfo info) {
3624        synchronized (mPackages) {
3625            return addPermissionLocked(info, true);
3626        }
3627    }
3628
3629    @Override
3630    public void removePermission(String name) {
3631        synchronized (mPackages) {
3632            checkPermissionTreeLP(name);
3633            BasePermission bp = mSettings.mPermissions.get(name);
3634            if (bp != null) {
3635                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3636                    throw new SecurityException(
3637                            "Not allowed to modify non-dynamic permission "
3638                            + name);
3639                }
3640                mSettings.mPermissions.remove(name);
3641                mSettings.writeLPr();
3642            }
3643        }
3644    }
3645
3646    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3647            BasePermission bp) {
3648        int index = pkg.requestedPermissions.indexOf(bp.name);
3649        if (index == -1) {
3650            throw new SecurityException("Package " + pkg.packageName
3651                    + " has not requested permission " + bp.name);
3652        }
3653        if (!bp.isRuntime() && !bp.isDevelopment()) {
3654            throw new SecurityException("Permission " + bp.name
3655                    + " is not a changeable permission type");
3656        }
3657    }
3658
3659    @Override
3660    public void grantRuntimePermission(String packageName, String name, final int userId) {
3661        if (!sUserManager.exists(userId)) {
3662            Log.e(TAG, "No such user:" + userId);
3663            return;
3664        }
3665
3666        mContext.enforceCallingOrSelfPermission(
3667                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3668                "grantRuntimePermission");
3669
3670        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3671                "grantRuntimePermission");
3672
3673        final int uid;
3674        final SettingBase sb;
3675
3676        synchronized (mPackages) {
3677            final PackageParser.Package pkg = mPackages.get(packageName);
3678            if (pkg == null) {
3679                throw new IllegalArgumentException("Unknown package: " + packageName);
3680            }
3681
3682            final BasePermission bp = mSettings.mPermissions.get(name);
3683            if (bp == null) {
3684                throw new IllegalArgumentException("Unknown permission: " + name);
3685            }
3686
3687            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3688
3689            // If a permission review is required for legacy apps we represent
3690            // their permissions as always granted runtime ones since we need
3691            // to keep the review required permission flag per user while an
3692            // install permission's state is shared across all users.
3693            if (Build.PERMISSIONS_REVIEW_REQUIRED
3694                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3695                    && bp.isRuntime()) {
3696                return;
3697            }
3698
3699            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3700            sb = (SettingBase) pkg.mExtras;
3701            if (sb == null) {
3702                throw new IllegalArgumentException("Unknown package: " + packageName);
3703            }
3704
3705            final PermissionsState permissionsState = sb.getPermissionsState();
3706
3707            final int flags = permissionsState.getPermissionFlags(name, userId);
3708            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3709                throw new SecurityException("Cannot grant system fixed permission: "
3710                        + name + " for package: " + packageName);
3711            }
3712
3713            if (bp.isDevelopment()) {
3714                // Development permissions must be handled specially, since they are not
3715                // normal runtime permissions.  For now they apply to all users.
3716                if (permissionsState.grantInstallPermission(bp) !=
3717                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3718                    scheduleWriteSettingsLocked();
3719                }
3720                return;
3721            }
3722
3723            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3724                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3725                return;
3726            }
3727
3728            final int result = permissionsState.grantRuntimePermission(bp, userId);
3729            switch (result) {
3730                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3731                    return;
3732                }
3733
3734                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3735                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3736                    mHandler.post(new Runnable() {
3737                        @Override
3738                        public void run() {
3739                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3740                        }
3741                    });
3742                }
3743                break;
3744            }
3745
3746            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3747
3748            // Not critical if that is lost - app has to request again.
3749            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3750        }
3751
3752        // Only need to do this if user is initialized. Otherwise it's a new user
3753        // and there are no processes running as the user yet and there's no need
3754        // to make an expensive call to remount processes for the changed permissions.
3755        if (READ_EXTERNAL_STORAGE.equals(name)
3756                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3757            final long token = Binder.clearCallingIdentity();
3758            try {
3759                if (sUserManager.isInitialized(userId)) {
3760                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3761                            MountServiceInternal.class);
3762                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3763                }
3764            } finally {
3765                Binder.restoreCallingIdentity(token);
3766            }
3767        }
3768    }
3769
3770    @Override
3771    public void revokeRuntimePermission(String packageName, String name, int userId) {
3772        if (!sUserManager.exists(userId)) {
3773            Log.e(TAG, "No such user:" + userId);
3774            return;
3775        }
3776
3777        mContext.enforceCallingOrSelfPermission(
3778                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3779                "revokeRuntimePermission");
3780
3781        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3782                "revokeRuntimePermission");
3783
3784        final int appId;
3785
3786        synchronized (mPackages) {
3787            final PackageParser.Package pkg = mPackages.get(packageName);
3788            if (pkg == null) {
3789                throw new IllegalArgumentException("Unknown package: " + packageName);
3790            }
3791
3792            final BasePermission bp = mSettings.mPermissions.get(name);
3793            if (bp == null) {
3794                throw new IllegalArgumentException("Unknown permission: " + name);
3795            }
3796
3797            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3798
3799            // If a permission review is required for legacy apps we represent
3800            // their permissions as always granted runtime ones since we need
3801            // to keep the review required permission flag per user while an
3802            // install permission's state is shared across all users.
3803            if (Build.PERMISSIONS_REVIEW_REQUIRED
3804                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3805                    && bp.isRuntime()) {
3806                return;
3807            }
3808
3809            SettingBase sb = (SettingBase) pkg.mExtras;
3810            if (sb == null) {
3811                throw new IllegalArgumentException("Unknown package: " + packageName);
3812            }
3813
3814            final PermissionsState permissionsState = sb.getPermissionsState();
3815
3816            final int flags = permissionsState.getPermissionFlags(name, userId);
3817            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3818                throw new SecurityException("Cannot revoke system fixed permission: "
3819                        + name + " for package: " + packageName);
3820            }
3821
3822            if (bp.isDevelopment()) {
3823                // Development permissions must be handled specially, since they are not
3824                // normal runtime permissions.  For now they apply to all users.
3825                if (permissionsState.revokeInstallPermission(bp) !=
3826                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3827                    scheduleWriteSettingsLocked();
3828                }
3829                return;
3830            }
3831
3832            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3833                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3834                return;
3835            }
3836
3837            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3838
3839            // Critical, after this call app should never have the permission.
3840            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3841
3842            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3843        }
3844
3845        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3846    }
3847
3848    @Override
3849    public void resetRuntimePermissions() {
3850        mContext.enforceCallingOrSelfPermission(
3851                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3852                "revokeRuntimePermission");
3853
3854        int callingUid = Binder.getCallingUid();
3855        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3856            mContext.enforceCallingOrSelfPermission(
3857                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3858                    "resetRuntimePermissions");
3859        }
3860
3861        synchronized (mPackages) {
3862            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3863            for (int userId : UserManagerService.getInstance().getUserIds()) {
3864                final int packageCount = mPackages.size();
3865                for (int i = 0; i < packageCount; i++) {
3866                    PackageParser.Package pkg = mPackages.valueAt(i);
3867                    if (!(pkg.mExtras instanceof PackageSetting)) {
3868                        continue;
3869                    }
3870                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3871                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3872                }
3873            }
3874        }
3875    }
3876
3877    @Override
3878    public int getPermissionFlags(String name, String packageName, int userId) {
3879        if (!sUserManager.exists(userId)) {
3880            return 0;
3881        }
3882
3883        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3884
3885        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3886                "getPermissionFlags");
3887
3888        synchronized (mPackages) {
3889            final PackageParser.Package pkg = mPackages.get(packageName);
3890            if (pkg == null) {
3891                throw new IllegalArgumentException("Unknown package: " + packageName);
3892            }
3893
3894            final BasePermission bp = mSettings.mPermissions.get(name);
3895            if (bp == null) {
3896                throw new IllegalArgumentException("Unknown permission: " + name);
3897            }
3898
3899            SettingBase sb = (SettingBase) pkg.mExtras;
3900            if (sb == null) {
3901                throw new IllegalArgumentException("Unknown package: " + packageName);
3902            }
3903
3904            PermissionsState permissionsState = sb.getPermissionsState();
3905            return permissionsState.getPermissionFlags(name, userId);
3906        }
3907    }
3908
3909    @Override
3910    public void updatePermissionFlags(String name, String packageName, int flagMask,
3911            int flagValues, int userId) {
3912        if (!sUserManager.exists(userId)) {
3913            return;
3914        }
3915
3916        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3917
3918        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3919                "updatePermissionFlags");
3920
3921        // Only the system can change these flags and nothing else.
3922        if (getCallingUid() != Process.SYSTEM_UID) {
3923            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3924            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3925            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3926            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3927            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3928        }
3929
3930        synchronized (mPackages) {
3931            final PackageParser.Package pkg = mPackages.get(packageName);
3932            if (pkg == null) {
3933                throw new IllegalArgumentException("Unknown package: " + packageName);
3934            }
3935
3936            final BasePermission bp = mSettings.mPermissions.get(name);
3937            if (bp == null) {
3938                throw new IllegalArgumentException("Unknown permission: " + name);
3939            }
3940
3941            SettingBase sb = (SettingBase) pkg.mExtras;
3942            if (sb == null) {
3943                throw new IllegalArgumentException("Unknown package: " + packageName);
3944            }
3945
3946            PermissionsState permissionsState = sb.getPermissionsState();
3947
3948            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3949
3950            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3951                // Install and runtime permissions are stored in different places,
3952                // so figure out what permission changed and persist the change.
3953                if (permissionsState.getInstallPermissionState(name) != null) {
3954                    scheduleWriteSettingsLocked();
3955                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3956                        || hadState) {
3957                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3958                }
3959            }
3960        }
3961    }
3962
3963    /**
3964     * Update the permission flags for all packages and runtime permissions of a user in order
3965     * to allow device or profile owner to remove POLICY_FIXED.
3966     */
3967    @Override
3968    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3969        if (!sUserManager.exists(userId)) {
3970            return;
3971        }
3972
3973        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3974
3975        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3976                "updatePermissionFlagsForAllApps");
3977
3978        // Only the system can change system fixed flags.
3979        if (getCallingUid() != Process.SYSTEM_UID) {
3980            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3981            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3982        }
3983
3984        synchronized (mPackages) {
3985            boolean changed = false;
3986            final int packageCount = mPackages.size();
3987            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3988                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3989                SettingBase sb = (SettingBase) pkg.mExtras;
3990                if (sb == null) {
3991                    continue;
3992                }
3993                PermissionsState permissionsState = sb.getPermissionsState();
3994                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3995                        userId, flagMask, flagValues);
3996            }
3997            if (changed) {
3998                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3999            }
4000        }
4001    }
4002
4003    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4004        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4005                != PackageManager.PERMISSION_GRANTED
4006            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4007                != PackageManager.PERMISSION_GRANTED) {
4008            throw new SecurityException(message + " requires "
4009                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4010                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4011        }
4012    }
4013
4014    @Override
4015    public boolean shouldShowRequestPermissionRationale(String permissionName,
4016            String packageName, int userId) {
4017        if (UserHandle.getCallingUserId() != userId) {
4018            mContext.enforceCallingPermission(
4019                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4020                    "canShowRequestPermissionRationale for user " + userId);
4021        }
4022
4023        final int uid = getPackageUid(packageName, userId);
4024        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4025            return false;
4026        }
4027
4028        if (checkPermission(permissionName, packageName, userId)
4029                == PackageManager.PERMISSION_GRANTED) {
4030            return false;
4031        }
4032
4033        final int flags;
4034
4035        final long identity = Binder.clearCallingIdentity();
4036        try {
4037            flags = getPermissionFlags(permissionName,
4038                    packageName, userId);
4039        } finally {
4040            Binder.restoreCallingIdentity(identity);
4041        }
4042
4043        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4044                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4045                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4046
4047        if ((flags & fixedFlags) != 0) {
4048            return false;
4049        }
4050
4051        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4052    }
4053
4054    @Override
4055    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4056        mContext.enforceCallingOrSelfPermission(
4057                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4058                "addOnPermissionsChangeListener");
4059
4060        synchronized (mPackages) {
4061            mOnPermissionChangeListeners.addListenerLocked(listener);
4062        }
4063    }
4064
4065    @Override
4066    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4067        synchronized (mPackages) {
4068            mOnPermissionChangeListeners.removeListenerLocked(listener);
4069        }
4070    }
4071
4072    @Override
4073    public boolean isProtectedBroadcast(String actionName) {
4074        synchronized (mPackages) {
4075            return mProtectedBroadcasts.contains(actionName);
4076        }
4077    }
4078
4079    @Override
4080    public int checkSignatures(String pkg1, String pkg2) {
4081        synchronized (mPackages) {
4082            final PackageParser.Package p1 = mPackages.get(pkg1);
4083            final PackageParser.Package p2 = mPackages.get(pkg2);
4084            if (p1 == null || p1.mExtras == null
4085                    || p2 == null || p2.mExtras == null) {
4086                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4087            }
4088            return compareSignatures(p1.mSignatures, p2.mSignatures);
4089        }
4090    }
4091
4092    @Override
4093    public int checkUidSignatures(int uid1, int uid2) {
4094        // Map to base uids.
4095        uid1 = UserHandle.getAppId(uid1);
4096        uid2 = UserHandle.getAppId(uid2);
4097        // reader
4098        synchronized (mPackages) {
4099            Signature[] s1;
4100            Signature[] s2;
4101            Object obj = mSettings.getUserIdLPr(uid1);
4102            if (obj != null) {
4103                if (obj instanceof SharedUserSetting) {
4104                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4105                } else if (obj instanceof PackageSetting) {
4106                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4107                } else {
4108                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4109                }
4110            } else {
4111                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4112            }
4113            obj = mSettings.getUserIdLPr(uid2);
4114            if (obj != null) {
4115                if (obj instanceof SharedUserSetting) {
4116                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4117                } else if (obj instanceof PackageSetting) {
4118                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4119                } else {
4120                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4121                }
4122            } else {
4123                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4124            }
4125            return compareSignatures(s1, s2);
4126        }
4127    }
4128
4129    private void killUid(int appId, int userId, String reason) {
4130        final long identity = Binder.clearCallingIdentity();
4131        try {
4132            IActivityManager am = ActivityManagerNative.getDefault();
4133            if (am != null) {
4134                try {
4135                    am.killUid(appId, userId, reason);
4136                } catch (RemoteException e) {
4137                    /* ignore - same process */
4138                }
4139            }
4140        } finally {
4141            Binder.restoreCallingIdentity(identity);
4142        }
4143    }
4144
4145    /**
4146     * Compares two sets of signatures. Returns:
4147     * <br />
4148     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4149     * <br />
4150     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4151     * <br />
4152     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4153     * <br />
4154     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4155     * <br />
4156     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4157     */
4158    static int compareSignatures(Signature[] s1, Signature[] s2) {
4159        if (s1 == null) {
4160            return s2 == null
4161                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4162                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4163        }
4164
4165        if (s2 == null) {
4166            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4167        }
4168
4169        if (s1.length != s2.length) {
4170            return PackageManager.SIGNATURE_NO_MATCH;
4171        }
4172
4173        // Since both signature sets are of size 1, we can compare without HashSets.
4174        if (s1.length == 1) {
4175            return s1[0].equals(s2[0]) ?
4176                    PackageManager.SIGNATURE_MATCH :
4177                    PackageManager.SIGNATURE_NO_MATCH;
4178        }
4179
4180        ArraySet<Signature> set1 = new ArraySet<Signature>();
4181        for (Signature sig : s1) {
4182            set1.add(sig);
4183        }
4184        ArraySet<Signature> set2 = new ArraySet<Signature>();
4185        for (Signature sig : s2) {
4186            set2.add(sig);
4187        }
4188        // Make sure s2 contains all signatures in s1.
4189        if (set1.equals(set2)) {
4190            return PackageManager.SIGNATURE_MATCH;
4191        }
4192        return PackageManager.SIGNATURE_NO_MATCH;
4193    }
4194
4195    /**
4196     * If the database version for this type of package (internal storage or
4197     * external storage) is less than the version where package signatures
4198     * were updated, return true.
4199     */
4200    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4201        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4202        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4203    }
4204
4205    /**
4206     * Used for backward compatibility to make sure any packages with
4207     * certificate chains get upgraded to the new style. {@code existingSigs}
4208     * will be in the old format (since they were stored on disk from before the
4209     * system upgrade) and {@code scannedSigs} will be in the newer format.
4210     */
4211    private int compareSignaturesCompat(PackageSignatures existingSigs,
4212            PackageParser.Package scannedPkg) {
4213        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4214            return PackageManager.SIGNATURE_NO_MATCH;
4215        }
4216
4217        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4218        for (Signature sig : existingSigs.mSignatures) {
4219            existingSet.add(sig);
4220        }
4221        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4222        for (Signature sig : scannedPkg.mSignatures) {
4223            try {
4224                Signature[] chainSignatures = sig.getChainSignatures();
4225                for (Signature chainSig : chainSignatures) {
4226                    scannedCompatSet.add(chainSig);
4227                }
4228            } catch (CertificateEncodingException e) {
4229                scannedCompatSet.add(sig);
4230            }
4231        }
4232        /*
4233         * Make sure the expanded scanned set contains all signatures in the
4234         * existing one.
4235         */
4236        if (scannedCompatSet.equals(existingSet)) {
4237            // Migrate the old signatures to the new scheme.
4238            existingSigs.assignSignatures(scannedPkg.mSignatures);
4239            // The new KeySets will be re-added later in the scanning process.
4240            synchronized (mPackages) {
4241                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4242            }
4243            return PackageManager.SIGNATURE_MATCH;
4244        }
4245        return PackageManager.SIGNATURE_NO_MATCH;
4246    }
4247
4248    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4249        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4250        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4251    }
4252
4253    private int compareSignaturesRecover(PackageSignatures existingSigs,
4254            PackageParser.Package scannedPkg) {
4255        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4256            return PackageManager.SIGNATURE_NO_MATCH;
4257        }
4258
4259        String msg = null;
4260        try {
4261            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4262                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4263                        + scannedPkg.packageName);
4264                return PackageManager.SIGNATURE_MATCH;
4265            }
4266        } catch (CertificateException e) {
4267            msg = e.getMessage();
4268        }
4269
4270        logCriticalInfo(Log.INFO,
4271                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4272        return PackageManager.SIGNATURE_NO_MATCH;
4273    }
4274
4275    @Override
4276    public String[] getPackagesForUid(int uid) {
4277        uid = UserHandle.getAppId(uid);
4278        // reader
4279        synchronized (mPackages) {
4280            Object obj = mSettings.getUserIdLPr(uid);
4281            if (obj instanceof SharedUserSetting) {
4282                final SharedUserSetting sus = (SharedUserSetting) obj;
4283                final int N = sus.packages.size();
4284                final String[] res = new String[N];
4285                final Iterator<PackageSetting> it = sus.packages.iterator();
4286                int i = 0;
4287                while (it.hasNext()) {
4288                    res[i++] = it.next().name;
4289                }
4290                return res;
4291            } else if (obj instanceof PackageSetting) {
4292                final PackageSetting ps = (PackageSetting) obj;
4293                return new String[] { ps.name };
4294            }
4295        }
4296        return null;
4297    }
4298
4299    @Override
4300    public String getNameForUid(int uid) {
4301        // reader
4302        synchronized (mPackages) {
4303            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4304            if (obj instanceof SharedUserSetting) {
4305                final SharedUserSetting sus = (SharedUserSetting) obj;
4306                return sus.name + ":" + sus.userId;
4307            } else if (obj instanceof PackageSetting) {
4308                final PackageSetting ps = (PackageSetting) obj;
4309                return ps.name;
4310            }
4311        }
4312        return null;
4313    }
4314
4315    @Override
4316    public int getUidForSharedUser(String sharedUserName) {
4317        if(sharedUserName == null) {
4318            return -1;
4319        }
4320        // reader
4321        synchronized (mPackages) {
4322            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4323            if (suid == null) {
4324                return -1;
4325            }
4326            return suid.userId;
4327        }
4328    }
4329
4330    @Override
4331    public int getFlagsForUid(int uid) {
4332        synchronized (mPackages) {
4333            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4334            if (obj instanceof SharedUserSetting) {
4335                final SharedUserSetting sus = (SharedUserSetting) obj;
4336                return sus.pkgFlags;
4337            } else if (obj instanceof PackageSetting) {
4338                final PackageSetting ps = (PackageSetting) obj;
4339                return ps.pkgFlags;
4340            }
4341        }
4342        return 0;
4343    }
4344
4345    @Override
4346    public int getPrivateFlagsForUid(int uid) {
4347        synchronized (mPackages) {
4348            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4349            if (obj instanceof SharedUserSetting) {
4350                final SharedUserSetting sus = (SharedUserSetting) obj;
4351                return sus.pkgPrivateFlags;
4352            } else if (obj instanceof PackageSetting) {
4353                final PackageSetting ps = (PackageSetting) obj;
4354                return ps.pkgPrivateFlags;
4355            }
4356        }
4357        return 0;
4358    }
4359
4360    @Override
4361    public boolean isUidPrivileged(int uid) {
4362        uid = UserHandle.getAppId(uid);
4363        // reader
4364        synchronized (mPackages) {
4365            Object obj = mSettings.getUserIdLPr(uid);
4366            if (obj instanceof SharedUserSetting) {
4367                final SharedUserSetting sus = (SharedUserSetting) obj;
4368                final Iterator<PackageSetting> it = sus.packages.iterator();
4369                while (it.hasNext()) {
4370                    if (it.next().isPrivileged()) {
4371                        return true;
4372                    }
4373                }
4374            } else if (obj instanceof PackageSetting) {
4375                final PackageSetting ps = (PackageSetting) obj;
4376                return ps.isPrivileged();
4377            }
4378        }
4379        return false;
4380    }
4381
4382    @Override
4383    public String[] getAppOpPermissionPackages(String permissionName) {
4384        synchronized (mPackages) {
4385            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4386            if (pkgs == null) {
4387                return null;
4388            }
4389            return pkgs.toArray(new String[pkgs.size()]);
4390        }
4391    }
4392
4393    @Override
4394    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4395            int flags, int userId) {
4396        if (!sUserManager.exists(userId)) return null;
4397        flags = augmentFlagsForUser(flags, userId);
4398        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4399        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4400        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4401    }
4402
4403    @Override
4404    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4405            IntentFilter filter, int match, ComponentName activity) {
4406        final int userId = UserHandle.getCallingUserId();
4407        if (DEBUG_PREFERRED) {
4408            Log.v(TAG, "setLastChosenActivity intent=" + intent
4409                + " resolvedType=" + resolvedType
4410                + " flags=" + flags
4411                + " filter=" + filter
4412                + " match=" + match
4413                + " activity=" + activity);
4414            filter.dump(new PrintStreamPrinter(System.out), "    ");
4415        }
4416        intent.setComponent(null);
4417        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4418        // Find any earlier preferred or last chosen entries and nuke them
4419        findPreferredActivity(intent, resolvedType,
4420                flags, query, 0, false, true, false, userId);
4421        // Add the new activity as the last chosen for this filter
4422        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4423                "Setting last chosen");
4424    }
4425
4426    @Override
4427    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4428        final int userId = UserHandle.getCallingUserId();
4429        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4430        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4431        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4432                false, false, false, userId);
4433    }
4434
4435    private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) {
4436        MessageDigest digest = null;
4437        try {
4438            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4439        } catch (NoSuchAlgorithmException e) {
4440            // If we can't create a digest, ignore ephemeral apps.
4441            return false;
4442        }
4443
4444        final byte[] hostBytes = intent.getData().getHost().getBytes();
4445        final byte[] digestBytes = digest.digest(hostBytes);
4446        int shaPrefix =
4447                digestBytes[0] << 24
4448                | digestBytes[1] << 16
4449                | digestBytes[2] << 8
4450                | digestBytes[3] << 0;
4451        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4452                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4453        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4454            // No hash prefix match; there are no ephemeral apps for this domain.
4455            return false;
4456        }
4457        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4458            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4459            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4460                continue;
4461            }
4462            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4463            // No filters; this should never happen.
4464            if (filters.isEmpty()) {
4465                continue;
4466            }
4467            // We have a domain match; resolve the filters to see if anything matches.
4468            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4469            for (int j = filters.size() - 1; j >= 0; --j) {
4470                ephemeralResolver.addFilter(filters.get(j));
4471            }
4472            List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent(
4473                    intent, resolvedType, false /*defaultOnly*/, userId);
4474            return !ephemeralResolveList.isEmpty();
4475        }
4476        // Hash or filter mis-match; no ephemeral apps for this domain.
4477        return false;
4478    }
4479
4480    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4481            int flags, List<ResolveInfo> query, int userId) {
4482        final boolean isWebUri = hasWebURI(intent);
4483        // Check whether or not an ephemeral app exists to handle the URI.
4484        if (isWebUri && mEphemeralResolverConnection != null) {
4485            // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution.
4486            boolean hasAlwaysHandler = false;
4487            synchronized (mPackages) {
4488                final int count = query.size();
4489                for (int n=0; n<count; n++) {
4490                    ResolveInfo info = query.get(n);
4491                    String packageName = info.activityInfo.packageName;
4492                    PackageSetting ps = mSettings.mPackages.get(packageName);
4493                    if (ps != null) {
4494                        // Try to get the status from User settings first
4495                        long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4496                        int status = (int) (packedStatus >> 32);
4497                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4498                                || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4499                            hasAlwaysHandler = true;
4500                            break;
4501                        }
4502                    }
4503                }
4504            }
4505
4506            // Only consider installing an ephemeral app if there isn't already a verified handler.
4507            // We've determined that there's an ephemeral app available for the URI, ignore any
4508            // ResolveInfo's and just return the ephemeral installer
4509            if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) {
4510                if (DEBUG_EPHEMERAL) {
4511                    Slog.v(TAG, "Resolving to the ephemeral installer");
4512                }
4513                // ditch the result and return a ResolveInfo to launch the ephemeral installer
4514                ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo);
4515                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4516                // make a deep copy of the applicationInfo
4517                ri.activityInfo.applicationInfo = new ApplicationInfo(
4518                        ri.activityInfo.applicationInfo);
4519                if (userId != 0) {
4520                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4521                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4522                }
4523                return ri;
4524            }
4525        }
4526        if (query != null) {
4527            final int N = query.size();
4528            if (N == 1) {
4529                return query.get(0);
4530            } else if (N > 1) {
4531                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4532                // If there is more than one activity with the same priority,
4533                // then let the user decide between them.
4534                ResolveInfo r0 = query.get(0);
4535                ResolveInfo r1 = query.get(1);
4536                if (DEBUG_INTENT_MATCHING || debug) {
4537                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4538                            + r1.activityInfo.name + "=" + r1.priority);
4539                }
4540                // If the first activity has a higher priority, or a different
4541                // default, then it is always desireable to pick it.
4542                if (r0.priority != r1.priority
4543                        || r0.preferredOrder != r1.preferredOrder
4544                        || r0.isDefault != r1.isDefault) {
4545                    return query.get(0);
4546                }
4547                // If we have saved a preference for a preferred activity for
4548                // this Intent, use that.
4549                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4550                        flags, query, r0.priority, true, false, debug, userId);
4551                if (ri != null) {
4552                    return ri;
4553                }
4554                ri = new ResolveInfo(mResolveInfo);
4555                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4556                ri.activityInfo.applicationInfo = new ApplicationInfo(
4557                        ri.activityInfo.applicationInfo);
4558                if (userId != 0) {
4559                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4560                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4561                }
4562                // Make sure that the resolver is displayable in car mode
4563                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4564                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4565                return ri;
4566            }
4567        }
4568        return null;
4569    }
4570
4571    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4572            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4573        final int N = query.size();
4574        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4575                .get(userId);
4576        // Get the list of persistent preferred activities that handle the intent
4577        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4578        List<PersistentPreferredActivity> pprefs = ppir != null
4579                ? ppir.queryIntent(intent, resolvedType,
4580                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4581                : null;
4582        if (pprefs != null && pprefs.size() > 0) {
4583            final int M = pprefs.size();
4584            for (int i=0; i<M; i++) {
4585                final PersistentPreferredActivity ppa = pprefs.get(i);
4586                if (DEBUG_PREFERRED || debug) {
4587                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4588                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4589                            + "\n  component=" + ppa.mComponent);
4590                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4591                }
4592                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4593                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4594                if (DEBUG_PREFERRED || debug) {
4595                    Slog.v(TAG, "Found persistent preferred activity:");
4596                    if (ai != null) {
4597                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4598                    } else {
4599                        Slog.v(TAG, "  null");
4600                    }
4601                }
4602                if (ai == null) {
4603                    // This previously registered persistent preferred activity
4604                    // component is no longer known. Ignore it and do NOT remove it.
4605                    continue;
4606                }
4607                for (int j=0; j<N; j++) {
4608                    final ResolveInfo ri = query.get(j);
4609                    if (!ri.activityInfo.applicationInfo.packageName
4610                            .equals(ai.applicationInfo.packageName)) {
4611                        continue;
4612                    }
4613                    if (!ri.activityInfo.name.equals(ai.name)) {
4614                        continue;
4615                    }
4616                    //  Found a persistent preference that can handle the intent.
4617                    if (DEBUG_PREFERRED || debug) {
4618                        Slog.v(TAG, "Returning persistent preferred activity: " +
4619                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4620                    }
4621                    return ri;
4622                }
4623            }
4624        }
4625        return null;
4626    }
4627
4628    // TODO: handle preferred activities missing while user has amnesia
4629    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4630            List<ResolveInfo> query, int priority, boolean always,
4631            boolean removeMatches, boolean debug, int userId) {
4632        if (!sUserManager.exists(userId)) return null;
4633        flags = augmentFlagsForUser(flags, userId);
4634        // writer
4635        synchronized (mPackages) {
4636            if (intent.getSelector() != null) {
4637                intent = intent.getSelector();
4638            }
4639            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4640
4641            // Try to find a matching persistent preferred activity.
4642            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4643                    debug, userId);
4644
4645            // If a persistent preferred activity matched, use it.
4646            if (pri != null) {
4647                return pri;
4648            }
4649
4650            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4651            // Get the list of preferred activities that handle the intent
4652            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4653            List<PreferredActivity> prefs = pir != null
4654                    ? pir.queryIntent(intent, resolvedType,
4655                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4656                    : null;
4657            if (prefs != null && prefs.size() > 0) {
4658                boolean changed = false;
4659                try {
4660                    // First figure out how good the original match set is.
4661                    // We will only allow preferred activities that came
4662                    // from the same match quality.
4663                    int match = 0;
4664
4665                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4666
4667                    final int N = query.size();
4668                    for (int j=0; j<N; j++) {
4669                        final ResolveInfo ri = query.get(j);
4670                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4671                                + ": 0x" + Integer.toHexString(match));
4672                        if (ri.match > match) {
4673                            match = ri.match;
4674                        }
4675                    }
4676
4677                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4678                            + Integer.toHexString(match));
4679
4680                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4681                    final int M = prefs.size();
4682                    for (int i=0; i<M; i++) {
4683                        final PreferredActivity pa = prefs.get(i);
4684                        if (DEBUG_PREFERRED || debug) {
4685                            Slog.v(TAG, "Checking PreferredActivity ds="
4686                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4687                                    + "\n  component=" + pa.mPref.mComponent);
4688                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4689                        }
4690                        if (pa.mPref.mMatch != match) {
4691                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4692                                    + Integer.toHexString(pa.mPref.mMatch));
4693                            continue;
4694                        }
4695                        // If it's not an "always" type preferred activity and that's what we're
4696                        // looking for, skip it.
4697                        if (always && !pa.mPref.mAlways) {
4698                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4699                            continue;
4700                        }
4701                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4702                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4703                        if (DEBUG_PREFERRED || debug) {
4704                            Slog.v(TAG, "Found preferred activity:");
4705                            if (ai != null) {
4706                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4707                            } else {
4708                                Slog.v(TAG, "  null");
4709                            }
4710                        }
4711                        if (ai == null) {
4712                            // This previously registered preferred activity
4713                            // component is no longer known.  Most likely an update
4714                            // to the app was installed and in the new version this
4715                            // component no longer exists.  Clean it up by removing
4716                            // it from the preferred activities list, and skip it.
4717                            Slog.w(TAG, "Removing dangling preferred activity: "
4718                                    + pa.mPref.mComponent);
4719                            pir.removeFilter(pa);
4720                            changed = true;
4721                            continue;
4722                        }
4723                        for (int j=0; j<N; j++) {
4724                            final ResolveInfo ri = query.get(j);
4725                            if (!ri.activityInfo.applicationInfo.packageName
4726                                    .equals(ai.applicationInfo.packageName)) {
4727                                continue;
4728                            }
4729                            if (!ri.activityInfo.name.equals(ai.name)) {
4730                                continue;
4731                            }
4732
4733                            if (removeMatches) {
4734                                pir.removeFilter(pa);
4735                                changed = true;
4736                                if (DEBUG_PREFERRED) {
4737                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4738                                }
4739                                break;
4740                            }
4741
4742                            // Okay we found a previously set preferred or last chosen app.
4743                            // If the result set is different from when this
4744                            // was created, we need to clear it and re-ask the
4745                            // user their preference, if we're looking for an "always" type entry.
4746                            if (always && !pa.mPref.sameSet(query)) {
4747                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4748                                        + intent + " type " + resolvedType);
4749                                if (DEBUG_PREFERRED) {
4750                                    Slog.v(TAG, "Removing preferred activity since set changed "
4751                                            + pa.mPref.mComponent);
4752                                }
4753                                pir.removeFilter(pa);
4754                                // Re-add the filter as a "last chosen" entry (!always)
4755                                PreferredActivity lastChosen = new PreferredActivity(
4756                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4757                                pir.addFilter(lastChosen);
4758                                changed = true;
4759                                return null;
4760                            }
4761
4762                            // Yay! Either the set matched or we're looking for the last chosen
4763                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4764                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4765                            return ri;
4766                        }
4767                    }
4768                } finally {
4769                    if (changed) {
4770                        if (DEBUG_PREFERRED) {
4771                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4772                        }
4773                        scheduleWritePackageRestrictionsLocked(userId);
4774                    }
4775                }
4776            }
4777        }
4778        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4779        return null;
4780    }
4781
4782    /*
4783     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4784     */
4785    @Override
4786    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4787            int targetUserId) {
4788        mContext.enforceCallingOrSelfPermission(
4789                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4790        List<CrossProfileIntentFilter> matches =
4791                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4792        if (matches != null) {
4793            int size = matches.size();
4794            for (int i = 0; i < size; i++) {
4795                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4796            }
4797        }
4798        if (hasWebURI(intent)) {
4799            // cross-profile app linking works only towards the parent.
4800            final UserInfo parent = getProfileParent(sourceUserId);
4801            synchronized(mPackages) {
4802                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4803                        intent, resolvedType, 0, sourceUserId, parent.id);
4804                return xpDomainInfo != null;
4805            }
4806        }
4807        return false;
4808    }
4809
4810    private UserInfo getProfileParent(int userId) {
4811        final long identity = Binder.clearCallingIdentity();
4812        try {
4813            return sUserManager.getProfileParent(userId);
4814        } finally {
4815            Binder.restoreCallingIdentity(identity);
4816        }
4817    }
4818
4819    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4820            String resolvedType, int userId) {
4821        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4822        if (resolver != null) {
4823            return resolver.queryIntent(intent, resolvedType, false, userId);
4824        }
4825        return null;
4826    }
4827
4828    @Override
4829    public List<ResolveInfo> queryIntentActivities(Intent intent,
4830            String resolvedType, int flags, int userId) {
4831        if (!sUserManager.exists(userId)) return Collections.emptyList();
4832        flags = augmentFlagsForUser(flags, userId);
4833        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4834        ComponentName comp = intent.getComponent();
4835        if (comp == null) {
4836            if (intent.getSelector() != null) {
4837                intent = intent.getSelector();
4838                comp = intent.getComponent();
4839            }
4840        }
4841
4842        if (comp != null) {
4843            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4844            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4845            if (ai != null) {
4846                final ResolveInfo ri = new ResolveInfo();
4847                ri.activityInfo = ai;
4848                list.add(ri);
4849            }
4850            return list;
4851        }
4852
4853        // reader
4854        synchronized (mPackages) {
4855            final String pkgName = intent.getPackage();
4856            if (pkgName == null) {
4857                List<CrossProfileIntentFilter> matchingFilters =
4858                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4859                // Check for results that need to skip the current profile.
4860                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4861                        resolvedType, flags, userId);
4862                if (xpResolveInfo != null) {
4863                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4864                    result.add(xpResolveInfo);
4865                    return filterIfNotSystemUser(result, userId);
4866                }
4867
4868                // Check for results in the current profile.
4869                List<ResolveInfo> result = mActivities.queryIntent(
4870                        intent, resolvedType, flags, userId);
4871
4872                // Check for cross profile results.
4873                xpResolveInfo = queryCrossProfileIntents(
4874                        matchingFilters, intent, resolvedType, flags, userId);
4875                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4876                    result.add(xpResolveInfo);
4877                    Collections.sort(result, mResolvePrioritySorter);
4878                }
4879                result = filterIfNotSystemUser(result, userId);
4880                if (hasWebURI(intent)) {
4881                    CrossProfileDomainInfo xpDomainInfo = null;
4882                    final UserInfo parent = getProfileParent(userId);
4883                    if (parent != null) {
4884                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4885                                flags, userId, parent.id);
4886                    }
4887                    if (xpDomainInfo != null) {
4888                        if (xpResolveInfo != null) {
4889                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4890                            // in the result.
4891                            result.remove(xpResolveInfo);
4892                        }
4893                        if (result.size() == 0) {
4894                            result.add(xpDomainInfo.resolveInfo);
4895                            return result;
4896                        }
4897                    } else if (result.size() <= 1) {
4898                        return result;
4899                    }
4900                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4901                            xpDomainInfo, userId);
4902                    Collections.sort(result, mResolvePrioritySorter);
4903                }
4904                return result;
4905            }
4906            final PackageParser.Package pkg = mPackages.get(pkgName);
4907            if (pkg != null) {
4908                return filterIfNotSystemUser(
4909                        mActivities.queryIntentForPackage(
4910                                intent, resolvedType, flags, pkg.activities, userId),
4911                        userId);
4912            }
4913            return new ArrayList<ResolveInfo>();
4914        }
4915    }
4916
4917    private static class CrossProfileDomainInfo {
4918        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4919        ResolveInfo resolveInfo;
4920        /* Best domain verification status of the activities found in the other profile */
4921        int bestDomainVerificationStatus;
4922    }
4923
4924    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4925            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4926        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4927                sourceUserId)) {
4928            return null;
4929        }
4930        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4931                resolvedType, flags, parentUserId);
4932
4933        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4934            return null;
4935        }
4936        CrossProfileDomainInfo result = null;
4937        int size = resultTargetUser.size();
4938        for (int i = 0; i < size; i++) {
4939            ResolveInfo riTargetUser = resultTargetUser.get(i);
4940            // Intent filter verification is only for filters that specify a host. So don't return
4941            // those that handle all web uris.
4942            if (riTargetUser.handleAllWebDataURI) {
4943                continue;
4944            }
4945            String packageName = riTargetUser.activityInfo.packageName;
4946            PackageSetting ps = mSettings.mPackages.get(packageName);
4947            if (ps == null) {
4948                continue;
4949            }
4950            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4951            int status = (int)(verificationState >> 32);
4952            if (result == null) {
4953                result = new CrossProfileDomainInfo();
4954                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4955                        sourceUserId, parentUserId);
4956                result.bestDomainVerificationStatus = status;
4957            } else {
4958                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4959                        result.bestDomainVerificationStatus);
4960            }
4961        }
4962        // Don't consider matches with status NEVER across profiles.
4963        if (result != null && result.bestDomainVerificationStatus
4964                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4965            return null;
4966        }
4967        return result;
4968    }
4969
4970    /**
4971     * Verification statuses are ordered from the worse to the best, except for
4972     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4973     */
4974    private int bestDomainVerificationStatus(int status1, int status2) {
4975        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4976            return status2;
4977        }
4978        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4979            return status1;
4980        }
4981        return (int) MathUtils.max(status1, status2);
4982    }
4983
4984    private boolean isUserEnabled(int userId) {
4985        long callingId = Binder.clearCallingIdentity();
4986        try {
4987            UserInfo userInfo = sUserManager.getUserInfo(userId);
4988            return userInfo != null && userInfo.isEnabled();
4989        } finally {
4990            Binder.restoreCallingIdentity(callingId);
4991        }
4992    }
4993
4994    /**
4995     * Filter out activities with systemUserOnly flag set, when current user is not System.
4996     *
4997     * @return filtered list
4998     */
4999    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5000        if (userId == UserHandle.USER_SYSTEM) {
5001            return resolveInfos;
5002        }
5003        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5004            ResolveInfo info = resolveInfos.get(i);
5005            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5006                resolveInfos.remove(i);
5007            }
5008        }
5009        return resolveInfos;
5010    }
5011
5012    private static boolean hasWebURI(Intent intent) {
5013        if (intent.getData() == null) {
5014            return false;
5015        }
5016        final String scheme = intent.getScheme();
5017        if (TextUtils.isEmpty(scheme)) {
5018            return false;
5019        }
5020        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5021    }
5022
5023    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5024            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5025            int userId) {
5026        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5027
5028        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5029            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5030                    candidates.size());
5031        }
5032
5033        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5034        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5035        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5036        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5037        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5038        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5039
5040        synchronized (mPackages) {
5041            final int count = candidates.size();
5042            // First, try to use linked apps. Partition the candidates into four lists:
5043            // one for the final results, one for the "do not use ever", one for "undefined status"
5044            // and finally one for "browser app type".
5045            for (int n=0; n<count; n++) {
5046                ResolveInfo info = candidates.get(n);
5047                String packageName = info.activityInfo.packageName;
5048                PackageSetting ps = mSettings.mPackages.get(packageName);
5049                if (ps != null) {
5050                    // Add to the special match all list (Browser use case)
5051                    if (info.handleAllWebDataURI) {
5052                        matchAllList.add(info);
5053                        continue;
5054                    }
5055                    // Try to get the status from User settings first
5056                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5057                    int status = (int)(packedStatus >> 32);
5058                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5059                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5060                        if (DEBUG_DOMAIN_VERIFICATION) {
5061                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5062                                    + " : linkgen=" + linkGeneration);
5063                        }
5064                        // Use link-enabled generation as preferredOrder, i.e.
5065                        // prefer newly-enabled over earlier-enabled.
5066                        info.preferredOrder = linkGeneration;
5067                        alwaysList.add(info);
5068                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5069                        if (DEBUG_DOMAIN_VERIFICATION) {
5070                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5071                        }
5072                        neverList.add(info);
5073                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5074                        if (DEBUG_DOMAIN_VERIFICATION) {
5075                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5076                        }
5077                        alwaysAskList.add(info);
5078                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5079                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5080                        if (DEBUG_DOMAIN_VERIFICATION) {
5081                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5082                        }
5083                        undefinedList.add(info);
5084                    }
5085                }
5086            }
5087
5088            // We'll want to include browser possibilities in a few cases
5089            boolean includeBrowser = false;
5090
5091            // First try to add the "always" resolution(s) for the current user, if any
5092            if (alwaysList.size() > 0) {
5093                result.addAll(alwaysList);
5094            } else {
5095                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5096                result.addAll(undefinedList);
5097                // Maybe add one for the other profile.
5098                if (xpDomainInfo != null && (
5099                        xpDomainInfo.bestDomainVerificationStatus
5100                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5101                    result.add(xpDomainInfo.resolveInfo);
5102                }
5103                includeBrowser = true;
5104            }
5105
5106            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5107            // If there were 'always' entries their preferred order has been set, so we also
5108            // back that off to make the alternatives equivalent
5109            if (alwaysAskList.size() > 0) {
5110                for (ResolveInfo i : result) {
5111                    i.preferredOrder = 0;
5112                }
5113                result.addAll(alwaysAskList);
5114                includeBrowser = true;
5115            }
5116
5117            if (includeBrowser) {
5118                // Also add browsers (all of them or only the default one)
5119                if (DEBUG_DOMAIN_VERIFICATION) {
5120                    Slog.v(TAG, "   ...including browsers in candidate set");
5121                }
5122                if ((matchFlags & MATCH_ALL) != 0) {
5123                    result.addAll(matchAllList);
5124                } else {
5125                    // Browser/generic handling case.  If there's a default browser, go straight
5126                    // to that (but only if there is no other higher-priority match).
5127                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5128                    int maxMatchPrio = 0;
5129                    ResolveInfo defaultBrowserMatch = null;
5130                    final int numCandidates = matchAllList.size();
5131                    for (int n = 0; n < numCandidates; n++) {
5132                        ResolveInfo info = matchAllList.get(n);
5133                        // track the highest overall match priority...
5134                        if (info.priority > maxMatchPrio) {
5135                            maxMatchPrio = info.priority;
5136                        }
5137                        // ...and the highest-priority default browser match
5138                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5139                            if (defaultBrowserMatch == null
5140                                    || (defaultBrowserMatch.priority < info.priority)) {
5141                                if (debug) {
5142                                    Slog.v(TAG, "Considering default browser match " + info);
5143                                }
5144                                defaultBrowserMatch = info;
5145                            }
5146                        }
5147                    }
5148                    if (defaultBrowserMatch != null
5149                            && defaultBrowserMatch.priority >= maxMatchPrio
5150                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5151                    {
5152                        if (debug) {
5153                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5154                        }
5155                        result.add(defaultBrowserMatch);
5156                    } else {
5157                        result.addAll(matchAllList);
5158                    }
5159                }
5160
5161                // If there is nothing selected, add all candidates and remove the ones that the user
5162                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5163                if (result.size() == 0) {
5164                    result.addAll(candidates);
5165                    result.removeAll(neverList);
5166                }
5167            }
5168        }
5169        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5170            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5171                    result.size());
5172            for (ResolveInfo info : result) {
5173                Slog.v(TAG, "  + " + info.activityInfo);
5174            }
5175        }
5176        return result;
5177    }
5178
5179    // Returns a packed value as a long:
5180    //
5181    // high 'int'-sized word: link status: undefined/ask/never/always.
5182    // low 'int'-sized word: relative priority among 'always' results.
5183    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5184        long result = ps.getDomainVerificationStatusForUser(userId);
5185        // if none available, get the master status
5186        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5187            if (ps.getIntentFilterVerificationInfo() != null) {
5188                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5189            }
5190        }
5191        return result;
5192    }
5193
5194    private ResolveInfo querySkipCurrentProfileIntents(
5195            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5196            int flags, int sourceUserId) {
5197        if (matchingFilters != null) {
5198            int size = matchingFilters.size();
5199            for (int i = 0; i < size; i ++) {
5200                CrossProfileIntentFilter filter = matchingFilters.get(i);
5201                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5202                    // Checking if there are activities in the target user that can handle the
5203                    // intent.
5204                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5205                            resolvedType, flags, sourceUserId);
5206                    if (resolveInfo != null) {
5207                        return resolveInfo;
5208                    }
5209                }
5210            }
5211        }
5212        return null;
5213    }
5214
5215    // Return matching ResolveInfo if any for skip current profile intent filters.
5216    private ResolveInfo queryCrossProfileIntents(
5217            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5218            int flags, int sourceUserId) {
5219        if (matchingFilters != null) {
5220            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5221            // match the same intent. For performance reasons, it is better not to
5222            // run queryIntent twice for the same userId
5223            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5224            int size = matchingFilters.size();
5225            for (int i = 0; i < size; i++) {
5226                CrossProfileIntentFilter filter = matchingFilters.get(i);
5227                int targetUserId = filter.getTargetUserId();
5228                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
5229                        && !alreadyTriedUserIds.get(targetUserId)) {
5230                    // Checking if there are activities in the target user that can handle the
5231                    // intent.
5232                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5233                            resolvedType, flags, sourceUserId);
5234                    if (resolveInfo != null) return resolveInfo;
5235                    alreadyTriedUserIds.put(targetUserId, true);
5236                }
5237            }
5238        }
5239        return null;
5240    }
5241
5242    /**
5243     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5244     * will forward the intent to the filter's target user.
5245     * Otherwise, returns null.
5246     */
5247    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5248            String resolvedType, int flags, int sourceUserId) {
5249        int targetUserId = filter.getTargetUserId();
5250        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5251                resolvedType, flags, targetUserId);
5252        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5253                && isUserEnabled(targetUserId)) {
5254            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5255        }
5256        return null;
5257    }
5258
5259    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5260            int sourceUserId, int targetUserId) {
5261        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5262        long ident = Binder.clearCallingIdentity();
5263        boolean targetIsProfile;
5264        try {
5265            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5266        } finally {
5267            Binder.restoreCallingIdentity(ident);
5268        }
5269        String className;
5270        if (targetIsProfile) {
5271            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5272        } else {
5273            className = FORWARD_INTENT_TO_PARENT;
5274        }
5275        ComponentName forwardingActivityComponentName = new ComponentName(
5276                mAndroidApplication.packageName, className);
5277        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5278                sourceUserId);
5279        if (!targetIsProfile) {
5280            forwardingActivityInfo.showUserIcon = targetUserId;
5281            forwardingResolveInfo.noResourceId = true;
5282        }
5283        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5284        forwardingResolveInfo.priority = 0;
5285        forwardingResolveInfo.preferredOrder = 0;
5286        forwardingResolveInfo.match = 0;
5287        forwardingResolveInfo.isDefault = true;
5288        forwardingResolveInfo.filter = filter;
5289        forwardingResolveInfo.targetUserId = targetUserId;
5290        return forwardingResolveInfo;
5291    }
5292
5293    @Override
5294    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5295            Intent[] specifics, String[] specificTypes, Intent intent,
5296            String resolvedType, int flags, int userId) {
5297        if (!sUserManager.exists(userId)) return Collections.emptyList();
5298        flags = augmentFlagsForUser(flags, userId);
5299        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5300                false, "query intent activity options");
5301        final String resultsAction = intent.getAction();
5302
5303        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5304                | PackageManager.GET_RESOLVED_FILTER, userId);
5305
5306        if (DEBUG_INTENT_MATCHING) {
5307            Log.v(TAG, "Query " + intent + ": " + results);
5308        }
5309
5310        int specificsPos = 0;
5311        int N;
5312
5313        // todo: note that the algorithm used here is O(N^2).  This
5314        // isn't a problem in our current environment, but if we start running
5315        // into situations where we have more than 5 or 10 matches then this
5316        // should probably be changed to something smarter...
5317
5318        // First we go through and resolve each of the specific items
5319        // that were supplied, taking care of removing any corresponding
5320        // duplicate items in the generic resolve list.
5321        if (specifics != null) {
5322            for (int i=0; i<specifics.length; i++) {
5323                final Intent sintent = specifics[i];
5324                if (sintent == null) {
5325                    continue;
5326                }
5327
5328                if (DEBUG_INTENT_MATCHING) {
5329                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5330                }
5331
5332                String action = sintent.getAction();
5333                if (resultsAction != null && resultsAction.equals(action)) {
5334                    // If this action was explicitly requested, then don't
5335                    // remove things that have it.
5336                    action = null;
5337                }
5338
5339                ResolveInfo ri = null;
5340                ActivityInfo ai = null;
5341
5342                ComponentName comp = sintent.getComponent();
5343                if (comp == null) {
5344                    ri = resolveIntent(
5345                        sintent,
5346                        specificTypes != null ? specificTypes[i] : null,
5347                            flags, userId);
5348                    if (ri == null) {
5349                        continue;
5350                    }
5351                    if (ri == mResolveInfo) {
5352                        // ACK!  Must do something better with this.
5353                    }
5354                    ai = ri.activityInfo;
5355                    comp = new ComponentName(ai.applicationInfo.packageName,
5356                            ai.name);
5357                } else {
5358                    ai = getActivityInfo(comp, flags, userId);
5359                    if (ai == null) {
5360                        continue;
5361                    }
5362                }
5363
5364                // Look for any generic query activities that are duplicates
5365                // of this specific one, and remove them from the results.
5366                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5367                N = results.size();
5368                int j;
5369                for (j=specificsPos; j<N; j++) {
5370                    ResolveInfo sri = results.get(j);
5371                    if ((sri.activityInfo.name.equals(comp.getClassName())
5372                            && sri.activityInfo.applicationInfo.packageName.equals(
5373                                    comp.getPackageName()))
5374                        || (action != null && sri.filter.matchAction(action))) {
5375                        results.remove(j);
5376                        if (DEBUG_INTENT_MATCHING) Log.v(
5377                            TAG, "Removing duplicate item from " + j
5378                            + " due to specific " + specificsPos);
5379                        if (ri == null) {
5380                            ri = sri;
5381                        }
5382                        j--;
5383                        N--;
5384                    }
5385                }
5386
5387                // Add this specific item to its proper place.
5388                if (ri == null) {
5389                    ri = new ResolveInfo();
5390                    ri.activityInfo = ai;
5391                }
5392                results.add(specificsPos, ri);
5393                ri.specificIndex = i;
5394                specificsPos++;
5395            }
5396        }
5397
5398        // Now we go through the remaining generic results and remove any
5399        // duplicate actions that are found here.
5400        N = results.size();
5401        for (int i=specificsPos; i<N-1; i++) {
5402            final ResolveInfo rii = results.get(i);
5403            if (rii.filter == null) {
5404                continue;
5405            }
5406
5407            // Iterate over all of the actions of this result's intent
5408            // filter...  typically this should be just one.
5409            final Iterator<String> it = rii.filter.actionsIterator();
5410            if (it == null) {
5411                continue;
5412            }
5413            while (it.hasNext()) {
5414                final String action = it.next();
5415                if (resultsAction != null && resultsAction.equals(action)) {
5416                    // If this action was explicitly requested, then don't
5417                    // remove things that have it.
5418                    continue;
5419                }
5420                for (int j=i+1; j<N; j++) {
5421                    final ResolveInfo rij = results.get(j);
5422                    if (rij.filter != null && rij.filter.hasAction(action)) {
5423                        results.remove(j);
5424                        if (DEBUG_INTENT_MATCHING) Log.v(
5425                            TAG, "Removing duplicate item from " + j
5426                            + " due to action " + action + " at " + i);
5427                        j--;
5428                        N--;
5429                    }
5430                }
5431            }
5432
5433            // If the caller didn't request filter information, drop it now
5434            // so we don't have to marshall/unmarshall it.
5435            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5436                rii.filter = null;
5437            }
5438        }
5439
5440        // Filter out the caller activity if so requested.
5441        if (caller != null) {
5442            N = results.size();
5443            for (int i=0; i<N; i++) {
5444                ActivityInfo ainfo = results.get(i).activityInfo;
5445                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5446                        && caller.getClassName().equals(ainfo.name)) {
5447                    results.remove(i);
5448                    break;
5449                }
5450            }
5451        }
5452
5453        // If the caller didn't request filter information,
5454        // drop them now so we don't have to
5455        // marshall/unmarshall it.
5456        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5457            N = results.size();
5458            for (int i=0; i<N; i++) {
5459                results.get(i).filter = null;
5460            }
5461        }
5462
5463        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5464        return results;
5465    }
5466
5467    @Override
5468    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5469            int userId) {
5470        if (!sUserManager.exists(userId)) return Collections.emptyList();
5471        flags = augmentFlagsForUser(flags, userId);
5472        ComponentName comp = intent.getComponent();
5473        if (comp == null) {
5474            if (intent.getSelector() != null) {
5475                intent = intent.getSelector();
5476                comp = intent.getComponent();
5477            }
5478        }
5479        if (comp != null) {
5480            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5481            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5482            if (ai != null) {
5483                ResolveInfo ri = new ResolveInfo();
5484                ri.activityInfo = ai;
5485                list.add(ri);
5486            }
5487            return list;
5488        }
5489
5490        // reader
5491        synchronized (mPackages) {
5492            String pkgName = intent.getPackage();
5493            if (pkgName == null) {
5494                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5495            }
5496            final PackageParser.Package pkg = mPackages.get(pkgName);
5497            if (pkg != null) {
5498                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5499                        userId);
5500            }
5501            return null;
5502        }
5503    }
5504
5505    @Override
5506    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5507        if (!sUserManager.exists(userId)) return null;
5508        flags = augmentFlagsForUser(flags, userId);
5509        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5510        if (query != null) {
5511            if (query.size() >= 1) {
5512                // If there is more than one service with the same priority,
5513                // just arbitrarily pick the first one.
5514                return query.get(0);
5515            }
5516        }
5517        return null;
5518    }
5519
5520    @Override
5521    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5522            int userId) {
5523        if (!sUserManager.exists(userId)) return Collections.emptyList();
5524        flags = augmentFlagsForUser(flags, userId);
5525        ComponentName comp = intent.getComponent();
5526        if (comp == null) {
5527            if (intent.getSelector() != null) {
5528                intent = intent.getSelector();
5529                comp = intent.getComponent();
5530            }
5531        }
5532        if (comp != null) {
5533            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5534            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5535            if (si != null) {
5536                final ResolveInfo ri = new ResolveInfo();
5537                ri.serviceInfo = si;
5538                list.add(ri);
5539            }
5540            return list;
5541        }
5542
5543        // reader
5544        synchronized (mPackages) {
5545            String pkgName = intent.getPackage();
5546            if (pkgName == null) {
5547                return mServices.queryIntent(intent, resolvedType, flags, userId);
5548            }
5549            final PackageParser.Package pkg = mPackages.get(pkgName);
5550            if (pkg != null) {
5551                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5552                        userId);
5553            }
5554            return null;
5555        }
5556    }
5557
5558    @Override
5559    public List<ResolveInfo> queryIntentContentProviders(
5560            Intent intent, String resolvedType, int flags, int userId) {
5561        if (!sUserManager.exists(userId)) return Collections.emptyList();
5562        flags = augmentFlagsForUser(flags, userId);
5563        ComponentName comp = intent.getComponent();
5564        if (comp == null) {
5565            if (intent.getSelector() != null) {
5566                intent = intent.getSelector();
5567                comp = intent.getComponent();
5568            }
5569        }
5570        if (comp != null) {
5571            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5572            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5573            if (pi != null) {
5574                final ResolveInfo ri = new ResolveInfo();
5575                ri.providerInfo = pi;
5576                list.add(ri);
5577            }
5578            return list;
5579        }
5580
5581        // reader
5582        synchronized (mPackages) {
5583            String pkgName = intent.getPackage();
5584            if (pkgName == null) {
5585                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5586            }
5587            final PackageParser.Package pkg = mPackages.get(pkgName);
5588            if (pkg != null) {
5589                return mProviders.queryIntentForPackage(
5590                        intent, resolvedType, flags, pkg.providers, userId);
5591            }
5592            return null;
5593        }
5594    }
5595
5596    @Override
5597    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5598        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5599
5600        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5601
5602        // writer
5603        synchronized (mPackages) {
5604            ArrayList<PackageInfo> list;
5605            if (listUninstalled) {
5606                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5607                for (PackageSetting ps : mSettings.mPackages.values()) {
5608                    PackageInfo pi;
5609                    if (ps.pkg != null) {
5610                        pi = generatePackageInfo(ps.pkg, flags, userId);
5611                    } else {
5612                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5613                    }
5614                    if (pi != null) {
5615                        list.add(pi);
5616                    }
5617                }
5618            } else {
5619                list = new ArrayList<PackageInfo>(mPackages.size());
5620                for (PackageParser.Package p : mPackages.values()) {
5621                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5622                    if (pi != null) {
5623                        list.add(pi);
5624                    }
5625                }
5626            }
5627
5628            return new ParceledListSlice<PackageInfo>(list);
5629        }
5630    }
5631
5632    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5633            String[] permissions, boolean[] tmp, int flags, int userId) {
5634        int numMatch = 0;
5635        final PermissionsState permissionsState = ps.getPermissionsState();
5636        for (int i=0; i<permissions.length; i++) {
5637            final String permission = permissions[i];
5638            if (permissionsState.hasPermission(permission, userId)) {
5639                tmp[i] = true;
5640                numMatch++;
5641            } else {
5642                tmp[i] = false;
5643            }
5644        }
5645        if (numMatch == 0) {
5646            return;
5647        }
5648        PackageInfo pi;
5649        if (ps.pkg != null) {
5650            pi = generatePackageInfo(ps.pkg, flags, userId);
5651        } else {
5652            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5653        }
5654        // The above might return null in cases of uninstalled apps or install-state
5655        // skew across users/profiles.
5656        if (pi != null) {
5657            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5658                if (numMatch == permissions.length) {
5659                    pi.requestedPermissions = permissions;
5660                } else {
5661                    pi.requestedPermissions = new String[numMatch];
5662                    numMatch = 0;
5663                    for (int i=0; i<permissions.length; i++) {
5664                        if (tmp[i]) {
5665                            pi.requestedPermissions[numMatch] = permissions[i];
5666                            numMatch++;
5667                        }
5668                    }
5669                }
5670            }
5671            list.add(pi);
5672        }
5673    }
5674
5675    @Override
5676    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5677            String[] permissions, int flags, int userId) {
5678        if (!sUserManager.exists(userId)) return null;
5679        flags = augmentFlagsForUser(flags, userId);
5680        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5681
5682        // writer
5683        synchronized (mPackages) {
5684            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5685            boolean[] tmpBools = new boolean[permissions.length];
5686            if (listUninstalled) {
5687                for (PackageSetting ps : mSettings.mPackages.values()) {
5688                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5689                }
5690            } else {
5691                for (PackageParser.Package pkg : mPackages.values()) {
5692                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5693                    if (ps != null) {
5694                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5695                                userId);
5696                    }
5697                }
5698            }
5699
5700            return new ParceledListSlice<PackageInfo>(list);
5701        }
5702    }
5703
5704    @Override
5705    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5706        if (!sUserManager.exists(userId)) return null;
5707        flags = augmentFlagsForUser(flags, userId);
5708        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5709
5710        // writer
5711        synchronized (mPackages) {
5712            ArrayList<ApplicationInfo> list;
5713            if (listUninstalled) {
5714                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5715                for (PackageSetting ps : mSettings.mPackages.values()) {
5716                    ApplicationInfo ai;
5717                    if (ps.pkg != null) {
5718                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5719                                ps.readUserState(userId), userId);
5720                    } else {
5721                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5722                    }
5723                    if (ai != null) {
5724                        list.add(ai);
5725                    }
5726                }
5727            } else {
5728                list = new ArrayList<ApplicationInfo>(mPackages.size());
5729                for (PackageParser.Package p : mPackages.values()) {
5730                    if (p.mExtras != null) {
5731                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5732                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5733                        if (ai != null) {
5734                            list.add(ai);
5735                        }
5736                    }
5737                }
5738            }
5739
5740            return new ParceledListSlice<ApplicationInfo>(list);
5741        }
5742    }
5743
5744    public List<ApplicationInfo> getPersistentApplications(int flags) {
5745        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5746
5747        // reader
5748        synchronized (mPackages) {
5749            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5750            final int userId = UserHandle.getCallingUserId();
5751            while (i.hasNext()) {
5752                final PackageParser.Package p = i.next();
5753                if (p.applicationInfo != null
5754                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5755                        && (!mSafeMode || isSystemApp(p))) {
5756                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5757                    if (ps != null) {
5758                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5759                                ps.readUserState(userId), userId);
5760                        if (ai != null) {
5761                            finalList.add(ai);
5762                        }
5763                    }
5764                }
5765            }
5766        }
5767
5768        return finalList;
5769    }
5770
5771    @Override
5772    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5773        if (!sUserManager.exists(userId)) return null;
5774        flags = augmentFlagsForUser(flags, userId);
5775        // reader
5776        synchronized (mPackages) {
5777            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5778            PackageSetting ps = provider != null
5779                    ? mSettings.mPackages.get(provider.owner.packageName)
5780                    : null;
5781            return ps != null
5782                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5783                    && (!mSafeMode || (provider.info.applicationInfo.flags
5784                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5785                    ? PackageParser.generateProviderInfo(provider, flags,
5786                            ps.readUserState(userId), userId)
5787                    : null;
5788        }
5789    }
5790
5791    /**
5792     * @deprecated
5793     */
5794    @Deprecated
5795    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5796        // reader
5797        synchronized (mPackages) {
5798            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5799                    .entrySet().iterator();
5800            final int userId = UserHandle.getCallingUserId();
5801            while (i.hasNext()) {
5802                Map.Entry<String, PackageParser.Provider> entry = i.next();
5803                PackageParser.Provider p = entry.getValue();
5804                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5805
5806                if (ps != null && p.syncable
5807                        && (!mSafeMode || (p.info.applicationInfo.flags
5808                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5809                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5810                            ps.readUserState(userId), userId);
5811                    if (info != null) {
5812                        outNames.add(entry.getKey());
5813                        outInfo.add(info);
5814                    }
5815                }
5816            }
5817        }
5818    }
5819
5820    @Override
5821    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5822            int uid, int flags) {
5823        final int userId = processName != null ? UserHandle.getUserId(uid)
5824                : UserHandle.getCallingUserId();
5825        if (!sUserManager.exists(userId)) return null;
5826        flags = augmentFlagsForUser(flags, userId);
5827
5828        ArrayList<ProviderInfo> finalList = null;
5829        // reader
5830        synchronized (mPackages) {
5831            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5832            while (i.hasNext()) {
5833                final PackageParser.Provider p = i.next();
5834                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5835                if (ps != null && p.info.authority != null
5836                        && (processName == null
5837                                || (p.info.processName.equals(processName)
5838                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5839                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5840                        && (!mSafeMode
5841                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5842                    if (finalList == null) {
5843                        finalList = new ArrayList<ProviderInfo>(3);
5844                    }
5845                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5846                            ps.readUserState(userId), userId);
5847                    if (info != null) {
5848                        finalList.add(info);
5849                    }
5850                }
5851            }
5852        }
5853
5854        if (finalList != null) {
5855            Collections.sort(finalList, mProviderInitOrderSorter);
5856            return new ParceledListSlice<ProviderInfo>(finalList);
5857        }
5858
5859        return null;
5860    }
5861
5862    @Override
5863    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5864            int flags) {
5865        // reader
5866        synchronized (mPackages) {
5867            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5868            return PackageParser.generateInstrumentationInfo(i, flags);
5869        }
5870    }
5871
5872    @Override
5873    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5874            int flags) {
5875        ArrayList<InstrumentationInfo> finalList =
5876            new ArrayList<InstrumentationInfo>();
5877
5878        // reader
5879        synchronized (mPackages) {
5880            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5881            while (i.hasNext()) {
5882                final PackageParser.Instrumentation p = i.next();
5883                if (targetPackage == null
5884                        || targetPackage.equals(p.info.targetPackage)) {
5885                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5886                            flags);
5887                    if (ii != null) {
5888                        finalList.add(ii);
5889                    }
5890                }
5891            }
5892        }
5893
5894        return finalList;
5895    }
5896
5897    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5898        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5899        if (overlays == null) {
5900            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5901            return;
5902        }
5903        for (PackageParser.Package opkg : overlays.values()) {
5904            // Not much to do if idmap fails: we already logged the error
5905            // and we certainly don't want to abort installation of pkg simply
5906            // because an overlay didn't fit properly. For these reasons,
5907            // ignore the return value of createIdmapForPackagePairLI.
5908            createIdmapForPackagePairLI(pkg, opkg);
5909        }
5910    }
5911
5912    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5913            PackageParser.Package opkg) {
5914        if (!opkg.mTrustedOverlay) {
5915            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5916                    opkg.baseCodePath + ": overlay not trusted");
5917            return false;
5918        }
5919        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5920        if (overlaySet == null) {
5921            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5922                    opkg.baseCodePath + " but target package has no known overlays");
5923            return false;
5924        }
5925        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5926        // TODO: generate idmap for split APKs
5927        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5928            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5929                    + opkg.baseCodePath);
5930            return false;
5931        }
5932        PackageParser.Package[] overlayArray =
5933            overlaySet.values().toArray(new PackageParser.Package[0]);
5934        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5935            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5936                return p1.mOverlayPriority - p2.mOverlayPriority;
5937            }
5938        };
5939        Arrays.sort(overlayArray, cmp);
5940
5941        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5942        int i = 0;
5943        for (PackageParser.Package p : overlayArray) {
5944            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5945        }
5946        return true;
5947    }
5948
5949    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5950        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5951        try {
5952            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5953        } finally {
5954            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5955        }
5956    }
5957
5958    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5959        final File[] files = dir.listFiles();
5960        if (ArrayUtils.isEmpty(files)) {
5961            Log.d(TAG, "No files in app dir " + dir);
5962            return;
5963        }
5964
5965        if (DEBUG_PACKAGE_SCANNING) {
5966            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5967                    + " flags=0x" + Integer.toHexString(parseFlags));
5968        }
5969
5970        for (File file : files) {
5971            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5972                    && !PackageInstallerService.isStageName(file.getName());
5973            if (!isPackage) {
5974                // Ignore entries which are not packages
5975                continue;
5976            }
5977            try {
5978                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5979                        scanFlags, currentTime, null);
5980            } catch (PackageManagerException e) {
5981                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5982
5983                // Delete invalid userdata apps
5984                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5985                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5986                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5987                    if (file.isDirectory()) {
5988                        mInstaller.rmPackageDir(file.getAbsolutePath());
5989                    } else {
5990                        file.delete();
5991                    }
5992                }
5993            }
5994        }
5995    }
5996
5997    private static File getSettingsProblemFile() {
5998        File dataDir = Environment.getDataDirectory();
5999        File systemDir = new File(dataDir, "system");
6000        File fname = new File(systemDir, "uiderrors.txt");
6001        return fname;
6002    }
6003
6004    static void reportSettingsProblem(int priority, String msg) {
6005        logCriticalInfo(priority, msg);
6006    }
6007
6008    static void logCriticalInfo(int priority, String msg) {
6009        Slog.println(priority, TAG, msg);
6010        EventLogTags.writePmCriticalInfo(msg);
6011        try {
6012            File fname = getSettingsProblemFile();
6013            FileOutputStream out = new FileOutputStream(fname, true);
6014            PrintWriter pw = new FastPrintWriter(out);
6015            SimpleDateFormat formatter = new SimpleDateFormat();
6016            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6017            pw.println(dateString + ": " + msg);
6018            pw.close();
6019            FileUtils.setPermissions(
6020                    fname.toString(),
6021                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6022                    -1, -1);
6023        } catch (java.io.IOException e) {
6024        }
6025    }
6026
6027    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6028            PackageParser.Package pkg, File srcFile, int parseFlags)
6029            throws PackageManagerException {
6030        if (ps != null
6031                && ps.codePath.equals(srcFile)
6032                && ps.timeStamp == srcFile.lastModified()
6033                && !isCompatSignatureUpdateNeeded(pkg)
6034                && !isRecoverSignatureUpdateNeeded(pkg)) {
6035            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6036            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6037            ArraySet<PublicKey> signingKs;
6038            synchronized (mPackages) {
6039                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6040            }
6041            if (ps.signatures.mSignatures != null
6042                    && ps.signatures.mSignatures.length != 0
6043                    && signingKs != null) {
6044                // Optimization: reuse the existing cached certificates
6045                // if the package appears to be unchanged.
6046                pkg.mSignatures = ps.signatures.mSignatures;
6047                pkg.mSigningKeys = signingKs;
6048                return;
6049            }
6050
6051            Slog.w(TAG, "PackageSetting for " + ps.name
6052                    + " is missing signatures.  Collecting certs again to recover them.");
6053        } else {
6054            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6055        }
6056
6057        try {
6058            pp.collectCertificates(pkg, parseFlags);
6059            pp.collectManifestDigest(pkg);
6060        } catch (PackageParserException e) {
6061            throw PackageManagerException.from(e);
6062        }
6063    }
6064
6065    /**
6066     *  Traces a package scan.
6067     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6068     */
6069    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6070            long currentTime, UserHandle user) throws PackageManagerException {
6071        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6072        try {
6073            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6074        } finally {
6075            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6076        }
6077    }
6078
6079    /**
6080     *  Scans a package and returns the newly parsed package.
6081     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6082     */
6083    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6084            long currentTime, UserHandle user) throws PackageManagerException {
6085        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6086        parseFlags |= mDefParseFlags;
6087        PackageParser pp = new PackageParser();
6088        pp.setSeparateProcesses(mSeparateProcesses);
6089        pp.setOnlyCoreApps(mOnlyCore);
6090        pp.setDisplayMetrics(mMetrics);
6091
6092        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6093            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6094        }
6095
6096        final PackageParser.Package pkg;
6097        try {
6098            pkg = pp.parsePackage(scanFile, parseFlags);
6099        } catch (PackageParserException e) {
6100            throw PackageManagerException.from(e);
6101        }
6102
6103        PackageSetting ps = null;
6104        PackageSetting updatedPkg;
6105        // reader
6106        synchronized (mPackages) {
6107            // Look to see if we already know about this package.
6108            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6109            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6110                // This package has been renamed to its original name.  Let's
6111                // use that.
6112                ps = mSettings.peekPackageLPr(oldName);
6113            }
6114            // If there was no original package, see one for the real package name.
6115            if (ps == null) {
6116                ps = mSettings.peekPackageLPr(pkg.packageName);
6117            }
6118            // Check to see if this package could be hiding/updating a system
6119            // package.  Must look for it either under the original or real
6120            // package name depending on our state.
6121            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6122            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6123        }
6124        boolean updatedPkgBetter = false;
6125        // First check if this is a system package that may involve an update
6126        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6127            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6128            // it needs to drop FLAG_PRIVILEGED.
6129            if (locationIsPrivileged(scanFile)) {
6130                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6131            } else {
6132                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6133            }
6134
6135            if (ps != null && !ps.codePath.equals(scanFile)) {
6136                // The path has changed from what was last scanned...  check the
6137                // version of the new path against what we have stored to determine
6138                // what to do.
6139                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6140                if (pkg.mVersionCode <= ps.versionCode) {
6141                    // The system package has been updated and the code path does not match
6142                    // Ignore entry. Skip it.
6143                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6144                            + " ignored: updated version " + ps.versionCode
6145                            + " better than this " + pkg.mVersionCode);
6146                    if (!updatedPkg.codePath.equals(scanFile)) {
6147                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6148                                + ps.name + " changing from " + updatedPkg.codePathString
6149                                + " to " + scanFile);
6150                        updatedPkg.codePath = scanFile;
6151                        updatedPkg.codePathString = scanFile.toString();
6152                        updatedPkg.resourcePath = scanFile;
6153                        updatedPkg.resourcePathString = scanFile.toString();
6154                    }
6155                    updatedPkg.pkg = pkg;
6156                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6157                            "Package " + ps.name + " at " + scanFile
6158                                    + " ignored: updated version " + ps.versionCode
6159                                    + " better than this " + pkg.mVersionCode);
6160                } else {
6161                    // The current app on the system partition is better than
6162                    // what we have updated to on the data partition; switch
6163                    // back to the system partition version.
6164                    // At this point, its safely assumed that package installation for
6165                    // apps in system partition will go through. If not there won't be a working
6166                    // version of the app
6167                    // writer
6168                    synchronized (mPackages) {
6169                        // Just remove the loaded entries from package lists.
6170                        mPackages.remove(ps.name);
6171                    }
6172
6173                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6174                            + " reverting from " + ps.codePathString
6175                            + ": new version " + pkg.mVersionCode
6176                            + " better than installed " + ps.versionCode);
6177
6178                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6179                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6180                    synchronized (mInstallLock) {
6181                        args.cleanUpResourcesLI();
6182                    }
6183                    synchronized (mPackages) {
6184                        mSettings.enableSystemPackageLPw(ps.name);
6185                    }
6186                    updatedPkgBetter = true;
6187                }
6188            }
6189        }
6190
6191        if (updatedPkg != null) {
6192            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6193            // initially
6194            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6195
6196            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6197            // flag set initially
6198            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6199                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6200            }
6201        }
6202
6203        // Verify certificates against what was last scanned
6204        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6205
6206        /*
6207         * A new system app appeared, but we already had a non-system one of the
6208         * same name installed earlier.
6209         */
6210        boolean shouldHideSystemApp = false;
6211        if (updatedPkg == null && ps != null
6212                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6213            /*
6214             * Check to make sure the signatures match first. If they don't,
6215             * wipe the installed application and its data.
6216             */
6217            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6218                    != PackageManager.SIGNATURE_MATCH) {
6219                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6220                        + " signatures don't match existing userdata copy; removing");
6221                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6222                ps = null;
6223            } else {
6224                /*
6225                 * If the newly-added system app is an older version than the
6226                 * already installed version, hide it. It will be scanned later
6227                 * and re-added like an update.
6228                 */
6229                if (pkg.mVersionCode <= ps.versionCode) {
6230                    shouldHideSystemApp = true;
6231                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6232                            + " but new version " + pkg.mVersionCode + " better than installed "
6233                            + ps.versionCode + "; hiding system");
6234                } else {
6235                    /*
6236                     * The newly found system app is a newer version that the
6237                     * one previously installed. Simply remove the
6238                     * already-installed application and replace it with our own
6239                     * while keeping the application data.
6240                     */
6241                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6242                            + " reverting from " + ps.codePathString + ": new version "
6243                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6244                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6245                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6246                    synchronized (mInstallLock) {
6247                        args.cleanUpResourcesLI();
6248                    }
6249                }
6250            }
6251        }
6252
6253        // The apk is forward locked (not public) if its code and resources
6254        // are kept in different files. (except for app in either system or
6255        // vendor path).
6256        // TODO grab this value from PackageSettings
6257        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6258            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6259                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6260            }
6261        }
6262
6263        // TODO: extend to support forward-locked splits
6264        String resourcePath = null;
6265        String baseResourcePath = null;
6266        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6267            if (ps != null && ps.resourcePathString != null) {
6268                resourcePath = ps.resourcePathString;
6269                baseResourcePath = ps.resourcePathString;
6270            } else {
6271                // Should not happen at all. Just log an error.
6272                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6273            }
6274        } else {
6275            resourcePath = pkg.codePath;
6276            baseResourcePath = pkg.baseCodePath;
6277        }
6278
6279        // Set application objects path explicitly.
6280        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6281        pkg.applicationInfo.setCodePath(pkg.codePath);
6282        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6283        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6284        pkg.applicationInfo.setResourcePath(resourcePath);
6285        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6286        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6287
6288        // Note that we invoke the following method only if we are about to unpack an application
6289        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6290                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6291
6292        /*
6293         * If the system app should be overridden by a previously installed
6294         * data, hide the system app now and let the /data/app scan pick it up
6295         * again.
6296         */
6297        if (shouldHideSystemApp) {
6298            synchronized (mPackages) {
6299                mSettings.disableSystemPackageLPw(pkg.packageName);
6300            }
6301        }
6302
6303        return scannedPkg;
6304    }
6305
6306    private static String fixProcessName(String defProcessName,
6307            String processName, int uid) {
6308        if (processName == null) {
6309            return defProcessName;
6310        }
6311        return processName;
6312    }
6313
6314    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6315            throws PackageManagerException {
6316        if (pkgSetting.signatures.mSignatures != null) {
6317            // Already existing package. Make sure signatures match
6318            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6319                    == PackageManager.SIGNATURE_MATCH;
6320            if (!match) {
6321                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6322                        == PackageManager.SIGNATURE_MATCH;
6323            }
6324            if (!match) {
6325                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6326                        == PackageManager.SIGNATURE_MATCH;
6327            }
6328            if (!match) {
6329                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6330                        + pkg.packageName + " signatures do not match the "
6331                        + "previously installed version; ignoring!");
6332            }
6333        }
6334
6335        // Check for shared user signatures
6336        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6337            // Already existing package. Make sure signatures match
6338            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6339                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6340            if (!match) {
6341                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6342                        == PackageManager.SIGNATURE_MATCH;
6343            }
6344            if (!match) {
6345                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6346                        == PackageManager.SIGNATURE_MATCH;
6347            }
6348            if (!match) {
6349                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6350                        "Package " + pkg.packageName
6351                        + " has no signatures that match those in shared user "
6352                        + pkgSetting.sharedUser.name + "; ignoring!");
6353            }
6354        }
6355    }
6356
6357    /**
6358     * Enforces that only the system UID or root's UID can call a method exposed
6359     * via Binder.
6360     *
6361     * @param message used as message if SecurityException is thrown
6362     * @throws SecurityException if the caller is not system or root
6363     */
6364    private static final void enforceSystemOrRoot(String message) {
6365        final int uid = Binder.getCallingUid();
6366        if (uid != Process.SYSTEM_UID && uid != 0) {
6367            throw new SecurityException(message);
6368        }
6369    }
6370
6371    @Override
6372    public void performFstrimIfNeeded() {
6373        enforceSystemOrRoot("Only the system can request fstrim");
6374
6375        // Before everything else, see whether we need to fstrim.
6376        try {
6377            IMountService ms = PackageHelper.getMountService();
6378            if (ms != null) {
6379                final boolean isUpgrade = isUpgrade();
6380                boolean doTrim = isUpgrade;
6381                if (doTrim) {
6382                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6383                } else {
6384                    final long interval = android.provider.Settings.Global.getLong(
6385                            mContext.getContentResolver(),
6386                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6387                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6388                    if (interval > 0) {
6389                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6390                        if (timeSinceLast > interval) {
6391                            doTrim = true;
6392                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6393                                    + "; running immediately");
6394                        }
6395                    }
6396                }
6397                if (doTrim) {
6398                    if (!isFirstBoot()) {
6399                        try {
6400                            ActivityManagerNative.getDefault().showBootMessage(
6401                                    mContext.getResources().getString(
6402                                            R.string.android_upgrading_fstrim), true);
6403                        } catch (RemoteException e) {
6404                        }
6405                    }
6406                    ms.runMaintenance();
6407                }
6408            } else {
6409                Slog.e(TAG, "Mount service unavailable!");
6410            }
6411        } catch (RemoteException e) {
6412            // Can't happen; MountService is local
6413        }
6414    }
6415
6416    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6417        List<ResolveInfo> ris = null;
6418        try {
6419            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6420                    intent, null, 0, userId);
6421        } catch (RemoteException e) {
6422        }
6423        ArraySet<String> pkgNames = new ArraySet<String>();
6424        if (ris != null) {
6425            for (ResolveInfo ri : ris) {
6426                pkgNames.add(ri.activityInfo.packageName);
6427            }
6428        }
6429        return pkgNames;
6430    }
6431
6432    @Override
6433    public void notifyPackageUse(String packageName) {
6434        synchronized (mPackages) {
6435            PackageParser.Package p = mPackages.get(packageName);
6436            if (p == null) {
6437                return;
6438            }
6439            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6440        }
6441    }
6442
6443    @Override
6444    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6445        return performDexOptTraced(packageName, instructionSet);
6446    }
6447
6448    public boolean performDexOpt(String packageName, String instructionSet) {
6449        return performDexOptTraced(packageName, instructionSet);
6450    }
6451
6452    private boolean performDexOptTraced(String packageName, String instructionSet) {
6453        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6454        try {
6455            return performDexOptInternal(packageName, instructionSet);
6456        } finally {
6457            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6458        }
6459    }
6460
6461    private boolean performDexOptInternal(String packageName, String instructionSet) {
6462        PackageParser.Package p;
6463        final String targetInstructionSet;
6464        synchronized (mPackages) {
6465            p = mPackages.get(packageName);
6466            if (p == null) {
6467                return false;
6468            }
6469            mPackageUsage.write(false);
6470
6471            targetInstructionSet = instructionSet != null ? instructionSet :
6472                    getPrimaryInstructionSet(p.applicationInfo);
6473            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6474                return false;
6475            }
6476        }
6477        long callingId = Binder.clearCallingIdentity();
6478        try {
6479            synchronized (mInstallLock) {
6480                final String[] instructionSets = new String[] { targetInstructionSet };
6481                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6482                        true /* inclDependencies */);
6483                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6484            }
6485        } finally {
6486            Binder.restoreCallingIdentity(callingId);
6487        }
6488    }
6489
6490    public ArraySet<String> getPackagesThatNeedDexOpt() {
6491        ArraySet<String> pkgs = null;
6492        synchronized (mPackages) {
6493            for (PackageParser.Package p : mPackages.values()) {
6494                if (DEBUG_DEXOPT) {
6495                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6496                }
6497                if (!p.mDexOptPerformed.isEmpty()) {
6498                    continue;
6499                }
6500                if (pkgs == null) {
6501                    pkgs = new ArraySet<String>();
6502                }
6503                pkgs.add(p.packageName);
6504            }
6505        }
6506        return pkgs;
6507    }
6508
6509    public void shutdown() {
6510        mPackageUsage.write(true);
6511    }
6512
6513    @Override
6514    public void forceDexOpt(String packageName) {
6515        enforceSystemOrRoot("forceDexOpt");
6516
6517        PackageParser.Package pkg;
6518        synchronized (mPackages) {
6519            pkg = mPackages.get(packageName);
6520            if (pkg == null) {
6521                throw new IllegalArgumentException("Missing package: " + packageName);
6522            }
6523        }
6524
6525        synchronized (mInstallLock) {
6526            final String[] instructionSets = new String[] {
6527                    getPrimaryInstructionSet(pkg.applicationInfo) };
6528
6529            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6530
6531            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6532                    true /* inclDependencies */);
6533
6534            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6535            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6536                throw new IllegalStateException("Failed to dexopt: " + res);
6537            }
6538        }
6539    }
6540
6541    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6542        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6543            Slog.w(TAG, "Unable to update from " + oldPkg.name
6544                    + " to " + newPkg.packageName
6545                    + ": old package not in system partition");
6546            return false;
6547        } else if (mPackages.get(oldPkg.name) != null) {
6548            Slog.w(TAG, "Unable to update from " + oldPkg.name
6549                    + " to " + newPkg.packageName
6550                    + ": old package still exists");
6551            return false;
6552        }
6553        return true;
6554    }
6555
6556    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6557            throws PackageManagerException {
6558        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6559        if (res != 0) {
6560            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6561                    "Failed to install " + packageName + ": " + res);
6562        }
6563
6564        final int[] users = sUserManager.getUserIds();
6565        for (int user : users) {
6566            if (user != 0) {
6567                res = mInstaller.createUserData(volumeUuid, packageName,
6568                        UserHandle.getUid(user, uid), user, seinfo);
6569                if (res != 0) {
6570                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6571                            "Failed to createUserData " + packageName + ": " + res);
6572                }
6573            }
6574        }
6575    }
6576
6577    private int removeDataDirsLI(String volumeUuid, String packageName) {
6578        int[] users = sUserManager.getUserIds();
6579        int res = 0;
6580        for (int user : users) {
6581            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6582            if (resInner < 0) {
6583                res = resInner;
6584            }
6585        }
6586
6587        return res;
6588    }
6589
6590    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6591        int[] users = sUserManager.getUserIds();
6592        int res = 0;
6593        for (int user : users) {
6594            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6595            if (resInner < 0) {
6596                res = resInner;
6597            }
6598        }
6599        return res;
6600    }
6601
6602    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6603            PackageParser.Package changingLib) {
6604        if (file.path != null) {
6605            usesLibraryFiles.add(file.path);
6606            return;
6607        }
6608        PackageParser.Package p = mPackages.get(file.apk);
6609        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6610            // If we are doing this while in the middle of updating a library apk,
6611            // then we need to make sure to use that new apk for determining the
6612            // dependencies here.  (We haven't yet finished committing the new apk
6613            // to the package manager state.)
6614            if (p == null || p.packageName.equals(changingLib.packageName)) {
6615                p = changingLib;
6616            }
6617        }
6618        if (p != null) {
6619            usesLibraryFiles.addAll(p.getAllCodePaths());
6620        }
6621    }
6622
6623    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6624            PackageParser.Package changingLib) throws PackageManagerException {
6625        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6626            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6627            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6628            for (int i=0; i<N; i++) {
6629                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6630                if (file == null) {
6631                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6632                            "Package " + pkg.packageName + " requires unavailable shared library "
6633                            + pkg.usesLibraries.get(i) + "; failing!");
6634                }
6635                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6636            }
6637            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6638            for (int i=0; i<N; i++) {
6639                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6640                if (file == null) {
6641                    Slog.w(TAG, "Package " + pkg.packageName
6642                            + " desires unavailable shared library "
6643                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6644                } else {
6645                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6646                }
6647            }
6648            N = usesLibraryFiles.size();
6649            if (N > 0) {
6650                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6651            } else {
6652                pkg.usesLibraryFiles = null;
6653            }
6654        }
6655    }
6656
6657    private static boolean hasString(List<String> list, List<String> which) {
6658        if (list == null) {
6659            return false;
6660        }
6661        for (int i=list.size()-1; i>=0; i--) {
6662            for (int j=which.size()-1; j>=0; j--) {
6663                if (which.get(j).equals(list.get(i))) {
6664                    return true;
6665                }
6666            }
6667        }
6668        return false;
6669    }
6670
6671    private void updateAllSharedLibrariesLPw() {
6672        for (PackageParser.Package pkg : mPackages.values()) {
6673            try {
6674                updateSharedLibrariesLPw(pkg, null);
6675            } catch (PackageManagerException e) {
6676                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6677            }
6678        }
6679    }
6680
6681    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6682            PackageParser.Package changingPkg) {
6683        ArrayList<PackageParser.Package> res = null;
6684        for (PackageParser.Package pkg : mPackages.values()) {
6685            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6686                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6687                if (res == null) {
6688                    res = new ArrayList<PackageParser.Package>();
6689                }
6690                res.add(pkg);
6691                try {
6692                    updateSharedLibrariesLPw(pkg, changingPkg);
6693                } catch (PackageManagerException e) {
6694                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6695                }
6696            }
6697        }
6698        return res;
6699    }
6700
6701    /**
6702     * Derive the value of the {@code cpuAbiOverride} based on the provided
6703     * value and an optional stored value from the package settings.
6704     */
6705    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6706        String cpuAbiOverride = null;
6707
6708        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6709            cpuAbiOverride = null;
6710        } else if (abiOverride != null) {
6711            cpuAbiOverride = abiOverride;
6712        } else if (settings != null) {
6713            cpuAbiOverride = settings.cpuAbiOverrideString;
6714        }
6715
6716        return cpuAbiOverride;
6717    }
6718
6719    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6720            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6721        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6722        try {
6723            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6724        } finally {
6725            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6726        }
6727    }
6728
6729    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6730            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6731        boolean success = false;
6732        try {
6733            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6734                    currentTime, user);
6735            success = true;
6736            return res;
6737        } finally {
6738            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6739                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6740            }
6741        }
6742    }
6743
6744    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6745            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6746        final File scanFile = new File(pkg.codePath);
6747        if (pkg.applicationInfo.getCodePath() == null ||
6748                pkg.applicationInfo.getResourcePath() == null) {
6749            // Bail out. The resource and code paths haven't been set.
6750            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6751                    "Code and resource paths haven't been set correctly");
6752        }
6753
6754        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6755            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6756        } else {
6757            // Only allow system apps to be flagged as core apps.
6758            pkg.coreApp = false;
6759        }
6760
6761        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6762            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6763        }
6764
6765        if (mCustomResolverComponentName != null &&
6766                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6767            setUpCustomResolverActivity(pkg);
6768        }
6769
6770        if (pkg.packageName.equals("android")) {
6771            synchronized (mPackages) {
6772                if (mAndroidApplication != null) {
6773                    Slog.w(TAG, "*************************************************");
6774                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6775                    Slog.w(TAG, " file=" + scanFile);
6776                    Slog.w(TAG, "*************************************************");
6777                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6778                            "Core android package being redefined.  Skipping.");
6779                }
6780
6781                // Set up information for our fall-back user intent resolution activity.
6782                mPlatformPackage = pkg;
6783                pkg.mVersionCode = mSdkVersion;
6784                mAndroidApplication = pkg.applicationInfo;
6785
6786                if (!mResolverReplaced) {
6787                    mResolveActivity.applicationInfo = mAndroidApplication;
6788                    mResolveActivity.name = ResolverActivity.class.getName();
6789                    mResolveActivity.packageName = mAndroidApplication.packageName;
6790                    mResolveActivity.processName = "system:ui";
6791                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6792                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6793                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6794                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6795                    mResolveActivity.exported = true;
6796                    mResolveActivity.enabled = true;
6797                    mResolveInfo.activityInfo = mResolveActivity;
6798                    mResolveInfo.priority = 0;
6799                    mResolveInfo.preferredOrder = 0;
6800                    mResolveInfo.match = 0;
6801                    mResolveComponentName = new ComponentName(
6802                            mAndroidApplication.packageName, mResolveActivity.name);
6803                }
6804            }
6805        }
6806
6807        if (DEBUG_PACKAGE_SCANNING) {
6808            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6809                Log.d(TAG, "Scanning package " + pkg.packageName);
6810        }
6811
6812        if (mPackages.containsKey(pkg.packageName)
6813                || mSharedLibraries.containsKey(pkg.packageName)) {
6814            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6815                    "Application package " + pkg.packageName
6816                    + " already installed.  Skipping duplicate.");
6817        }
6818
6819        // If we're only installing presumed-existing packages, require that the
6820        // scanned APK is both already known and at the path previously established
6821        // for it.  Previously unknown packages we pick up normally, but if we have an
6822        // a priori expectation about this package's install presence, enforce it.
6823        // With a singular exception for new system packages. When an OTA contains
6824        // a new system package, we allow the codepath to change from a system location
6825        // to the user-installed location. If we don't allow this change, any newer,
6826        // user-installed version of the application will be ignored.
6827        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6828            if (mExpectingBetter.containsKey(pkg.packageName)) {
6829                logCriticalInfo(Log.WARN,
6830                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6831            } else {
6832                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6833                if (known != null) {
6834                    if (DEBUG_PACKAGE_SCANNING) {
6835                        Log.d(TAG, "Examining " + pkg.codePath
6836                                + " and requiring known paths " + known.codePathString
6837                                + " & " + known.resourcePathString);
6838                    }
6839                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6840                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6841                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6842                                "Application package " + pkg.packageName
6843                                + " found at " + pkg.applicationInfo.getCodePath()
6844                                + " but expected at " + known.codePathString + "; ignoring.");
6845                    }
6846                }
6847            }
6848        }
6849
6850        // Initialize package source and resource directories
6851        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6852        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6853
6854        SharedUserSetting suid = null;
6855        PackageSetting pkgSetting = null;
6856
6857        if (!isSystemApp(pkg)) {
6858            // Only system apps can use these features.
6859            pkg.mOriginalPackages = null;
6860            pkg.mRealPackage = null;
6861            pkg.mAdoptPermissions = null;
6862        }
6863
6864        // writer
6865        synchronized (mPackages) {
6866            if (pkg.mSharedUserId != null) {
6867                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6868                if (suid == null) {
6869                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6870                            "Creating application package " + pkg.packageName
6871                            + " for shared user failed");
6872                }
6873                if (DEBUG_PACKAGE_SCANNING) {
6874                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6875                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6876                                + "): packages=" + suid.packages);
6877                }
6878            }
6879
6880            // Check if we are renaming from an original package name.
6881            PackageSetting origPackage = null;
6882            String realName = null;
6883            if (pkg.mOriginalPackages != null) {
6884                // This package may need to be renamed to a previously
6885                // installed name.  Let's check on that...
6886                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6887                if (pkg.mOriginalPackages.contains(renamed)) {
6888                    // This package had originally been installed as the
6889                    // original name, and we have already taken care of
6890                    // transitioning to the new one.  Just update the new
6891                    // one to continue using the old name.
6892                    realName = pkg.mRealPackage;
6893                    if (!pkg.packageName.equals(renamed)) {
6894                        // Callers into this function may have already taken
6895                        // care of renaming the package; only do it here if
6896                        // it is not already done.
6897                        pkg.setPackageName(renamed);
6898                    }
6899
6900                } else {
6901                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6902                        if ((origPackage = mSettings.peekPackageLPr(
6903                                pkg.mOriginalPackages.get(i))) != null) {
6904                            // We do have the package already installed under its
6905                            // original name...  should we use it?
6906                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6907                                // New package is not compatible with original.
6908                                origPackage = null;
6909                                continue;
6910                            } else if (origPackage.sharedUser != null) {
6911                                // Make sure uid is compatible between packages.
6912                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6913                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6914                                            + " to " + pkg.packageName + ": old uid "
6915                                            + origPackage.sharedUser.name
6916                                            + " differs from " + pkg.mSharedUserId);
6917                                    origPackage = null;
6918                                    continue;
6919                                }
6920                            } else {
6921                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6922                                        + pkg.packageName + " to old name " + origPackage.name);
6923                            }
6924                            break;
6925                        }
6926                    }
6927                }
6928            }
6929
6930            if (mTransferedPackages.contains(pkg.packageName)) {
6931                Slog.w(TAG, "Package " + pkg.packageName
6932                        + " was transferred to another, but its .apk remains");
6933            }
6934
6935            // Just create the setting, don't add it yet. For already existing packages
6936            // the PkgSetting exists already and doesn't have to be created.
6937            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6938                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6939                    pkg.applicationInfo.primaryCpuAbi,
6940                    pkg.applicationInfo.secondaryCpuAbi,
6941                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6942                    user, false);
6943            if (pkgSetting == null) {
6944                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6945                        "Creating application package " + pkg.packageName + " failed");
6946            }
6947
6948            if (pkgSetting.origPackage != null) {
6949                // If we are first transitioning from an original package,
6950                // fix up the new package's name now.  We need to do this after
6951                // looking up the package under its new name, so getPackageLP
6952                // can take care of fiddling things correctly.
6953                pkg.setPackageName(origPackage.name);
6954
6955                // File a report about this.
6956                String msg = "New package " + pkgSetting.realName
6957                        + " renamed to replace old package " + pkgSetting.name;
6958                reportSettingsProblem(Log.WARN, msg);
6959
6960                // Make a note of it.
6961                mTransferedPackages.add(origPackage.name);
6962
6963                // No longer need to retain this.
6964                pkgSetting.origPackage = null;
6965            }
6966
6967            if (realName != null) {
6968                // Make a note of it.
6969                mTransferedPackages.add(pkg.packageName);
6970            }
6971
6972            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6973                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6974            }
6975
6976            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6977                // Check all shared libraries and map to their actual file path.
6978                // We only do this here for apps not on a system dir, because those
6979                // are the only ones that can fail an install due to this.  We
6980                // will take care of the system apps by updating all of their
6981                // library paths after the scan is done.
6982                updateSharedLibrariesLPw(pkg, null);
6983            }
6984
6985            if (mFoundPolicyFile) {
6986                SELinuxMMAC.assignSeinfoValue(pkg);
6987            }
6988
6989            pkg.applicationInfo.uid = pkgSetting.appId;
6990            pkg.mExtras = pkgSetting;
6991            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6992                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6993                    // We just determined the app is signed correctly, so bring
6994                    // over the latest parsed certs.
6995                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6996                } else {
6997                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6998                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6999                                "Package " + pkg.packageName + " upgrade keys do not match the "
7000                                + "previously installed version");
7001                    } else {
7002                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7003                        String msg = "System package " + pkg.packageName
7004                            + " signature changed; retaining data.";
7005                        reportSettingsProblem(Log.WARN, msg);
7006                    }
7007                }
7008            } else {
7009                try {
7010                    verifySignaturesLP(pkgSetting, pkg);
7011                    // We just determined the app is signed correctly, so bring
7012                    // over the latest parsed certs.
7013                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7014                } catch (PackageManagerException e) {
7015                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7016                        throw e;
7017                    }
7018                    // The signature has changed, but this package is in the system
7019                    // image...  let's recover!
7020                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7021                    // However...  if this package is part of a shared user, but it
7022                    // doesn't match the signature of the shared user, let's fail.
7023                    // What this means is that you can't change the signatures
7024                    // associated with an overall shared user, which doesn't seem all
7025                    // that unreasonable.
7026                    if (pkgSetting.sharedUser != null) {
7027                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7028                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7029                            throw new PackageManagerException(
7030                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7031                                            "Signature mismatch for shared user : "
7032                                            + pkgSetting.sharedUser);
7033                        }
7034                    }
7035                    // File a report about this.
7036                    String msg = "System package " + pkg.packageName
7037                        + " signature changed; retaining data.";
7038                    reportSettingsProblem(Log.WARN, msg);
7039                }
7040            }
7041            // Verify that this new package doesn't have any content providers
7042            // that conflict with existing packages.  Only do this if the
7043            // package isn't already installed, since we don't want to break
7044            // things that are installed.
7045            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7046                final int N = pkg.providers.size();
7047                int i;
7048                for (i=0; i<N; i++) {
7049                    PackageParser.Provider p = pkg.providers.get(i);
7050                    if (p.info.authority != null) {
7051                        String names[] = p.info.authority.split(";");
7052                        for (int j = 0; j < names.length; j++) {
7053                            if (mProvidersByAuthority.containsKey(names[j])) {
7054                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7055                                final String otherPackageName =
7056                                        ((other != null && other.getComponentName() != null) ?
7057                                                other.getComponentName().getPackageName() : "?");
7058                                throw new PackageManagerException(
7059                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7060                                                "Can't install because provider name " + names[j]
7061                                                + " (in package " + pkg.applicationInfo.packageName
7062                                                + ") is already used by " + otherPackageName);
7063                            }
7064                        }
7065                    }
7066                }
7067            }
7068
7069            if (pkg.mAdoptPermissions != null) {
7070                // This package wants to adopt ownership of permissions from
7071                // another package.
7072                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7073                    final String origName = pkg.mAdoptPermissions.get(i);
7074                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7075                    if (orig != null) {
7076                        if (verifyPackageUpdateLPr(orig, pkg)) {
7077                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7078                                    + pkg.packageName);
7079                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7080                        }
7081                    }
7082                }
7083            }
7084        }
7085
7086        final String pkgName = pkg.packageName;
7087
7088        final long scanFileTime = scanFile.lastModified();
7089        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7090        pkg.applicationInfo.processName = fixProcessName(
7091                pkg.applicationInfo.packageName,
7092                pkg.applicationInfo.processName,
7093                pkg.applicationInfo.uid);
7094
7095        if (pkg != mPlatformPackage) {
7096            // This is a normal package, need to make its data directory.
7097            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7098                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7099
7100            boolean uidError = false;
7101            if (dataPath.exists()) {
7102                int currentUid = 0;
7103                try {
7104                    StructStat stat = Os.stat(dataPath.getPath());
7105                    currentUid = stat.st_uid;
7106                } catch (ErrnoException e) {
7107                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7108                }
7109
7110                // If we have mismatched owners for the data path, we have a problem.
7111                if (currentUid != pkg.applicationInfo.uid) {
7112                    boolean recovered = false;
7113                    if (currentUid == 0) {
7114                        // The directory somehow became owned by root.  Wow.
7115                        // This is probably because the system was stopped while
7116                        // installd was in the middle of messing with its libs
7117                        // directory.  Ask installd to fix that.
7118                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7119                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7120                        if (ret >= 0) {
7121                            recovered = true;
7122                            String msg = "Package " + pkg.packageName
7123                                    + " unexpectedly changed to uid 0; recovered to " +
7124                                    + pkg.applicationInfo.uid;
7125                            reportSettingsProblem(Log.WARN, msg);
7126                        }
7127                    }
7128                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7129                            || (scanFlags&SCAN_BOOTING) != 0)) {
7130                        // If this is a system app, we can at least delete its
7131                        // current data so the application will still work.
7132                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7133                        if (ret >= 0) {
7134                            // TODO: Kill the processes first
7135                            // Old data gone!
7136                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7137                                    ? "System package " : "Third party package ";
7138                            String msg = prefix + pkg.packageName
7139                                    + " has changed from uid: "
7140                                    + currentUid + " to "
7141                                    + pkg.applicationInfo.uid + "; old data erased";
7142                            reportSettingsProblem(Log.WARN, msg);
7143                            recovered = true;
7144                        }
7145                        if (!recovered) {
7146                            mHasSystemUidErrors = true;
7147                        }
7148                    } else if (!recovered) {
7149                        // If we allow this install to proceed, we will be broken.
7150                        // Abort, abort!
7151                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7152                                "scanPackageLI");
7153                    }
7154                    if (!recovered) {
7155                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7156                            + pkg.applicationInfo.uid + "/fs_"
7157                            + currentUid;
7158                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7159                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7160                        String msg = "Package " + pkg.packageName
7161                                + " has mismatched uid: "
7162                                + currentUid + " on disk, "
7163                                + pkg.applicationInfo.uid + " in settings";
7164                        // writer
7165                        synchronized (mPackages) {
7166                            mSettings.mReadMessages.append(msg);
7167                            mSettings.mReadMessages.append('\n');
7168                            uidError = true;
7169                            if (!pkgSetting.uidError) {
7170                                reportSettingsProblem(Log.ERROR, msg);
7171                            }
7172                        }
7173                    }
7174                }
7175
7176                // Ensure that directories are prepared
7177                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7178                        pkg.applicationInfo.seinfo);
7179
7180                if (mShouldRestoreconData) {
7181                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7182                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7183                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7184                }
7185            } else {
7186                if (DEBUG_PACKAGE_SCANNING) {
7187                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7188                        Log.v(TAG, "Want this data dir: " + dataPath);
7189                }
7190                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7191                        pkg.applicationInfo.seinfo);
7192            }
7193
7194            // Get all of our default paths setup
7195            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7196
7197            pkgSetting.uidError = uidError;
7198        }
7199
7200        final String path = scanFile.getPath();
7201        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7202
7203        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7204            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7205
7206            // Some system apps still use directory structure for native libraries
7207            // in which case we might end up not detecting abi solely based on apk
7208            // structure. Try to detect abi based on directory structure.
7209            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7210                    pkg.applicationInfo.primaryCpuAbi == null) {
7211                setBundledAppAbisAndRoots(pkg, pkgSetting);
7212                setNativeLibraryPaths(pkg);
7213            }
7214
7215        } else {
7216            if ((scanFlags & SCAN_MOVE) != 0) {
7217                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7218                // but we already have this packages package info in the PackageSetting. We just
7219                // use that and derive the native library path based on the new codepath.
7220                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7221                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7222            }
7223
7224            // Set native library paths again. For moves, the path will be updated based on the
7225            // ABIs we've determined above. For non-moves, the path will be updated based on the
7226            // ABIs we determined during compilation, but the path will depend on the final
7227            // package path (after the rename away from the stage path).
7228            setNativeLibraryPaths(pkg);
7229        }
7230
7231        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7232        final int[] userIds = sUserManager.getUserIds();
7233        synchronized (mInstallLock) {
7234            // Make sure all user data directories are ready to roll; we're okay
7235            // if they already exist
7236            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7237                for (int userId : userIds) {
7238                    if (userId != UserHandle.USER_SYSTEM) {
7239                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7240                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7241                                pkg.applicationInfo.seinfo);
7242                    }
7243                }
7244            }
7245
7246            // Create a native library symlink only if we have native libraries
7247            // and if the native libraries are 32 bit libraries. We do not provide
7248            // this symlink for 64 bit libraries.
7249            if (pkg.applicationInfo.primaryCpuAbi != null &&
7250                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7251                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7252                try {
7253                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7254                    for (int userId : userIds) {
7255                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7256                                nativeLibPath, userId) < 0) {
7257                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7258                                    "Failed linking native library dir (user=" + userId + ")");
7259                        }
7260                    }
7261                } finally {
7262                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7263                }
7264            }
7265        }
7266
7267        // This is a special case for the "system" package, where the ABI is
7268        // dictated by the zygote configuration (and init.rc). We should keep track
7269        // of this ABI so that we can deal with "normal" applications that run under
7270        // the same UID correctly.
7271        if (mPlatformPackage == pkg) {
7272            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7273                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7274        }
7275
7276        // If there's a mismatch between the abi-override in the package setting
7277        // and the abiOverride specified for the install. Warn about this because we
7278        // would've already compiled the app without taking the package setting into
7279        // account.
7280        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7281            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7282                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7283                        " for package: " + pkg.packageName);
7284            }
7285        }
7286
7287        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7288        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7289        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7290
7291        // Copy the derived override back to the parsed package, so that we can
7292        // update the package settings accordingly.
7293        pkg.cpuAbiOverride = cpuAbiOverride;
7294
7295        if (DEBUG_ABI_SELECTION) {
7296            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7297                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7298                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7299        }
7300
7301        // Push the derived path down into PackageSettings so we know what to
7302        // clean up at uninstall time.
7303        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7304
7305        if (DEBUG_ABI_SELECTION) {
7306            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7307                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7308                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7309        }
7310
7311        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7312            // We don't do this here during boot because we can do it all
7313            // at once after scanning all existing packages.
7314            //
7315            // We also do this *before* we perform dexopt on this package, so that
7316            // we can avoid redundant dexopts, and also to make sure we've got the
7317            // code and package path correct.
7318            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7319                    pkg, true /* boot complete */);
7320        }
7321
7322        if (mFactoryTest && pkg.requestedPermissions.contains(
7323                android.Manifest.permission.FACTORY_TEST)) {
7324            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7325        }
7326
7327        ArrayList<PackageParser.Package> clientLibPkgs = null;
7328
7329        // writer
7330        synchronized (mPackages) {
7331            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7332                // Only system apps can add new shared libraries.
7333                if (pkg.libraryNames != null) {
7334                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7335                        String name = pkg.libraryNames.get(i);
7336                        boolean allowed = false;
7337                        if (pkg.isUpdatedSystemApp()) {
7338                            // New library entries can only be added through the
7339                            // system image.  This is important to get rid of a lot
7340                            // of nasty edge cases: for example if we allowed a non-
7341                            // system update of the app to add a library, then uninstalling
7342                            // the update would make the library go away, and assumptions
7343                            // we made such as through app install filtering would now
7344                            // have allowed apps on the device which aren't compatible
7345                            // with it.  Better to just have the restriction here, be
7346                            // conservative, and create many fewer cases that can negatively
7347                            // impact the user experience.
7348                            final PackageSetting sysPs = mSettings
7349                                    .getDisabledSystemPkgLPr(pkg.packageName);
7350                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7351                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7352                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7353                                        allowed = true;
7354                                        break;
7355                                    }
7356                                }
7357                            }
7358                        } else {
7359                            allowed = true;
7360                        }
7361                        if (allowed) {
7362                            if (!mSharedLibraries.containsKey(name)) {
7363                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7364                            } else if (!name.equals(pkg.packageName)) {
7365                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7366                                        + name + " already exists; skipping");
7367                            }
7368                        } else {
7369                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7370                                    + name + " that is not declared on system image; skipping");
7371                        }
7372                    }
7373                    if ((scanFlags & SCAN_BOOTING) == 0) {
7374                        // If we are not booting, we need to update any applications
7375                        // that are clients of our shared library.  If we are booting,
7376                        // this will all be done once the scan is complete.
7377                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7378                    }
7379                }
7380            }
7381        }
7382
7383        // Request the ActivityManager to kill the process(only for existing packages)
7384        // so that we do not end up in a confused state while the user is still using the older
7385        // version of the application while the new one gets installed.
7386        if ((scanFlags & SCAN_REPLACING) != 0) {
7387            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7388
7389            killApplication(pkg.applicationInfo.packageName,
7390                        pkg.applicationInfo.uid, "replace pkg");
7391
7392            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7393        }
7394
7395        // Also need to kill any apps that are dependent on the library.
7396        if (clientLibPkgs != null) {
7397            for (int i=0; i<clientLibPkgs.size(); i++) {
7398                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7399                killApplication(clientPkg.applicationInfo.packageName,
7400                        clientPkg.applicationInfo.uid, "update lib");
7401            }
7402        }
7403
7404        // Make sure we're not adding any bogus keyset info
7405        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7406        ksms.assertScannedPackageValid(pkg);
7407
7408        // writer
7409        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7410
7411        boolean createIdmapFailed = false;
7412        synchronized (mPackages) {
7413            // We don't expect installation to fail beyond this point
7414
7415            // Add the new setting to mSettings
7416            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7417            // Add the new setting to mPackages
7418            mPackages.put(pkg.applicationInfo.packageName, pkg);
7419            // Make sure we don't accidentally delete its data.
7420            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7421            while (iter.hasNext()) {
7422                PackageCleanItem item = iter.next();
7423                if (pkgName.equals(item.packageName)) {
7424                    iter.remove();
7425                }
7426            }
7427
7428            // Take care of first install / last update times.
7429            if (currentTime != 0) {
7430                if (pkgSetting.firstInstallTime == 0) {
7431                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7432                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7433                    pkgSetting.lastUpdateTime = currentTime;
7434                }
7435            } else if (pkgSetting.firstInstallTime == 0) {
7436                // We need *something*.  Take time time stamp of the file.
7437                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7438            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7439                if (scanFileTime != pkgSetting.timeStamp) {
7440                    // A package on the system image has changed; consider this
7441                    // to be an update.
7442                    pkgSetting.lastUpdateTime = scanFileTime;
7443                }
7444            }
7445
7446            // Add the package's KeySets to the global KeySetManagerService
7447            ksms.addScannedPackageLPw(pkg);
7448
7449            int N = pkg.providers.size();
7450            StringBuilder r = null;
7451            int i;
7452            for (i=0; i<N; i++) {
7453                PackageParser.Provider p = pkg.providers.get(i);
7454                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7455                        p.info.processName, pkg.applicationInfo.uid);
7456                mProviders.addProvider(p);
7457                p.syncable = p.info.isSyncable;
7458                if (p.info.authority != null) {
7459                    String names[] = p.info.authority.split(";");
7460                    p.info.authority = null;
7461                    for (int j = 0; j < names.length; j++) {
7462                        if (j == 1 && p.syncable) {
7463                            // We only want the first authority for a provider to possibly be
7464                            // syncable, so if we already added this provider using a different
7465                            // authority clear the syncable flag. We copy the provider before
7466                            // changing it because the mProviders object contains a reference
7467                            // to a provider that we don't want to change.
7468                            // Only do this for the second authority since the resulting provider
7469                            // object can be the same for all future authorities for this provider.
7470                            p = new PackageParser.Provider(p);
7471                            p.syncable = false;
7472                        }
7473                        if (!mProvidersByAuthority.containsKey(names[j])) {
7474                            mProvidersByAuthority.put(names[j], p);
7475                            if (p.info.authority == null) {
7476                                p.info.authority = names[j];
7477                            } else {
7478                                p.info.authority = p.info.authority + ";" + names[j];
7479                            }
7480                            if (DEBUG_PACKAGE_SCANNING) {
7481                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7482                                    Log.d(TAG, "Registered content provider: " + names[j]
7483                                            + ", className = " + p.info.name + ", isSyncable = "
7484                                            + p.info.isSyncable);
7485                            }
7486                        } else {
7487                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7488                            Slog.w(TAG, "Skipping provider name " + names[j] +
7489                                    " (in package " + pkg.applicationInfo.packageName +
7490                                    "): name already used by "
7491                                    + ((other != null && other.getComponentName() != null)
7492                                            ? other.getComponentName().getPackageName() : "?"));
7493                        }
7494                    }
7495                }
7496                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7497                    if (r == null) {
7498                        r = new StringBuilder(256);
7499                    } else {
7500                        r.append(' ');
7501                    }
7502                    r.append(p.info.name);
7503                }
7504            }
7505            if (r != null) {
7506                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7507            }
7508
7509            N = pkg.services.size();
7510            r = null;
7511            for (i=0; i<N; i++) {
7512                PackageParser.Service s = pkg.services.get(i);
7513                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7514                        s.info.processName, pkg.applicationInfo.uid);
7515                mServices.addService(s);
7516                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7517                    if (r == null) {
7518                        r = new StringBuilder(256);
7519                    } else {
7520                        r.append(' ');
7521                    }
7522                    r.append(s.info.name);
7523                }
7524            }
7525            if (r != null) {
7526                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7527            }
7528
7529            N = pkg.receivers.size();
7530            r = null;
7531            for (i=0; i<N; i++) {
7532                PackageParser.Activity a = pkg.receivers.get(i);
7533                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7534                        a.info.processName, pkg.applicationInfo.uid);
7535                mReceivers.addActivity(a, "receiver");
7536                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7537                    if (r == null) {
7538                        r = new StringBuilder(256);
7539                    } else {
7540                        r.append(' ');
7541                    }
7542                    r.append(a.info.name);
7543                }
7544            }
7545            if (r != null) {
7546                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7547            }
7548
7549            N = pkg.activities.size();
7550            r = null;
7551            for (i=0; i<N; i++) {
7552                PackageParser.Activity a = pkg.activities.get(i);
7553                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7554                        a.info.processName, pkg.applicationInfo.uid);
7555                mActivities.addActivity(a, "activity");
7556                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7557                    if (r == null) {
7558                        r = new StringBuilder(256);
7559                    } else {
7560                        r.append(' ');
7561                    }
7562                    r.append(a.info.name);
7563                }
7564            }
7565            if (r != null) {
7566                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7567            }
7568
7569            N = pkg.permissionGroups.size();
7570            r = null;
7571            for (i=0; i<N; i++) {
7572                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7573                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7574                if (cur == null) {
7575                    mPermissionGroups.put(pg.info.name, pg);
7576                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7577                        if (r == null) {
7578                            r = new StringBuilder(256);
7579                        } else {
7580                            r.append(' ');
7581                        }
7582                        r.append(pg.info.name);
7583                    }
7584                } else {
7585                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7586                            + pg.info.packageName + " ignored: original from "
7587                            + cur.info.packageName);
7588                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7589                        if (r == null) {
7590                            r = new StringBuilder(256);
7591                        } else {
7592                            r.append(' ');
7593                        }
7594                        r.append("DUP:");
7595                        r.append(pg.info.name);
7596                    }
7597                }
7598            }
7599            if (r != null) {
7600                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7601            }
7602
7603            N = pkg.permissions.size();
7604            r = null;
7605            for (i=0; i<N; i++) {
7606                PackageParser.Permission p = pkg.permissions.get(i);
7607
7608                // Assume by default that we did not install this permission into the system.
7609                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7610
7611                // Now that permission groups have a special meaning, we ignore permission
7612                // groups for legacy apps to prevent unexpected behavior. In particular,
7613                // permissions for one app being granted to someone just becuase they happen
7614                // to be in a group defined by another app (before this had no implications).
7615                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7616                    p.group = mPermissionGroups.get(p.info.group);
7617                    // Warn for a permission in an unknown group.
7618                    if (p.info.group != null && p.group == null) {
7619                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7620                                + p.info.packageName + " in an unknown group " + p.info.group);
7621                    }
7622                }
7623
7624                ArrayMap<String, BasePermission> permissionMap =
7625                        p.tree ? mSettings.mPermissionTrees
7626                                : mSettings.mPermissions;
7627                BasePermission bp = permissionMap.get(p.info.name);
7628
7629                // Allow system apps to redefine non-system permissions
7630                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7631                    final boolean currentOwnerIsSystem = (bp.perm != null
7632                            && isSystemApp(bp.perm.owner));
7633                    if (isSystemApp(p.owner)) {
7634                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7635                            // It's a built-in permission and no owner, take ownership now
7636                            bp.packageSetting = pkgSetting;
7637                            bp.perm = p;
7638                            bp.uid = pkg.applicationInfo.uid;
7639                            bp.sourcePackage = p.info.packageName;
7640                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7641                        } else if (!currentOwnerIsSystem) {
7642                            String msg = "New decl " + p.owner + " of permission  "
7643                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7644                            reportSettingsProblem(Log.WARN, msg);
7645                            bp = null;
7646                        }
7647                    }
7648                }
7649
7650                if (bp == null) {
7651                    bp = new BasePermission(p.info.name, p.info.packageName,
7652                            BasePermission.TYPE_NORMAL);
7653                    permissionMap.put(p.info.name, bp);
7654                }
7655
7656                if (bp.perm == null) {
7657                    if (bp.sourcePackage == null
7658                            || bp.sourcePackage.equals(p.info.packageName)) {
7659                        BasePermission tree = findPermissionTreeLP(p.info.name);
7660                        if (tree == null
7661                                || tree.sourcePackage.equals(p.info.packageName)) {
7662                            bp.packageSetting = pkgSetting;
7663                            bp.perm = p;
7664                            bp.uid = pkg.applicationInfo.uid;
7665                            bp.sourcePackage = p.info.packageName;
7666                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7667                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7668                                if (r == null) {
7669                                    r = new StringBuilder(256);
7670                                } else {
7671                                    r.append(' ');
7672                                }
7673                                r.append(p.info.name);
7674                            }
7675                        } else {
7676                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7677                                    + p.info.packageName + " ignored: base tree "
7678                                    + tree.name + " is from package "
7679                                    + tree.sourcePackage);
7680                        }
7681                    } else {
7682                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7683                                + p.info.packageName + " ignored: original from "
7684                                + bp.sourcePackage);
7685                    }
7686                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7687                    if (r == null) {
7688                        r = new StringBuilder(256);
7689                    } else {
7690                        r.append(' ');
7691                    }
7692                    r.append("DUP:");
7693                    r.append(p.info.name);
7694                }
7695                if (bp.perm == p) {
7696                    bp.protectionLevel = p.info.protectionLevel;
7697                }
7698            }
7699
7700            if (r != null) {
7701                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7702            }
7703
7704            N = pkg.instrumentation.size();
7705            r = null;
7706            for (i=0; i<N; i++) {
7707                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7708                a.info.packageName = pkg.applicationInfo.packageName;
7709                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7710                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7711                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7712                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7713                a.info.dataDir = pkg.applicationInfo.dataDir;
7714                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7715                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7716
7717                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7718                // need other information about the application, like the ABI and what not ?
7719                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7720                mInstrumentation.put(a.getComponentName(), a);
7721                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7722                    if (r == null) {
7723                        r = new StringBuilder(256);
7724                    } else {
7725                        r.append(' ');
7726                    }
7727                    r.append(a.info.name);
7728                }
7729            }
7730            if (r != null) {
7731                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7732            }
7733
7734            if (pkg.protectedBroadcasts != null) {
7735                N = pkg.protectedBroadcasts.size();
7736                for (i=0; i<N; i++) {
7737                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7738                }
7739            }
7740
7741            pkgSetting.setTimeStamp(scanFileTime);
7742
7743            // Create idmap files for pairs of (packages, overlay packages).
7744            // Note: "android", ie framework-res.apk, is handled by native layers.
7745            if (pkg.mOverlayTarget != null) {
7746                // This is an overlay package.
7747                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7748                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7749                        mOverlays.put(pkg.mOverlayTarget,
7750                                new ArrayMap<String, PackageParser.Package>());
7751                    }
7752                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7753                    map.put(pkg.packageName, pkg);
7754                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7755                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7756                        createIdmapFailed = true;
7757                    }
7758                }
7759            } else if (mOverlays.containsKey(pkg.packageName) &&
7760                    !pkg.packageName.equals("android")) {
7761                // This is a regular package, with one or more known overlay packages.
7762                createIdmapsForPackageLI(pkg);
7763            }
7764        }
7765
7766        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7767
7768        if (createIdmapFailed) {
7769            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7770                    "scanPackageLI failed to createIdmap");
7771        }
7772        return pkg;
7773    }
7774
7775    /**
7776     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7777     * is derived purely on the basis of the contents of {@code scanFile} and
7778     * {@code cpuAbiOverride}.
7779     *
7780     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7781     */
7782    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7783                                 String cpuAbiOverride, boolean extractLibs)
7784            throws PackageManagerException {
7785        // TODO: We can probably be smarter about this stuff. For installed apps,
7786        // we can calculate this information at install time once and for all. For
7787        // system apps, we can probably assume that this information doesn't change
7788        // after the first boot scan. As things stand, we do lots of unnecessary work.
7789
7790        // Give ourselves some initial paths; we'll come back for another
7791        // pass once we've determined ABI below.
7792        setNativeLibraryPaths(pkg);
7793
7794        // We would never need to extract libs for forward-locked and external packages,
7795        // since the container service will do it for us. We shouldn't attempt to
7796        // extract libs from system app when it was not updated.
7797        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7798                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7799            extractLibs = false;
7800        }
7801
7802        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7803        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7804
7805        NativeLibraryHelper.Handle handle = null;
7806        try {
7807            handle = NativeLibraryHelper.Handle.create(pkg);
7808            // TODO(multiArch): This can be null for apps that didn't go through the
7809            // usual installation process. We can calculate it again, like we
7810            // do during install time.
7811            //
7812            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7813            // unnecessary.
7814            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7815
7816            // Null out the abis so that they can be recalculated.
7817            pkg.applicationInfo.primaryCpuAbi = null;
7818            pkg.applicationInfo.secondaryCpuAbi = null;
7819            if (isMultiArch(pkg.applicationInfo)) {
7820                // Warn if we've set an abiOverride for multi-lib packages..
7821                // By definition, we need to copy both 32 and 64 bit libraries for
7822                // such packages.
7823                if (pkg.cpuAbiOverride != null
7824                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7825                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7826                }
7827
7828                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7829                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7830                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7831                    if (extractLibs) {
7832                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7833                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7834                                useIsaSpecificSubdirs);
7835                    } else {
7836                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7837                    }
7838                }
7839
7840                maybeThrowExceptionForMultiArchCopy(
7841                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7842
7843                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7844                    if (extractLibs) {
7845                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7846                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7847                                useIsaSpecificSubdirs);
7848                    } else {
7849                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7850                    }
7851                }
7852
7853                maybeThrowExceptionForMultiArchCopy(
7854                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7855
7856                if (abi64 >= 0) {
7857                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7858                }
7859
7860                if (abi32 >= 0) {
7861                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7862                    if (abi64 >= 0) {
7863                        pkg.applicationInfo.secondaryCpuAbi = abi;
7864                    } else {
7865                        pkg.applicationInfo.primaryCpuAbi = abi;
7866                    }
7867                }
7868            } else {
7869                String[] abiList = (cpuAbiOverride != null) ?
7870                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7871
7872                // Enable gross and lame hacks for apps that are built with old
7873                // SDK tools. We must scan their APKs for renderscript bitcode and
7874                // not launch them if it's present. Don't bother checking on devices
7875                // that don't have 64 bit support.
7876                boolean needsRenderScriptOverride = false;
7877                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7878                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7879                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7880                    needsRenderScriptOverride = true;
7881                }
7882
7883                final int copyRet;
7884                if (extractLibs) {
7885                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7886                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7887                } else {
7888                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7889                }
7890
7891                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7892                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7893                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7894                }
7895
7896                if (copyRet >= 0) {
7897                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7898                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7899                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7900                } else if (needsRenderScriptOverride) {
7901                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7902                }
7903            }
7904        } catch (IOException ioe) {
7905            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7906        } finally {
7907            IoUtils.closeQuietly(handle);
7908        }
7909
7910        // Now that we've calculated the ABIs and determined if it's an internal app,
7911        // we will go ahead and populate the nativeLibraryPath.
7912        setNativeLibraryPaths(pkg);
7913    }
7914
7915    /**
7916     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7917     * i.e, so that all packages can be run inside a single process if required.
7918     *
7919     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7920     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7921     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7922     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7923     * updating a package that belongs to a shared user.
7924     *
7925     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7926     * adds unnecessary complexity.
7927     */
7928    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7929            PackageParser.Package scannedPackage, boolean bootComplete) {
7930        String requiredInstructionSet = null;
7931        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7932            requiredInstructionSet = VMRuntime.getInstructionSet(
7933                     scannedPackage.applicationInfo.primaryCpuAbi);
7934        }
7935
7936        PackageSetting requirer = null;
7937        for (PackageSetting ps : packagesForUser) {
7938            // If packagesForUser contains scannedPackage, we skip it. This will happen
7939            // when scannedPackage is an update of an existing package. Without this check,
7940            // we will never be able to change the ABI of any package belonging to a shared
7941            // user, even if it's compatible with other packages.
7942            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7943                if (ps.primaryCpuAbiString == null) {
7944                    continue;
7945                }
7946
7947                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7948                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7949                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7950                    // this but there's not much we can do.
7951                    String errorMessage = "Instruction set mismatch, "
7952                            + ((requirer == null) ? "[caller]" : requirer)
7953                            + " requires " + requiredInstructionSet + " whereas " + ps
7954                            + " requires " + instructionSet;
7955                    Slog.w(TAG, errorMessage);
7956                }
7957
7958                if (requiredInstructionSet == null) {
7959                    requiredInstructionSet = instructionSet;
7960                    requirer = ps;
7961                }
7962            }
7963        }
7964
7965        if (requiredInstructionSet != null) {
7966            String adjustedAbi;
7967            if (requirer != null) {
7968                // requirer != null implies that either scannedPackage was null or that scannedPackage
7969                // did not require an ABI, in which case we have to adjust scannedPackage to match
7970                // the ABI of the set (which is the same as requirer's ABI)
7971                adjustedAbi = requirer.primaryCpuAbiString;
7972                if (scannedPackage != null) {
7973                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7974                }
7975            } else {
7976                // requirer == null implies that we're updating all ABIs in the set to
7977                // match scannedPackage.
7978                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7979            }
7980
7981            for (PackageSetting ps : packagesForUser) {
7982                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7983                    if (ps.primaryCpuAbiString != null) {
7984                        continue;
7985                    }
7986
7987                    ps.primaryCpuAbiString = adjustedAbi;
7988                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7989                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7990                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7991                        mInstaller.rmdex(ps.codePathString,
7992                                getDexCodeInstructionSet(getPreferredInstructionSet()));
7993                    }
7994                }
7995            }
7996        }
7997    }
7998
7999    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8000        synchronized (mPackages) {
8001            mResolverReplaced = true;
8002            // Set up information for custom user intent resolution activity.
8003            mResolveActivity.applicationInfo = pkg.applicationInfo;
8004            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8005            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8006            mResolveActivity.processName = pkg.applicationInfo.packageName;
8007            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8008            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8009                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8010            mResolveActivity.theme = 0;
8011            mResolveActivity.exported = true;
8012            mResolveActivity.enabled = true;
8013            mResolveInfo.activityInfo = mResolveActivity;
8014            mResolveInfo.priority = 0;
8015            mResolveInfo.preferredOrder = 0;
8016            mResolveInfo.match = 0;
8017            mResolveComponentName = mCustomResolverComponentName;
8018            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8019                    mResolveComponentName);
8020        }
8021    }
8022
8023    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8024        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8025
8026        // Set up information for ephemeral installer activity
8027        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8028        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8029        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8030        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8031        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8032        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8033                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8034        mEphemeralInstallerActivity.theme = 0;
8035        mEphemeralInstallerActivity.exported = true;
8036        mEphemeralInstallerActivity.enabled = true;
8037        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8038        mEphemeralInstallerInfo.priority = 0;
8039        mEphemeralInstallerInfo.preferredOrder = 0;
8040        mEphemeralInstallerInfo.match = 0;
8041
8042        if (DEBUG_EPHEMERAL) {
8043            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8044        }
8045    }
8046
8047    private static String calculateBundledApkRoot(final String codePathString) {
8048        final File codePath = new File(codePathString);
8049        final File codeRoot;
8050        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8051            codeRoot = Environment.getRootDirectory();
8052        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8053            codeRoot = Environment.getOemDirectory();
8054        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8055            codeRoot = Environment.getVendorDirectory();
8056        } else {
8057            // Unrecognized code path; take its top real segment as the apk root:
8058            // e.g. /something/app/blah.apk => /something
8059            try {
8060                File f = codePath.getCanonicalFile();
8061                File parent = f.getParentFile();    // non-null because codePath is a file
8062                File tmp;
8063                while ((tmp = parent.getParentFile()) != null) {
8064                    f = parent;
8065                    parent = tmp;
8066                }
8067                codeRoot = f;
8068                Slog.w(TAG, "Unrecognized code path "
8069                        + codePath + " - using " + codeRoot);
8070            } catch (IOException e) {
8071                // Can't canonicalize the code path -- shenanigans?
8072                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8073                return Environment.getRootDirectory().getPath();
8074            }
8075        }
8076        return codeRoot.getPath();
8077    }
8078
8079    /**
8080     * Derive and set the location of native libraries for the given package,
8081     * which varies depending on where and how the package was installed.
8082     */
8083    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8084        final ApplicationInfo info = pkg.applicationInfo;
8085        final String codePath = pkg.codePath;
8086        final File codeFile = new File(codePath);
8087        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8088        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8089
8090        info.nativeLibraryRootDir = null;
8091        info.nativeLibraryRootRequiresIsa = false;
8092        info.nativeLibraryDir = null;
8093        info.secondaryNativeLibraryDir = null;
8094
8095        if (isApkFile(codeFile)) {
8096            // Monolithic install
8097            if (bundledApp) {
8098                // If "/system/lib64/apkname" exists, assume that is the per-package
8099                // native library directory to use; otherwise use "/system/lib/apkname".
8100                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8101                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8102                        getPrimaryInstructionSet(info));
8103
8104                // This is a bundled system app so choose the path based on the ABI.
8105                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8106                // is just the default path.
8107                final String apkName = deriveCodePathName(codePath);
8108                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8109                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8110                        apkName).getAbsolutePath();
8111
8112                if (info.secondaryCpuAbi != null) {
8113                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8114                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8115                            secondaryLibDir, apkName).getAbsolutePath();
8116                }
8117            } else if (asecApp) {
8118                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8119                        .getAbsolutePath();
8120            } else {
8121                final String apkName = deriveCodePathName(codePath);
8122                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8123                        .getAbsolutePath();
8124            }
8125
8126            info.nativeLibraryRootRequiresIsa = false;
8127            info.nativeLibraryDir = info.nativeLibraryRootDir;
8128        } else {
8129            // Cluster install
8130            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8131            info.nativeLibraryRootRequiresIsa = true;
8132
8133            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8134                    getPrimaryInstructionSet(info)).getAbsolutePath();
8135
8136            if (info.secondaryCpuAbi != null) {
8137                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8138                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8139            }
8140        }
8141    }
8142
8143    /**
8144     * Calculate the abis and roots for a bundled app. These can uniquely
8145     * be determined from the contents of the system partition, i.e whether
8146     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8147     * of this information, and instead assume that the system was built
8148     * sensibly.
8149     */
8150    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8151                                           PackageSetting pkgSetting) {
8152        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8153
8154        // If "/system/lib64/apkname" exists, assume that is the per-package
8155        // native library directory to use; otherwise use "/system/lib/apkname".
8156        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8157        setBundledAppAbi(pkg, apkRoot, apkName);
8158        // pkgSetting might be null during rescan following uninstall of updates
8159        // to a bundled app, so accommodate that possibility.  The settings in
8160        // that case will be established later from the parsed package.
8161        //
8162        // If the settings aren't null, sync them up with what we've just derived.
8163        // note that apkRoot isn't stored in the package settings.
8164        if (pkgSetting != null) {
8165            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8166            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8167        }
8168    }
8169
8170    /**
8171     * Deduces the ABI of a bundled app and sets the relevant fields on the
8172     * parsed pkg object.
8173     *
8174     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8175     *        under which system libraries are installed.
8176     * @param apkName the name of the installed package.
8177     */
8178    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8179        final File codeFile = new File(pkg.codePath);
8180
8181        final boolean has64BitLibs;
8182        final boolean has32BitLibs;
8183        if (isApkFile(codeFile)) {
8184            // Monolithic install
8185            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8186            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8187        } else {
8188            // Cluster install
8189            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8190            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8191                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8192                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8193                has64BitLibs = (new File(rootDir, isa)).exists();
8194            } else {
8195                has64BitLibs = false;
8196            }
8197            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8198                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8199                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8200                has32BitLibs = (new File(rootDir, isa)).exists();
8201            } else {
8202                has32BitLibs = false;
8203            }
8204        }
8205
8206        if (has64BitLibs && !has32BitLibs) {
8207            // The package has 64 bit libs, but not 32 bit libs. Its primary
8208            // ABI should be 64 bit. We can safely assume here that the bundled
8209            // native libraries correspond to the most preferred ABI in the list.
8210
8211            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8212            pkg.applicationInfo.secondaryCpuAbi = null;
8213        } else if (has32BitLibs && !has64BitLibs) {
8214            // The package has 32 bit libs but not 64 bit libs. Its primary
8215            // ABI should be 32 bit.
8216
8217            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8218            pkg.applicationInfo.secondaryCpuAbi = null;
8219        } else if (has32BitLibs && has64BitLibs) {
8220            // The application has both 64 and 32 bit bundled libraries. We check
8221            // here that the app declares multiArch support, and warn if it doesn't.
8222            //
8223            // We will be lenient here and record both ABIs. The primary will be the
8224            // ABI that's higher on the list, i.e, a device that's configured to prefer
8225            // 64 bit apps will see a 64 bit primary ABI,
8226
8227            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8228                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8229            }
8230
8231            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8232                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8233                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8234            } else {
8235                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8236                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8237            }
8238        } else {
8239            pkg.applicationInfo.primaryCpuAbi = null;
8240            pkg.applicationInfo.secondaryCpuAbi = null;
8241        }
8242    }
8243
8244    private void killApplication(String pkgName, int appId, String reason) {
8245        // Request the ActivityManager to kill the process(only for existing packages)
8246        // so that we do not end up in a confused state while the user is still using the older
8247        // version of the application while the new one gets installed.
8248        IActivityManager am = ActivityManagerNative.getDefault();
8249        if (am != null) {
8250            try {
8251                am.killApplicationWithAppId(pkgName, appId, reason);
8252            } catch (RemoteException e) {
8253            }
8254        }
8255    }
8256
8257    void removePackageLI(PackageSetting ps, boolean chatty) {
8258        if (DEBUG_INSTALL) {
8259            if (chatty)
8260                Log.d(TAG, "Removing package " + ps.name);
8261        }
8262
8263        // writer
8264        synchronized (mPackages) {
8265            mPackages.remove(ps.name);
8266            final PackageParser.Package pkg = ps.pkg;
8267            if (pkg != null) {
8268                cleanPackageDataStructuresLILPw(pkg, chatty);
8269            }
8270        }
8271    }
8272
8273    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8274        if (DEBUG_INSTALL) {
8275            if (chatty)
8276                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8277        }
8278
8279        // writer
8280        synchronized (mPackages) {
8281            mPackages.remove(pkg.applicationInfo.packageName);
8282            cleanPackageDataStructuresLILPw(pkg, chatty);
8283        }
8284    }
8285
8286    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8287        int N = pkg.providers.size();
8288        StringBuilder r = null;
8289        int i;
8290        for (i=0; i<N; i++) {
8291            PackageParser.Provider p = pkg.providers.get(i);
8292            mProviders.removeProvider(p);
8293            if (p.info.authority == null) {
8294
8295                /* There was another ContentProvider with this authority when
8296                 * this app was installed so this authority is null,
8297                 * Ignore it as we don't have to unregister the provider.
8298                 */
8299                continue;
8300            }
8301            String names[] = p.info.authority.split(";");
8302            for (int j = 0; j < names.length; j++) {
8303                if (mProvidersByAuthority.get(names[j]) == p) {
8304                    mProvidersByAuthority.remove(names[j]);
8305                    if (DEBUG_REMOVE) {
8306                        if (chatty)
8307                            Log.d(TAG, "Unregistered content provider: " + names[j]
8308                                    + ", className = " + p.info.name + ", isSyncable = "
8309                                    + p.info.isSyncable);
8310                    }
8311                }
8312            }
8313            if (DEBUG_REMOVE && chatty) {
8314                if (r == null) {
8315                    r = new StringBuilder(256);
8316                } else {
8317                    r.append(' ');
8318                }
8319                r.append(p.info.name);
8320            }
8321        }
8322        if (r != null) {
8323            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8324        }
8325
8326        N = pkg.services.size();
8327        r = null;
8328        for (i=0; i<N; i++) {
8329            PackageParser.Service s = pkg.services.get(i);
8330            mServices.removeService(s);
8331            if (chatty) {
8332                if (r == null) {
8333                    r = new StringBuilder(256);
8334                } else {
8335                    r.append(' ');
8336                }
8337                r.append(s.info.name);
8338            }
8339        }
8340        if (r != null) {
8341            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8342        }
8343
8344        N = pkg.receivers.size();
8345        r = null;
8346        for (i=0; i<N; i++) {
8347            PackageParser.Activity a = pkg.receivers.get(i);
8348            mReceivers.removeActivity(a, "receiver");
8349            if (DEBUG_REMOVE && chatty) {
8350                if (r == null) {
8351                    r = new StringBuilder(256);
8352                } else {
8353                    r.append(' ');
8354                }
8355                r.append(a.info.name);
8356            }
8357        }
8358        if (r != null) {
8359            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8360        }
8361
8362        N = pkg.activities.size();
8363        r = null;
8364        for (i=0; i<N; i++) {
8365            PackageParser.Activity a = pkg.activities.get(i);
8366            mActivities.removeActivity(a, "activity");
8367            if (DEBUG_REMOVE && chatty) {
8368                if (r == null) {
8369                    r = new StringBuilder(256);
8370                } else {
8371                    r.append(' ');
8372                }
8373                r.append(a.info.name);
8374            }
8375        }
8376        if (r != null) {
8377            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8378        }
8379
8380        N = pkg.permissions.size();
8381        r = null;
8382        for (i=0; i<N; i++) {
8383            PackageParser.Permission p = pkg.permissions.get(i);
8384            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8385            if (bp == null) {
8386                bp = mSettings.mPermissionTrees.get(p.info.name);
8387            }
8388            if (bp != null && bp.perm == p) {
8389                bp.perm = null;
8390                if (DEBUG_REMOVE && chatty) {
8391                    if (r == null) {
8392                        r = new StringBuilder(256);
8393                    } else {
8394                        r.append(' ');
8395                    }
8396                    r.append(p.info.name);
8397                }
8398            }
8399            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8400                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8401                if (appOpPerms != null) {
8402                    appOpPerms.remove(pkg.packageName);
8403                }
8404            }
8405        }
8406        if (r != null) {
8407            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8408        }
8409
8410        N = pkg.requestedPermissions.size();
8411        r = null;
8412        for (i=0; i<N; i++) {
8413            String perm = pkg.requestedPermissions.get(i);
8414            BasePermission bp = mSettings.mPermissions.get(perm);
8415            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8416                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8417                if (appOpPerms != null) {
8418                    appOpPerms.remove(pkg.packageName);
8419                    if (appOpPerms.isEmpty()) {
8420                        mAppOpPermissionPackages.remove(perm);
8421                    }
8422                }
8423            }
8424        }
8425        if (r != null) {
8426            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8427        }
8428
8429        N = pkg.instrumentation.size();
8430        r = null;
8431        for (i=0; i<N; i++) {
8432            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8433            mInstrumentation.remove(a.getComponentName());
8434            if (DEBUG_REMOVE && chatty) {
8435                if (r == null) {
8436                    r = new StringBuilder(256);
8437                } else {
8438                    r.append(' ');
8439                }
8440                r.append(a.info.name);
8441            }
8442        }
8443        if (r != null) {
8444            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8445        }
8446
8447        r = null;
8448        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8449            // Only system apps can hold shared libraries.
8450            if (pkg.libraryNames != null) {
8451                for (i=0; i<pkg.libraryNames.size(); i++) {
8452                    String name = pkg.libraryNames.get(i);
8453                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8454                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8455                        mSharedLibraries.remove(name);
8456                        if (DEBUG_REMOVE && chatty) {
8457                            if (r == null) {
8458                                r = new StringBuilder(256);
8459                            } else {
8460                                r.append(' ');
8461                            }
8462                            r.append(name);
8463                        }
8464                    }
8465                }
8466            }
8467        }
8468        if (r != null) {
8469            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8470        }
8471    }
8472
8473    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8474        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8475            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8476                return true;
8477            }
8478        }
8479        return false;
8480    }
8481
8482    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8483    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8484    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8485
8486    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8487            int flags) {
8488        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8489        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8490    }
8491
8492    private void updatePermissionsLPw(String changingPkg,
8493            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8494        // Make sure there are no dangling permission trees.
8495        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8496        while (it.hasNext()) {
8497            final BasePermission bp = it.next();
8498            if (bp.packageSetting == null) {
8499                // We may not yet have parsed the package, so just see if
8500                // we still know about its settings.
8501                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8502            }
8503            if (bp.packageSetting == null) {
8504                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8505                        + " from package " + bp.sourcePackage);
8506                it.remove();
8507            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8508                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8509                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8510                            + " from package " + bp.sourcePackage);
8511                    flags |= UPDATE_PERMISSIONS_ALL;
8512                    it.remove();
8513                }
8514            }
8515        }
8516
8517        // Make sure all dynamic permissions have been assigned to a package,
8518        // and make sure there are no dangling permissions.
8519        it = mSettings.mPermissions.values().iterator();
8520        while (it.hasNext()) {
8521            final BasePermission bp = it.next();
8522            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8523                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8524                        + bp.name + " pkg=" + bp.sourcePackage
8525                        + " info=" + bp.pendingInfo);
8526                if (bp.packageSetting == null && bp.pendingInfo != null) {
8527                    final BasePermission tree = findPermissionTreeLP(bp.name);
8528                    if (tree != null && tree.perm != null) {
8529                        bp.packageSetting = tree.packageSetting;
8530                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8531                                new PermissionInfo(bp.pendingInfo));
8532                        bp.perm.info.packageName = tree.perm.info.packageName;
8533                        bp.perm.info.name = bp.name;
8534                        bp.uid = tree.uid;
8535                    }
8536                }
8537            }
8538            if (bp.packageSetting == null) {
8539                // We may not yet have parsed the package, so just see if
8540                // we still know about its settings.
8541                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8542            }
8543            if (bp.packageSetting == null) {
8544                Slog.w(TAG, "Removing dangling permission: " + bp.name
8545                        + " from package " + bp.sourcePackage);
8546                it.remove();
8547            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8548                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8549                    Slog.i(TAG, "Removing old permission: " + bp.name
8550                            + " from package " + bp.sourcePackage);
8551                    flags |= UPDATE_PERMISSIONS_ALL;
8552                    it.remove();
8553                }
8554            }
8555        }
8556
8557        // Now update the permissions for all packages, in particular
8558        // replace the granted permissions of the system packages.
8559        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8560            for (PackageParser.Package pkg : mPackages.values()) {
8561                if (pkg != pkgInfo) {
8562                    // Only replace for packages on requested volume
8563                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8564                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8565                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8566                    grantPermissionsLPw(pkg, replace, changingPkg);
8567                }
8568            }
8569        }
8570
8571        if (pkgInfo != null) {
8572            // Only replace for packages on requested volume
8573            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8574            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8575                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8576            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8577        }
8578    }
8579
8580    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8581            String packageOfInterest) {
8582        // IMPORTANT: There are two types of permissions: install and runtime.
8583        // Install time permissions are granted when the app is installed to
8584        // all device users and users added in the future. Runtime permissions
8585        // are granted at runtime explicitly to specific users. Normal and signature
8586        // protected permissions are install time permissions. Dangerous permissions
8587        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8588        // otherwise they are runtime permissions. This function does not manage
8589        // runtime permissions except for the case an app targeting Lollipop MR1
8590        // being upgraded to target a newer SDK, in which case dangerous permissions
8591        // are transformed from install time to runtime ones.
8592
8593        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8594        if (ps == null) {
8595            return;
8596        }
8597
8598        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8599
8600        PermissionsState permissionsState = ps.getPermissionsState();
8601        PermissionsState origPermissions = permissionsState;
8602
8603        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8604
8605        boolean runtimePermissionsRevoked = false;
8606        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8607
8608        boolean changedInstallPermission = false;
8609
8610        if (replace) {
8611            ps.installPermissionsFixed = false;
8612            if (!ps.isSharedUser()) {
8613                origPermissions = new PermissionsState(permissionsState);
8614                permissionsState.reset();
8615            } else {
8616                // We need to know only about runtime permission changes since the
8617                // calling code always writes the install permissions state but
8618                // the runtime ones are written only if changed. The only cases of
8619                // changed runtime permissions here are promotion of an install to
8620                // runtime and revocation of a runtime from a shared user.
8621                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8622                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8623                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8624                    runtimePermissionsRevoked = true;
8625                }
8626            }
8627        }
8628
8629        permissionsState.setGlobalGids(mGlobalGids);
8630
8631        final int N = pkg.requestedPermissions.size();
8632        for (int i=0; i<N; i++) {
8633            final String name = pkg.requestedPermissions.get(i);
8634            final BasePermission bp = mSettings.mPermissions.get(name);
8635
8636            if (DEBUG_INSTALL) {
8637                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8638            }
8639
8640            if (bp == null || bp.packageSetting == null) {
8641                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8642                    Slog.w(TAG, "Unknown permission " + name
8643                            + " in package " + pkg.packageName);
8644                }
8645                continue;
8646            }
8647
8648            final String perm = bp.name;
8649            boolean allowedSig = false;
8650            int grant = GRANT_DENIED;
8651
8652            // Keep track of app op permissions.
8653            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8654                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8655                if (pkgs == null) {
8656                    pkgs = new ArraySet<>();
8657                    mAppOpPermissionPackages.put(bp.name, pkgs);
8658                }
8659                pkgs.add(pkg.packageName);
8660            }
8661
8662            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8663            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8664                    >= Build.VERSION_CODES.M;
8665            switch (level) {
8666                case PermissionInfo.PROTECTION_NORMAL: {
8667                    // For all apps normal permissions are install time ones.
8668                    grant = GRANT_INSTALL;
8669                } break;
8670
8671                case PermissionInfo.PROTECTION_DANGEROUS: {
8672                    // If a permission review is required for legacy apps we represent
8673                    // their permissions as always granted runtime ones since we need
8674                    // to keep the review required permission flag per user while an
8675                    // install permission's state is shared across all users.
8676                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8677                        // For legacy apps dangerous permissions are install time ones.
8678                        grant = GRANT_INSTALL;
8679                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8680                        // For legacy apps that became modern, install becomes runtime.
8681                        grant = GRANT_UPGRADE;
8682                    } else if (mPromoteSystemApps
8683                            && isSystemApp(ps)
8684                            && mExistingSystemPackages.contains(ps.name)) {
8685                        // For legacy system apps, install becomes runtime.
8686                        // We cannot check hasInstallPermission() for system apps since those
8687                        // permissions were granted implicitly and not persisted pre-M.
8688                        grant = GRANT_UPGRADE;
8689                    } else {
8690                        // For modern apps keep runtime permissions unchanged.
8691                        grant = GRANT_RUNTIME;
8692                    }
8693                } break;
8694
8695                case PermissionInfo.PROTECTION_SIGNATURE: {
8696                    // For all apps signature permissions are install time ones.
8697                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8698                    if (allowedSig) {
8699                        grant = GRANT_INSTALL;
8700                    }
8701                } break;
8702            }
8703
8704            if (DEBUG_INSTALL) {
8705                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8706            }
8707
8708            if (grant != GRANT_DENIED) {
8709                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8710                    // If this is an existing, non-system package, then
8711                    // we can't add any new permissions to it.
8712                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8713                        // Except...  if this is a permission that was added
8714                        // to the platform (note: need to only do this when
8715                        // updating the platform).
8716                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8717                            grant = GRANT_DENIED;
8718                        }
8719                    }
8720                }
8721
8722                switch (grant) {
8723                    case GRANT_INSTALL: {
8724                        // Revoke this as runtime permission to handle the case of
8725                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8726                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8727                            if (origPermissions.getRuntimePermissionState(
8728                                    bp.name, userId) != null) {
8729                                // Revoke the runtime permission and clear the flags.
8730                                origPermissions.revokeRuntimePermission(bp, userId);
8731                                origPermissions.updatePermissionFlags(bp, userId,
8732                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8733                                // If we revoked a permission permission, we have to write.
8734                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8735                                        changedRuntimePermissionUserIds, userId);
8736                            }
8737                        }
8738                        // Grant an install permission.
8739                        if (permissionsState.grantInstallPermission(bp) !=
8740                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8741                            changedInstallPermission = true;
8742                        }
8743                    } break;
8744
8745                    case GRANT_RUNTIME: {
8746                        // Grant previously granted runtime permissions.
8747                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8748                            PermissionState permissionState = origPermissions
8749                                    .getRuntimePermissionState(bp.name, userId);
8750                            int flags = permissionState != null
8751                                    ? permissionState.getFlags() : 0;
8752                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8753                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8754                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8755                                    // If we cannot put the permission as it was, we have to write.
8756                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8757                                            changedRuntimePermissionUserIds, userId);
8758                                }
8759                                // If the app supports runtime permissions no need for a review.
8760                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8761                                        && appSupportsRuntimePermissions
8762                                        && (flags & PackageManager
8763                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8764                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8765                                    // Since we changed the flags, we have to write.
8766                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8767                                            changedRuntimePermissionUserIds, userId);
8768                                }
8769                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8770                                    && !appSupportsRuntimePermissions) {
8771                                // For legacy apps that need a permission review, every new
8772                                // runtime permission is granted but it is pending a review.
8773                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8774                                    permissionsState.grantRuntimePermission(bp, userId);
8775                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8776                                    // We changed the permission and flags, hence have to write.
8777                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8778                                            changedRuntimePermissionUserIds, userId);
8779                                }
8780                            }
8781                            // Propagate the permission flags.
8782                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8783                        }
8784                    } break;
8785
8786                    case GRANT_UPGRADE: {
8787                        // Grant runtime permissions for a previously held install permission.
8788                        PermissionState permissionState = origPermissions
8789                                .getInstallPermissionState(bp.name);
8790                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8791
8792                        if (origPermissions.revokeInstallPermission(bp)
8793                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8794                            // We will be transferring the permission flags, so clear them.
8795                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8796                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8797                            changedInstallPermission = true;
8798                        }
8799
8800                        // If the permission is not to be promoted to runtime we ignore it and
8801                        // also its other flags as they are not applicable to install permissions.
8802                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8803                            for (int userId : currentUserIds) {
8804                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8805                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8806                                    // Transfer the permission flags.
8807                                    permissionsState.updatePermissionFlags(bp, userId,
8808                                            flags, flags);
8809                                    // If we granted the permission, we have to write.
8810                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8811                                            changedRuntimePermissionUserIds, userId);
8812                                }
8813                            }
8814                        }
8815                    } break;
8816
8817                    default: {
8818                        if (packageOfInterest == null
8819                                || packageOfInterest.equals(pkg.packageName)) {
8820                            Slog.w(TAG, "Not granting permission " + perm
8821                                    + " to package " + pkg.packageName
8822                                    + " because it was previously installed without");
8823                        }
8824                    } break;
8825                }
8826            } else {
8827                if (permissionsState.revokeInstallPermission(bp) !=
8828                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8829                    // Also drop the permission flags.
8830                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8831                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8832                    changedInstallPermission = true;
8833                    Slog.i(TAG, "Un-granting permission " + perm
8834                            + " from package " + pkg.packageName
8835                            + " (protectionLevel=" + bp.protectionLevel
8836                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8837                            + ")");
8838                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8839                    // Don't print warning for app op permissions, since it is fine for them
8840                    // not to be granted, there is a UI for the user to decide.
8841                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8842                        Slog.w(TAG, "Not granting permission " + perm
8843                                + " to package " + pkg.packageName
8844                                + " (protectionLevel=" + bp.protectionLevel
8845                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8846                                + ")");
8847                    }
8848                }
8849            }
8850        }
8851
8852        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8853                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8854            // This is the first that we have heard about this package, so the
8855            // permissions we have now selected are fixed until explicitly
8856            // changed.
8857            ps.installPermissionsFixed = true;
8858        }
8859
8860        // Persist the runtime permissions state for users with changes. If permissions
8861        // were revoked because no app in the shared user declares them we have to
8862        // write synchronously to avoid losing runtime permissions state.
8863        for (int userId : changedRuntimePermissionUserIds) {
8864            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8865        }
8866
8867        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8868    }
8869
8870    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8871        boolean allowed = false;
8872        final int NP = PackageParser.NEW_PERMISSIONS.length;
8873        for (int ip=0; ip<NP; ip++) {
8874            final PackageParser.NewPermissionInfo npi
8875                    = PackageParser.NEW_PERMISSIONS[ip];
8876            if (npi.name.equals(perm)
8877                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8878                allowed = true;
8879                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8880                        + pkg.packageName);
8881                break;
8882            }
8883        }
8884        return allowed;
8885    }
8886
8887    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8888            BasePermission bp, PermissionsState origPermissions) {
8889        boolean allowed;
8890        allowed = (compareSignatures(
8891                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8892                        == PackageManager.SIGNATURE_MATCH)
8893                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8894                        == PackageManager.SIGNATURE_MATCH);
8895        if (!allowed && (bp.protectionLevel
8896                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8897            if (isSystemApp(pkg)) {
8898                // For updated system applications, a system permission
8899                // is granted only if it had been defined by the original application.
8900                if (pkg.isUpdatedSystemApp()) {
8901                    final PackageSetting sysPs = mSettings
8902                            .getDisabledSystemPkgLPr(pkg.packageName);
8903                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8904                        // If the original was granted this permission, we take
8905                        // that grant decision as read and propagate it to the
8906                        // update.
8907                        if (sysPs.isPrivileged()) {
8908                            allowed = true;
8909                        }
8910                    } else {
8911                        // The system apk may have been updated with an older
8912                        // version of the one on the data partition, but which
8913                        // granted a new system permission that it didn't have
8914                        // before.  In this case we do want to allow the app to
8915                        // now get the new permission if the ancestral apk is
8916                        // privileged to get it.
8917                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8918                            for (int j=0;
8919                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8920                                if (perm.equals(
8921                                        sysPs.pkg.requestedPermissions.get(j))) {
8922                                    allowed = true;
8923                                    break;
8924                                }
8925                            }
8926                        }
8927                    }
8928                } else {
8929                    allowed = isPrivilegedApp(pkg);
8930                }
8931            }
8932        }
8933        if (!allowed) {
8934            if (!allowed && (bp.protectionLevel
8935                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8936                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8937                // If this was a previously normal/dangerous permission that got moved
8938                // to a system permission as part of the runtime permission redesign, then
8939                // we still want to blindly grant it to old apps.
8940                allowed = true;
8941            }
8942            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8943                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8944                // If this permission is to be granted to the system installer and
8945                // this app is an installer, then it gets the permission.
8946                allowed = true;
8947            }
8948            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8949                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8950                // If this permission is to be granted to the system verifier and
8951                // this app is a verifier, then it gets the permission.
8952                allowed = true;
8953            }
8954            if (!allowed && (bp.protectionLevel
8955                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8956                    && isSystemApp(pkg)) {
8957                // Any pre-installed system app is allowed to get this permission.
8958                allowed = true;
8959            }
8960            if (!allowed && (bp.protectionLevel
8961                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8962                // For development permissions, a development permission
8963                // is granted only if it was already granted.
8964                allowed = origPermissions.hasInstallPermission(perm);
8965            }
8966        }
8967        return allowed;
8968    }
8969
8970    final class ActivityIntentResolver
8971            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8972        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8973                boolean defaultOnly, int userId) {
8974            if (!sUserManager.exists(userId)) return null;
8975            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8976            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8977        }
8978
8979        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8980                int userId) {
8981            if (!sUserManager.exists(userId)) return null;
8982            mFlags = flags;
8983            return super.queryIntent(intent, resolvedType,
8984                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8985        }
8986
8987        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8988                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8989            if (!sUserManager.exists(userId)) return null;
8990            if (packageActivities == null) {
8991                return null;
8992            }
8993            mFlags = flags;
8994            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8995            final int N = packageActivities.size();
8996            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8997                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8998
8999            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9000            for (int i = 0; i < N; ++i) {
9001                intentFilters = packageActivities.get(i).intents;
9002                if (intentFilters != null && intentFilters.size() > 0) {
9003                    PackageParser.ActivityIntentInfo[] array =
9004                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9005                    intentFilters.toArray(array);
9006                    listCut.add(array);
9007                }
9008            }
9009            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9010        }
9011
9012        public final void addActivity(PackageParser.Activity a, String type) {
9013            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9014            mActivities.put(a.getComponentName(), a);
9015            if (DEBUG_SHOW_INFO)
9016                Log.v(
9017                TAG, "  " + type + " " +
9018                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9019            if (DEBUG_SHOW_INFO)
9020                Log.v(TAG, "    Class=" + a.info.name);
9021            final int NI = a.intents.size();
9022            for (int j=0; j<NI; j++) {
9023                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9024                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9025                    intent.setPriority(0);
9026                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9027                            + a.className + " with priority > 0, forcing to 0");
9028                }
9029                if (DEBUG_SHOW_INFO) {
9030                    Log.v(TAG, "    IntentFilter:");
9031                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9032                }
9033                if (!intent.debugCheck()) {
9034                    Log.w(TAG, "==> For Activity " + a.info.name);
9035                }
9036                addFilter(intent);
9037            }
9038        }
9039
9040        public final void removeActivity(PackageParser.Activity a, String type) {
9041            mActivities.remove(a.getComponentName());
9042            if (DEBUG_SHOW_INFO) {
9043                Log.v(TAG, "  " + type + " "
9044                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9045                                : a.info.name) + ":");
9046                Log.v(TAG, "    Class=" + a.info.name);
9047            }
9048            final int NI = a.intents.size();
9049            for (int j=0; j<NI; j++) {
9050                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9051                if (DEBUG_SHOW_INFO) {
9052                    Log.v(TAG, "    IntentFilter:");
9053                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9054                }
9055                removeFilter(intent);
9056            }
9057        }
9058
9059        @Override
9060        protected boolean allowFilterResult(
9061                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9062            ActivityInfo filterAi = filter.activity.info;
9063            for (int i=dest.size()-1; i>=0; i--) {
9064                ActivityInfo destAi = dest.get(i).activityInfo;
9065                if (destAi.name == filterAi.name
9066                        && destAi.packageName == filterAi.packageName) {
9067                    return false;
9068                }
9069            }
9070            return true;
9071        }
9072
9073        @Override
9074        protected ActivityIntentInfo[] newArray(int size) {
9075            return new ActivityIntentInfo[size];
9076        }
9077
9078        @Override
9079        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9080            if (!sUserManager.exists(userId)) return true;
9081            PackageParser.Package p = filter.activity.owner;
9082            if (p != null) {
9083                PackageSetting ps = (PackageSetting)p.mExtras;
9084                if (ps != null) {
9085                    // System apps are never considered stopped for purposes of
9086                    // filtering, because there may be no way for the user to
9087                    // actually re-launch them.
9088                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9089                            && ps.getStopped(userId);
9090                }
9091            }
9092            return false;
9093        }
9094
9095        @Override
9096        protected boolean isPackageForFilter(String packageName,
9097                PackageParser.ActivityIntentInfo info) {
9098            return packageName.equals(info.activity.owner.packageName);
9099        }
9100
9101        @Override
9102        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9103                int match, int userId) {
9104            if (!sUserManager.exists(userId)) return null;
9105            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9106                return null;
9107            }
9108            final PackageParser.Activity activity = info.activity;
9109            if (mSafeMode && (activity.info.applicationInfo.flags
9110                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9111                return null;
9112            }
9113            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9114            if (ps == null) {
9115                return null;
9116            }
9117            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9118                    ps.readUserState(userId), userId);
9119            if (ai == null) {
9120                return null;
9121            }
9122            final ResolveInfo res = new ResolveInfo();
9123            res.activityInfo = ai;
9124            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9125                res.filter = info;
9126            }
9127            if (info != null) {
9128                res.handleAllWebDataURI = info.handleAllWebDataURI();
9129            }
9130            res.priority = info.getPriority();
9131            res.preferredOrder = activity.owner.mPreferredOrder;
9132            //System.out.println("Result: " + res.activityInfo.className +
9133            //                   " = " + res.priority);
9134            res.match = match;
9135            res.isDefault = info.hasDefault;
9136            res.labelRes = info.labelRes;
9137            res.nonLocalizedLabel = info.nonLocalizedLabel;
9138            if (userNeedsBadging(userId)) {
9139                res.noResourceId = true;
9140            } else {
9141                res.icon = info.icon;
9142            }
9143            res.iconResourceId = info.icon;
9144            res.system = res.activityInfo.applicationInfo.isSystemApp();
9145            return res;
9146        }
9147
9148        @Override
9149        protected void sortResults(List<ResolveInfo> results) {
9150            Collections.sort(results, mResolvePrioritySorter);
9151        }
9152
9153        @Override
9154        protected void dumpFilter(PrintWriter out, String prefix,
9155                PackageParser.ActivityIntentInfo filter) {
9156            out.print(prefix); out.print(
9157                    Integer.toHexString(System.identityHashCode(filter.activity)));
9158                    out.print(' ');
9159                    filter.activity.printComponentShortName(out);
9160                    out.print(" filter ");
9161                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9162        }
9163
9164        @Override
9165        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9166            return filter.activity;
9167        }
9168
9169        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9170            PackageParser.Activity activity = (PackageParser.Activity)label;
9171            out.print(prefix); out.print(
9172                    Integer.toHexString(System.identityHashCode(activity)));
9173                    out.print(' ');
9174                    activity.printComponentShortName(out);
9175            if (count > 1) {
9176                out.print(" ("); out.print(count); out.print(" filters)");
9177            }
9178            out.println();
9179        }
9180
9181//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9182//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9183//            final List<ResolveInfo> retList = Lists.newArrayList();
9184//            while (i.hasNext()) {
9185//                final ResolveInfo resolveInfo = i.next();
9186//                if (isEnabledLP(resolveInfo.activityInfo)) {
9187//                    retList.add(resolveInfo);
9188//                }
9189//            }
9190//            return retList;
9191//        }
9192
9193        // Keys are String (activity class name), values are Activity.
9194        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9195                = new ArrayMap<ComponentName, PackageParser.Activity>();
9196        private int mFlags;
9197    }
9198
9199    private final class ServiceIntentResolver
9200            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9201        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9202                boolean defaultOnly, int userId) {
9203            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9204            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9205        }
9206
9207        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9208                int userId) {
9209            if (!sUserManager.exists(userId)) return null;
9210            mFlags = flags;
9211            return super.queryIntent(intent, resolvedType,
9212                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9213        }
9214
9215        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9216                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9217            if (!sUserManager.exists(userId)) return null;
9218            if (packageServices == null) {
9219                return null;
9220            }
9221            mFlags = flags;
9222            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9223            final int N = packageServices.size();
9224            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9225                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9226
9227            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9228            for (int i = 0; i < N; ++i) {
9229                intentFilters = packageServices.get(i).intents;
9230                if (intentFilters != null && intentFilters.size() > 0) {
9231                    PackageParser.ServiceIntentInfo[] array =
9232                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9233                    intentFilters.toArray(array);
9234                    listCut.add(array);
9235                }
9236            }
9237            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9238        }
9239
9240        public final void addService(PackageParser.Service s) {
9241            mServices.put(s.getComponentName(), s);
9242            if (DEBUG_SHOW_INFO) {
9243                Log.v(TAG, "  "
9244                        + (s.info.nonLocalizedLabel != null
9245                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9246                Log.v(TAG, "    Class=" + s.info.name);
9247            }
9248            final int NI = s.intents.size();
9249            int j;
9250            for (j=0; j<NI; j++) {
9251                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9252                if (DEBUG_SHOW_INFO) {
9253                    Log.v(TAG, "    IntentFilter:");
9254                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9255                }
9256                if (!intent.debugCheck()) {
9257                    Log.w(TAG, "==> For Service " + s.info.name);
9258                }
9259                addFilter(intent);
9260            }
9261        }
9262
9263        public final void removeService(PackageParser.Service s) {
9264            mServices.remove(s.getComponentName());
9265            if (DEBUG_SHOW_INFO) {
9266                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9267                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9268                Log.v(TAG, "    Class=" + s.info.name);
9269            }
9270            final int NI = s.intents.size();
9271            int j;
9272            for (j=0; j<NI; j++) {
9273                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9274                if (DEBUG_SHOW_INFO) {
9275                    Log.v(TAG, "    IntentFilter:");
9276                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9277                }
9278                removeFilter(intent);
9279            }
9280        }
9281
9282        @Override
9283        protected boolean allowFilterResult(
9284                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9285            ServiceInfo filterSi = filter.service.info;
9286            for (int i=dest.size()-1; i>=0; i--) {
9287                ServiceInfo destAi = dest.get(i).serviceInfo;
9288                if (destAi.name == filterSi.name
9289                        && destAi.packageName == filterSi.packageName) {
9290                    return false;
9291                }
9292            }
9293            return true;
9294        }
9295
9296        @Override
9297        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9298            return new PackageParser.ServiceIntentInfo[size];
9299        }
9300
9301        @Override
9302        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9303            if (!sUserManager.exists(userId)) return true;
9304            PackageParser.Package p = filter.service.owner;
9305            if (p != null) {
9306                PackageSetting ps = (PackageSetting)p.mExtras;
9307                if (ps != null) {
9308                    // System apps are never considered stopped for purposes of
9309                    // filtering, because there may be no way for the user to
9310                    // actually re-launch them.
9311                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9312                            && ps.getStopped(userId);
9313                }
9314            }
9315            return false;
9316        }
9317
9318        @Override
9319        protected boolean isPackageForFilter(String packageName,
9320                PackageParser.ServiceIntentInfo info) {
9321            return packageName.equals(info.service.owner.packageName);
9322        }
9323
9324        @Override
9325        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9326                int match, int userId) {
9327            if (!sUserManager.exists(userId)) return null;
9328            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9329            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9330                return null;
9331            }
9332            final PackageParser.Service service = info.service;
9333            if (mSafeMode && (service.info.applicationInfo.flags
9334                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9335                return null;
9336            }
9337            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9338            if (ps == null) {
9339                return null;
9340            }
9341            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9342                    ps.readUserState(userId), userId);
9343            if (si == null) {
9344                return null;
9345            }
9346            final ResolveInfo res = new ResolveInfo();
9347            res.serviceInfo = si;
9348            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9349                res.filter = filter;
9350            }
9351            res.priority = info.getPriority();
9352            res.preferredOrder = service.owner.mPreferredOrder;
9353            res.match = match;
9354            res.isDefault = info.hasDefault;
9355            res.labelRes = info.labelRes;
9356            res.nonLocalizedLabel = info.nonLocalizedLabel;
9357            res.icon = info.icon;
9358            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9359            return res;
9360        }
9361
9362        @Override
9363        protected void sortResults(List<ResolveInfo> results) {
9364            Collections.sort(results, mResolvePrioritySorter);
9365        }
9366
9367        @Override
9368        protected void dumpFilter(PrintWriter out, String prefix,
9369                PackageParser.ServiceIntentInfo filter) {
9370            out.print(prefix); out.print(
9371                    Integer.toHexString(System.identityHashCode(filter.service)));
9372                    out.print(' ');
9373                    filter.service.printComponentShortName(out);
9374                    out.print(" filter ");
9375                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9376        }
9377
9378        @Override
9379        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9380            return filter.service;
9381        }
9382
9383        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9384            PackageParser.Service service = (PackageParser.Service)label;
9385            out.print(prefix); out.print(
9386                    Integer.toHexString(System.identityHashCode(service)));
9387                    out.print(' ');
9388                    service.printComponentShortName(out);
9389            if (count > 1) {
9390                out.print(" ("); out.print(count); out.print(" filters)");
9391            }
9392            out.println();
9393        }
9394
9395//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9396//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9397//            final List<ResolveInfo> retList = Lists.newArrayList();
9398//            while (i.hasNext()) {
9399//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9400//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9401//                    retList.add(resolveInfo);
9402//                }
9403//            }
9404//            return retList;
9405//        }
9406
9407        // Keys are String (activity class name), values are Activity.
9408        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9409                = new ArrayMap<ComponentName, PackageParser.Service>();
9410        private int mFlags;
9411    };
9412
9413    private final class ProviderIntentResolver
9414            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9415        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9416                boolean defaultOnly, int userId) {
9417            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9418            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9419        }
9420
9421        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9422                int userId) {
9423            if (!sUserManager.exists(userId))
9424                return null;
9425            mFlags = flags;
9426            return super.queryIntent(intent, resolvedType,
9427                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9428        }
9429
9430        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9431                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9432            if (!sUserManager.exists(userId))
9433                return null;
9434            if (packageProviders == null) {
9435                return null;
9436            }
9437            mFlags = flags;
9438            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9439            final int N = packageProviders.size();
9440            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9441                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9442
9443            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9444            for (int i = 0; i < N; ++i) {
9445                intentFilters = packageProviders.get(i).intents;
9446                if (intentFilters != null && intentFilters.size() > 0) {
9447                    PackageParser.ProviderIntentInfo[] array =
9448                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9449                    intentFilters.toArray(array);
9450                    listCut.add(array);
9451                }
9452            }
9453            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9454        }
9455
9456        public final void addProvider(PackageParser.Provider p) {
9457            if (mProviders.containsKey(p.getComponentName())) {
9458                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9459                return;
9460            }
9461
9462            mProviders.put(p.getComponentName(), p);
9463            if (DEBUG_SHOW_INFO) {
9464                Log.v(TAG, "  "
9465                        + (p.info.nonLocalizedLabel != null
9466                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9467                Log.v(TAG, "    Class=" + p.info.name);
9468            }
9469            final int NI = p.intents.size();
9470            int j;
9471            for (j = 0; j < NI; j++) {
9472                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9473                if (DEBUG_SHOW_INFO) {
9474                    Log.v(TAG, "    IntentFilter:");
9475                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9476                }
9477                if (!intent.debugCheck()) {
9478                    Log.w(TAG, "==> For Provider " + p.info.name);
9479                }
9480                addFilter(intent);
9481            }
9482        }
9483
9484        public final void removeProvider(PackageParser.Provider p) {
9485            mProviders.remove(p.getComponentName());
9486            if (DEBUG_SHOW_INFO) {
9487                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9488                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9489                Log.v(TAG, "    Class=" + p.info.name);
9490            }
9491            final int NI = p.intents.size();
9492            int j;
9493            for (j = 0; j < NI; j++) {
9494                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9495                if (DEBUG_SHOW_INFO) {
9496                    Log.v(TAG, "    IntentFilter:");
9497                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9498                }
9499                removeFilter(intent);
9500            }
9501        }
9502
9503        @Override
9504        protected boolean allowFilterResult(
9505                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9506            ProviderInfo filterPi = filter.provider.info;
9507            for (int i = dest.size() - 1; i >= 0; i--) {
9508                ProviderInfo destPi = dest.get(i).providerInfo;
9509                if (destPi.name == filterPi.name
9510                        && destPi.packageName == filterPi.packageName) {
9511                    return false;
9512                }
9513            }
9514            return true;
9515        }
9516
9517        @Override
9518        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9519            return new PackageParser.ProviderIntentInfo[size];
9520        }
9521
9522        @Override
9523        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9524            if (!sUserManager.exists(userId))
9525                return true;
9526            PackageParser.Package p = filter.provider.owner;
9527            if (p != null) {
9528                PackageSetting ps = (PackageSetting) p.mExtras;
9529                if (ps != null) {
9530                    // System apps are never considered stopped for purposes of
9531                    // filtering, because there may be no way for the user to
9532                    // actually re-launch them.
9533                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9534                            && ps.getStopped(userId);
9535                }
9536            }
9537            return false;
9538        }
9539
9540        @Override
9541        protected boolean isPackageForFilter(String packageName,
9542                PackageParser.ProviderIntentInfo info) {
9543            return packageName.equals(info.provider.owner.packageName);
9544        }
9545
9546        @Override
9547        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9548                int match, int userId) {
9549            if (!sUserManager.exists(userId))
9550                return null;
9551            final PackageParser.ProviderIntentInfo info = filter;
9552            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9553                return null;
9554            }
9555            final PackageParser.Provider provider = info.provider;
9556            if (mSafeMode && (provider.info.applicationInfo.flags
9557                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9558                return null;
9559            }
9560            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9561            if (ps == null) {
9562                return null;
9563            }
9564            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9565                    ps.readUserState(userId), userId);
9566            if (pi == null) {
9567                return null;
9568            }
9569            final ResolveInfo res = new ResolveInfo();
9570            res.providerInfo = pi;
9571            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9572                res.filter = filter;
9573            }
9574            res.priority = info.getPriority();
9575            res.preferredOrder = provider.owner.mPreferredOrder;
9576            res.match = match;
9577            res.isDefault = info.hasDefault;
9578            res.labelRes = info.labelRes;
9579            res.nonLocalizedLabel = info.nonLocalizedLabel;
9580            res.icon = info.icon;
9581            res.system = res.providerInfo.applicationInfo.isSystemApp();
9582            return res;
9583        }
9584
9585        @Override
9586        protected void sortResults(List<ResolveInfo> results) {
9587            Collections.sort(results, mResolvePrioritySorter);
9588        }
9589
9590        @Override
9591        protected void dumpFilter(PrintWriter out, String prefix,
9592                PackageParser.ProviderIntentInfo filter) {
9593            out.print(prefix);
9594            out.print(
9595                    Integer.toHexString(System.identityHashCode(filter.provider)));
9596            out.print(' ');
9597            filter.provider.printComponentShortName(out);
9598            out.print(" filter ");
9599            out.println(Integer.toHexString(System.identityHashCode(filter)));
9600        }
9601
9602        @Override
9603        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9604            return filter.provider;
9605        }
9606
9607        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9608            PackageParser.Provider provider = (PackageParser.Provider)label;
9609            out.print(prefix); out.print(
9610                    Integer.toHexString(System.identityHashCode(provider)));
9611                    out.print(' ');
9612                    provider.printComponentShortName(out);
9613            if (count > 1) {
9614                out.print(" ("); out.print(count); out.print(" filters)");
9615            }
9616            out.println();
9617        }
9618
9619        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9620                = new ArrayMap<ComponentName, PackageParser.Provider>();
9621        private int mFlags;
9622    }
9623
9624    private static final class EphemeralIntentResolver
9625            extends IntentResolver<IntentFilter, ResolveInfo> {
9626        @Override
9627        protected IntentFilter[] newArray(int size) {
9628            return new IntentFilter[size];
9629        }
9630
9631        @Override
9632        protected boolean isPackageForFilter(String packageName, IntentFilter info) {
9633            return true;
9634        }
9635
9636        @Override
9637        protected ResolveInfo newResult(IntentFilter info, int match, int userId) {
9638            if (!sUserManager.exists(userId)) return null;
9639            final ResolveInfo res = new ResolveInfo();
9640            res.filter = info;
9641            return res;
9642        }
9643    }
9644
9645    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9646            new Comparator<ResolveInfo>() {
9647        public int compare(ResolveInfo r1, ResolveInfo r2) {
9648            int v1 = r1.priority;
9649            int v2 = r2.priority;
9650            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9651            if (v1 != v2) {
9652                return (v1 > v2) ? -1 : 1;
9653            }
9654            v1 = r1.preferredOrder;
9655            v2 = r2.preferredOrder;
9656            if (v1 != v2) {
9657                return (v1 > v2) ? -1 : 1;
9658            }
9659            if (r1.isDefault != r2.isDefault) {
9660                return r1.isDefault ? -1 : 1;
9661            }
9662            v1 = r1.match;
9663            v2 = r2.match;
9664            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9665            if (v1 != v2) {
9666                return (v1 > v2) ? -1 : 1;
9667            }
9668            if (r1.system != r2.system) {
9669                return r1.system ? -1 : 1;
9670            }
9671            return 0;
9672        }
9673    };
9674
9675    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9676            new Comparator<ProviderInfo>() {
9677        public int compare(ProviderInfo p1, ProviderInfo p2) {
9678            final int v1 = p1.initOrder;
9679            final int v2 = p2.initOrder;
9680            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9681        }
9682    };
9683
9684    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9685            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9686            final int[] userIds) {
9687        mHandler.post(new Runnable() {
9688            @Override
9689            public void run() {
9690                try {
9691                    final IActivityManager am = ActivityManagerNative.getDefault();
9692                    if (am == null) return;
9693                    final int[] resolvedUserIds;
9694                    if (userIds == null) {
9695                        resolvedUserIds = am.getRunningUserIds();
9696                    } else {
9697                        resolvedUserIds = userIds;
9698                    }
9699                    for (int id : resolvedUserIds) {
9700                        final Intent intent = new Intent(action,
9701                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9702                        if (extras != null) {
9703                            intent.putExtras(extras);
9704                        }
9705                        if (targetPkg != null) {
9706                            intent.setPackage(targetPkg);
9707                        }
9708                        // Modify the UID when posting to other users
9709                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9710                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9711                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9712                            intent.putExtra(Intent.EXTRA_UID, uid);
9713                        }
9714                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9715                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9716                        if (DEBUG_BROADCASTS) {
9717                            RuntimeException here = new RuntimeException("here");
9718                            here.fillInStackTrace();
9719                            Slog.d(TAG, "Sending to user " + id + ": "
9720                                    + intent.toShortString(false, true, false, false)
9721                                    + " " + intent.getExtras(), here);
9722                        }
9723                        am.broadcastIntent(null, intent, null, finishedReceiver,
9724                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9725                                null, finishedReceiver != null, false, id);
9726                    }
9727                } catch (RemoteException ex) {
9728                }
9729            }
9730        });
9731    }
9732
9733    /**
9734     * Check if the external storage media is available. This is true if there
9735     * is a mounted external storage medium or if the external storage is
9736     * emulated.
9737     */
9738    private boolean isExternalMediaAvailable() {
9739        return mMediaMounted || Environment.isExternalStorageEmulated();
9740    }
9741
9742    @Override
9743    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9744        // writer
9745        synchronized (mPackages) {
9746            if (!isExternalMediaAvailable()) {
9747                // If the external storage is no longer mounted at this point,
9748                // the caller may not have been able to delete all of this
9749                // packages files and can not delete any more.  Bail.
9750                return null;
9751            }
9752            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9753            if (lastPackage != null) {
9754                pkgs.remove(lastPackage);
9755            }
9756            if (pkgs.size() > 0) {
9757                return pkgs.get(0);
9758            }
9759        }
9760        return null;
9761    }
9762
9763    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9764        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9765                userId, andCode ? 1 : 0, packageName);
9766        if (mSystemReady) {
9767            msg.sendToTarget();
9768        } else {
9769            if (mPostSystemReadyMessages == null) {
9770                mPostSystemReadyMessages = new ArrayList<>();
9771            }
9772            mPostSystemReadyMessages.add(msg);
9773        }
9774    }
9775
9776    void startCleaningPackages() {
9777        // reader
9778        synchronized (mPackages) {
9779            if (!isExternalMediaAvailable()) {
9780                return;
9781            }
9782            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9783                return;
9784            }
9785        }
9786        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9787        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9788        IActivityManager am = ActivityManagerNative.getDefault();
9789        if (am != null) {
9790            try {
9791                am.startService(null, intent, null, mContext.getOpPackageName(),
9792                        UserHandle.USER_SYSTEM);
9793            } catch (RemoteException e) {
9794            }
9795        }
9796    }
9797
9798    @Override
9799    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9800            int installFlags, String installerPackageName, VerificationParams verificationParams,
9801            String packageAbiOverride) {
9802        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9803                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9804    }
9805
9806    @Override
9807    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9808            int installFlags, String installerPackageName, VerificationParams verificationParams,
9809            String packageAbiOverride, int userId) {
9810        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9811
9812        final int callingUid = Binder.getCallingUid();
9813        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9814
9815        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9816            try {
9817                if (observer != null) {
9818                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9819                }
9820            } catch (RemoteException re) {
9821            }
9822            return;
9823        }
9824
9825        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9826            installFlags |= PackageManager.INSTALL_FROM_ADB;
9827
9828        } else {
9829            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9830            // about installerPackageName.
9831
9832            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9833            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9834        }
9835
9836        UserHandle user;
9837        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9838            user = UserHandle.ALL;
9839        } else {
9840            user = new UserHandle(userId);
9841        }
9842
9843        // Only system components can circumvent runtime permissions when installing.
9844        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9845                && mContext.checkCallingOrSelfPermission(Manifest.permission
9846                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9847            throw new SecurityException("You need the "
9848                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9849                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9850        }
9851
9852        verificationParams.setInstallerUid(callingUid);
9853
9854        final File originFile = new File(originPath);
9855        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9856
9857        final Message msg = mHandler.obtainMessage(INIT_COPY);
9858        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9859                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9860        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9861        msg.obj = params;
9862
9863        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9864                System.identityHashCode(msg.obj));
9865        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9866                System.identityHashCode(msg.obj));
9867
9868        mHandler.sendMessage(msg);
9869    }
9870
9871    void installStage(String packageName, File stagedDir, String stagedCid,
9872            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9873            String installerPackageName, int installerUid, UserHandle user) {
9874        final VerificationParams verifParams = new VerificationParams(
9875                null, sessionParams.originatingUri, sessionParams.referrerUri,
9876                sessionParams.originatingUid, null);
9877        verifParams.setInstallerUid(installerUid);
9878
9879        final OriginInfo origin;
9880        if (stagedDir != null) {
9881            origin = OriginInfo.fromStagedFile(stagedDir);
9882        } else {
9883            origin = OriginInfo.fromStagedContainer(stagedCid);
9884        }
9885
9886        final Message msg = mHandler.obtainMessage(INIT_COPY);
9887        final InstallParams params = new InstallParams(origin, null, observer,
9888                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9889                verifParams, user, sessionParams.abiOverride,
9890                sessionParams.grantedRuntimePermissions);
9891        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9892        msg.obj = params;
9893
9894        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9895                System.identityHashCode(msg.obj));
9896        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9897                System.identityHashCode(msg.obj));
9898
9899        mHandler.sendMessage(msg);
9900    }
9901
9902    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9903        Bundle extras = new Bundle(1);
9904        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9905
9906        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9907                packageName, extras, 0, null, null, new int[] {userId});
9908        try {
9909            IActivityManager am = ActivityManagerNative.getDefault();
9910            final boolean isSystem =
9911                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9912            if (isSystem && am.isUserRunning(userId, 0)) {
9913                // The just-installed/enabled app is bundled on the system, so presumed
9914                // to be able to run automatically without needing an explicit launch.
9915                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9916                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9917                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9918                        .setPackage(packageName);
9919                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9920                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9921            }
9922        } catch (RemoteException e) {
9923            // shouldn't happen
9924            Slog.w(TAG, "Unable to bootstrap installed package", e);
9925        }
9926    }
9927
9928    @Override
9929    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9930            int userId) {
9931        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9932        PackageSetting pkgSetting;
9933        final int uid = Binder.getCallingUid();
9934        enforceCrossUserPermission(uid, userId, true, true,
9935                "setApplicationHiddenSetting for user " + userId);
9936
9937        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9938            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9939            return false;
9940        }
9941
9942        long callingId = Binder.clearCallingIdentity();
9943        try {
9944            boolean sendAdded = false;
9945            boolean sendRemoved = false;
9946            // writer
9947            synchronized (mPackages) {
9948                pkgSetting = mSettings.mPackages.get(packageName);
9949                if (pkgSetting == null) {
9950                    return false;
9951                }
9952                if (pkgSetting.getHidden(userId) != hidden) {
9953                    pkgSetting.setHidden(hidden, userId);
9954                    mSettings.writePackageRestrictionsLPr(userId);
9955                    if (hidden) {
9956                        sendRemoved = true;
9957                    } else {
9958                        sendAdded = true;
9959                    }
9960                }
9961            }
9962            if (sendAdded) {
9963                sendPackageAddedForUser(packageName, pkgSetting, userId);
9964                return true;
9965            }
9966            if (sendRemoved) {
9967                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9968                        "hiding pkg");
9969                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9970                return true;
9971            }
9972        } finally {
9973            Binder.restoreCallingIdentity(callingId);
9974        }
9975        return false;
9976    }
9977
9978    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9979            int userId) {
9980        final PackageRemovedInfo info = new PackageRemovedInfo();
9981        info.removedPackage = packageName;
9982        info.removedUsers = new int[] {userId};
9983        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9984        info.sendBroadcast(false, false, false);
9985    }
9986
9987    /**
9988     * Returns true if application is not found or there was an error. Otherwise it returns
9989     * the hidden state of the package for the given user.
9990     */
9991    @Override
9992    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9993        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9994        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9995                false, "getApplicationHidden for user " + userId);
9996        PackageSetting pkgSetting;
9997        long callingId = Binder.clearCallingIdentity();
9998        try {
9999            // writer
10000            synchronized (mPackages) {
10001                pkgSetting = mSettings.mPackages.get(packageName);
10002                if (pkgSetting == null) {
10003                    return true;
10004                }
10005                return pkgSetting.getHidden(userId);
10006            }
10007        } finally {
10008            Binder.restoreCallingIdentity(callingId);
10009        }
10010    }
10011
10012    /**
10013     * @hide
10014     */
10015    @Override
10016    public int installExistingPackageAsUser(String packageName, int userId) {
10017        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10018                null);
10019        PackageSetting pkgSetting;
10020        final int uid = Binder.getCallingUid();
10021        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10022                + userId);
10023        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10024            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10025        }
10026
10027        long callingId = Binder.clearCallingIdentity();
10028        try {
10029            boolean sendAdded = false;
10030
10031            // writer
10032            synchronized (mPackages) {
10033                pkgSetting = mSettings.mPackages.get(packageName);
10034                if (pkgSetting == null) {
10035                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10036                }
10037                if (!pkgSetting.getInstalled(userId)) {
10038                    pkgSetting.setInstalled(true, userId);
10039                    pkgSetting.setHidden(false, userId);
10040                    mSettings.writePackageRestrictionsLPr(userId);
10041                    sendAdded = true;
10042                }
10043            }
10044
10045            if (sendAdded) {
10046                sendPackageAddedForUser(packageName, pkgSetting, userId);
10047            }
10048        } finally {
10049            Binder.restoreCallingIdentity(callingId);
10050        }
10051
10052        return PackageManager.INSTALL_SUCCEEDED;
10053    }
10054
10055    boolean isUserRestricted(int userId, String restrictionKey) {
10056        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10057        if (restrictions.getBoolean(restrictionKey, false)) {
10058            Log.w(TAG, "User is restricted: " + restrictionKey);
10059            return true;
10060        }
10061        return false;
10062    }
10063
10064    @Override
10065    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10066        mContext.enforceCallingOrSelfPermission(
10067                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10068                "Only package verification agents can verify applications");
10069
10070        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10071        final PackageVerificationResponse response = new PackageVerificationResponse(
10072                verificationCode, Binder.getCallingUid());
10073        msg.arg1 = id;
10074        msg.obj = response;
10075        mHandler.sendMessage(msg);
10076    }
10077
10078    @Override
10079    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10080            long millisecondsToDelay) {
10081        mContext.enforceCallingOrSelfPermission(
10082                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10083                "Only package verification agents can extend verification timeouts");
10084
10085        final PackageVerificationState state = mPendingVerification.get(id);
10086        final PackageVerificationResponse response = new PackageVerificationResponse(
10087                verificationCodeAtTimeout, Binder.getCallingUid());
10088
10089        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10090            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10091        }
10092        if (millisecondsToDelay < 0) {
10093            millisecondsToDelay = 0;
10094        }
10095        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10096                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10097            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10098        }
10099
10100        if ((state != null) && !state.timeoutExtended()) {
10101            state.extendTimeout();
10102
10103            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10104            msg.arg1 = id;
10105            msg.obj = response;
10106            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10107        }
10108    }
10109
10110    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10111            int verificationCode, UserHandle user) {
10112        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10113        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10114        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10115        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10116        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10117
10118        mContext.sendBroadcastAsUser(intent, user,
10119                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10120    }
10121
10122    private ComponentName matchComponentForVerifier(String packageName,
10123            List<ResolveInfo> receivers) {
10124        ActivityInfo targetReceiver = null;
10125
10126        final int NR = receivers.size();
10127        for (int i = 0; i < NR; i++) {
10128            final ResolveInfo info = receivers.get(i);
10129            if (info.activityInfo == null) {
10130                continue;
10131            }
10132
10133            if (packageName.equals(info.activityInfo.packageName)) {
10134                targetReceiver = info.activityInfo;
10135                break;
10136            }
10137        }
10138
10139        if (targetReceiver == null) {
10140            return null;
10141        }
10142
10143        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10144    }
10145
10146    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10147            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10148        if (pkgInfo.verifiers.length == 0) {
10149            return null;
10150        }
10151
10152        final int N = pkgInfo.verifiers.length;
10153        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10154        for (int i = 0; i < N; i++) {
10155            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10156
10157            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10158                    receivers);
10159            if (comp == null) {
10160                continue;
10161            }
10162
10163            final int verifierUid = getUidForVerifier(verifierInfo);
10164            if (verifierUid == -1) {
10165                continue;
10166            }
10167
10168            if (DEBUG_VERIFY) {
10169                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10170                        + " with the correct signature");
10171            }
10172            sufficientVerifiers.add(comp);
10173            verificationState.addSufficientVerifier(verifierUid);
10174        }
10175
10176        return sufficientVerifiers;
10177    }
10178
10179    private int getUidForVerifier(VerifierInfo verifierInfo) {
10180        synchronized (mPackages) {
10181            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10182            if (pkg == null) {
10183                return -1;
10184            } else if (pkg.mSignatures.length != 1) {
10185                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10186                        + " has more than one signature; ignoring");
10187                return -1;
10188            }
10189
10190            /*
10191             * If the public key of the package's signature does not match
10192             * our expected public key, then this is a different package and
10193             * we should skip.
10194             */
10195
10196            final byte[] expectedPublicKey;
10197            try {
10198                final Signature verifierSig = pkg.mSignatures[0];
10199                final PublicKey publicKey = verifierSig.getPublicKey();
10200                expectedPublicKey = publicKey.getEncoded();
10201            } catch (CertificateException e) {
10202                return -1;
10203            }
10204
10205            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10206
10207            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10208                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10209                        + " does not have the expected public key; ignoring");
10210                return -1;
10211            }
10212
10213            return pkg.applicationInfo.uid;
10214        }
10215    }
10216
10217    @Override
10218    public void finishPackageInstall(int token) {
10219        enforceSystemOrRoot("Only the system is allowed to finish installs");
10220
10221        if (DEBUG_INSTALL) {
10222            Slog.v(TAG, "BM finishing package install for " + token);
10223        }
10224        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10225
10226        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10227        mHandler.sendMessage(msg);
10228    }
10229
10230    /**
10231     * Get the verification agent timeout.
10232     *
10233     * @return verification timeout in milliseconds
10234     */
10235    private long getVerificationTimeout() {
10236        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10237                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10238                DEFAULT_VERIFICATION_TIMEOUT);
10239    }
10240
10241    /**
10242     * Get the default verification agent response code.
10243     *
10244     * @return default verification response code
10245     */
10246    private int getDefaultVerificationResponse() {
10247        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10248                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10249                DEFAULT_VERIFICATION_RESPONSE);
10250    }
10251
10252    /**
10253     * Check whether or not package verification has been enabled.
10254     *
10255     * @return true if verification should be performed
10256     */
10257    private boolean isVerificationEnabled(int userId, int installFlags) {
10258        if (!DEFAULT_VERIFY_ENABLE) {
10259            return false;
10260        }
10261        // TODO: fix b/25118622; don't bypass verification
10262        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10263            return false;
10264        }
10265
10266        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10267
10268        // Check if installing from ADB
10269        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10270            // Do not run verification in a test harness environment
10271            if (ActivityManager.isRunningInTestHarness()) {
10272                return false;
10273            }
10274            if (ensureVerifyAppsEnabled) {
10275                return true;
10276            }
10277            // Check if the developer does not want package verification for ADB installs
10278            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10279                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10280                return false;
10281            }
10282        }
10283
10284        if (ensureVerifyAppsEnabled) {
10285            return true;
10286        }
10287
10288        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10289                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10290    }
10291
10292    @Override
10293    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10294            throws RemoteException {
10295        mContext.enforceCallingOrSelfPermission(
10296                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10297                "Only intentfilter verification agents can verify applications");
10298
10299        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10300        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10301                Binder.getCallingUid(), verificationCode, failedDomains);
10302        msg.arg1 = id;
10303        msg.obj = response;
10304        mHandler.sendMessage(msg);
10305    }
10306
10307    @Override
10308    public int getIntentVerificationStatus(String packageName, int userId) {
10309        synchronized (mPackages) {
10310            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10311        }
10312    }
10313
10314    @Override
10315    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10316        mContext.enforceCallingOrSelfPermission(
10317                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10318
10319        boolean result = false;
10320        synchronized (mPackages) {
10321            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10322        }
10323        if (result) {
10324            scheduleWritePackageRestrictionsLocked(userId);
10325        }
10326        return result;
10327    }
10328
10329    @Override
10330    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10331        synchronized (mPackages) {
10332            return mSettings.getIntentFilterVerificationsLPr(packageName);
10333        }
10334    }
10335
10336    @Override
10337    public List<IntentFilter> getAllIntentFilters(String packageName) {
10338        if (TextUtils.isEmpty(packageName)) {
10339            return Collections.<IntentFilter>emptyList();
10340        }
10341        synchronized (mPackages) {
10342            PackageParser.Package pkg = mPackages.get(packageName);
10343            if (pkg == null || pkg.activities == null) {
10344                return Collections.<IntentFilter>emptyList();
10345            }
10346            final int count = pkg.activities.size();
10347            ArrayList<IntentFilter> result = new ArrayList<>();
10348            for (int n=0; n<count; n++) {
10349                PackageParser.Activity activity = pkg.activities.get(n);
10350                if (activity.intents != null || activity.intents.size() > 0) {
10351                    result.addAll(activity.intents);
10352                }
10353            }
10354            return result;
10355        }
10356    }
10357
10358    @Override
10359    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10360        mContext.enforceCallingOrSelfPermission(
10361                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10362
10363        synchronized (mPackages) {
10364            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10365            if (packageName != null) {
10366                result |= updateIntentVerificationStatus(packageName,
10367                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10368                        userId);
10369                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10370                        packageName, userId);
10371            }
10372            return result;
10373        }
10374    }
10375
10376    @Override
10377    public String getDefaultBrowserPackageName(int userId) {
10378        synchronized (mPackages) {
10379            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10380        }
10381    }
10382
10383    /**
10384     * Get the "allow unknown sources" setting.
10385     *
10386     * @return the current "allow unknown sources" setting
10387     */
10388    private int getUnknownSourcesSettings() {
10389        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10390                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10391                -1);
10392    }
10393
10394    @Override
10395    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10396        final int uid = Binder.getCallingUid();
10397        // writer
10398        synchronized (mPackages) {
10399            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10400            if (targetPackageSetting == null) {
10401                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10402            }
10403
10404            PackageSetting installerPackageSetting;
10405            if (installerPackageName != null) {
10406                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10407                if (installerPackageSetting == null) {
10408                    throw new IllegalArgumentException("Unknown installer package: "
10409                            + installerPackageName);
10410                }
10411            } else {
10412                installerPackageSetting = null;
10413            }
10414
10415            Signature[] callerSignature;
10416            Object obj = mSettings.getUserIdLPr(uid);
10417            if (obj != null) {
10418                if (obj instanceof SharedUserSetting) {
10419                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10420                } else if (obj instanceof PackageSetting) {
10421                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10422                } else {
10423                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10424                }
10425            } else {
10426                throw new SecurityException("Unknown calling uid " + uid);
10427            }
10428
10429            // Verify: can't set installerPackageName to a package that is
10430            // not signed with the same cert as the caller.
10431            if (installerPackageSetting != null) {
10432                if (compareSignatures(callerSignature,
10433                        installerPackageSetting.signatures.mSignatures)
10434                        != PackageManager.SIGNATURE_MATCH) {
10435                    throw new SecurityException(
10436                            "Caller does not have same cert as new installer package "
10437                            + installerPackageName);
10438                }
10439            }
10440
10441            // Verify: if target already has an installer package, it must
10442            // be signed with the same cert as the caller.
10443            if (targetPackageSetting.installerPackageName != null) {
10444                PackageSetting setting = mSettings.mPackages.get(
10445                        targetPackageSetting.installerPackageName);
10446                // If the currently set package isn't valid, then it's always
10447                // okay to change it.
10448                if (setting != null) {
10449                    if (compareSignatures(callerSignature,
10450                            setting.signatures.mSignatures)
10451                            != PackageManager.SIGNATURE_MATCH) {
10452                        throw new SecurityException(
10453                                "Caller does not have same cert as old installer package "
10454                                + targetPackageSetting.installerPackageName);
10455                    }
10456                }
10457            }
10458
10459            // Okay!
10460            targetPackageSetting.installerPackageName = installerPackageName;
10461            scheduleWriteSettingsLocked();
10462        }
10463    }
10464
10465    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10466        // Queue up an async operation since the package installation may take a little while.
10467        mHandler.post(new Runnable() {
10468            public void run() {
10469                mHandler.removeCallbacks(this);
10470                 // Result object to be returned
10471                PackageInstalledInfo res = new PackageInstalledInfo();
10472                res.returnCode = currentStatus;
10473                res.uid = -1;
10474                res.pkg = null;
10475                res.removedInfo = new PackageRemovedInfo();
10476                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10477                    args.doPreInstall(res.returnCode);
10478                    synchronized (mInstallLock) {
10479                        installPackageTracedLI(args, res);
10480                    }
10481                    args.doPostInstall(res.returnCode, res.uid);
10482                }
10483
10484                // A restore should be performed at this point if (a) the install
10485                // succeeded, (b) the operation is not an update, and (c) the new
10486                // package has not opted out of backup participation.
10487                final boolean update = res.removedInfo.removedPackage != null;
10488                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10489                boolean doRestore = !update
10490                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10491
10492                // Set up the post-install work request bookkeeping.  This will be used
10493                // and cleaned up by the post-install event handling regardless of whether
10494                // there's a restore pass performed.  Token values are >= 1.
10495                int token;
10496                if (mNextInstallToken < 0) mNextInstallToken = 1;
10497                token = mNextInstallToken++;
10498
10499                PostInstallData data = new PostInstallData(args, res);
10500                mRunningInstalls.put(token, data);
10501                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10502
10503                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10504                    // Pass responsibility to the Backup Manager.  It will perform a
10505                    // restore if appropriate, then pass responsibility back to the
10506                    // Package Manager to run the post-install observer callbacks
10507                    // and broadcasts.
10508                    IBackupManager bm = IBackupManager.Stub.asInterface(
10509                            ServiceManager.getService(Context.BACKUP_SERVICE));
10510                    if (bm != null) {
10511                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10512                                + " to BM for possible restore");
10513                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10514                        try {
10515                            // TODO: http://b/22388012
10516                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10517                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10518                            } else {
10519                                doRestore = false;
10520                            }
10521                        } catch (RemoteException e) {
10522                            // can't happen; the backup manager is local
10523                        } catch (Exception e) {
10524                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10525                            doRestore = false;
10526                        }
10527                    } else {
10528                        Slog.e(TAG, "Backup Manager not found!");
10529                        doRestore = false;
10530                    }
10531                }
10532
10533                if (!doRestore) {
10534                    // No restore possible, or the Backup Manager was mysteriously not
10535                    // available -- just fire the post-install work request directly.
10536                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10537
10538                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10539
10540                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10541                    mHandler.sendMessage(msg);
10542                }
10543            }
10544        });
10545    }
10546
10547    private abstract class HandlerParams {
10548        private static final int MAX_RETRIES = 4;
10549
10550        /**
10551         * Number of times startCopy() has been attempted and had a non-fatal
10552         * error.
10553         */
10554        private int mRetries = 0;
10555
10556        /** User handle for the user requesting the information or installation. */
10557        private final UserHandle mUser;
10558        String traceMethod;
10559        int traceCookie;
10560
10561        HandlerParams(UserHandle user) {
10562            mUser = user;
10563        }
10564
10565        UserHandle getUser() {
10566            return mUser;
10567        }
10568
10569        HandlerParams setTraceMethod(String traceMethod) {
10570            this.traceMethod = traceMethod;
10571            return this;
10572        }
10573
10574        HandlerParams setTraceCookie(int traceCookie) {
10575            this.traceCookie = traceCookie;
10576            return this;
10577        }
10578
10579        final boolean startCopy() {
10580            boolean res;
10581            try {
10582                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10583
10584                if (++mRetries > MAX_RETRIES) {
10585                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10586                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10587                    handleServiceError();
10588                    return false;
10589                } else {
10590                    handleStartCopy();
10591                    res = true;
10592                }
10593            } catch (RemoteException e) {
10594                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10595                mHandler.sendEmptyMessage(MCS_RECONNECT);
10596                res = false;
10597            }
10598            handleReturnCode();
10599            return res;
10600        }
10601
10602        final void serviceError() {
10603            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10604            handleServiceError();
10605            handleReturnCode();
10606        }
10607
10608        abstract void handleStartCopy() throws RemoteException;
10609        abstract void handleServiceError();
10610        abstract void handleReturnCode();
10611    }
10612
10613    class MeasureParams extends HandlerParams {
10614        private final PackageStats mStats;
10615        private boolean mSuccess;
10616
10617        private final IPackageStatsObserver mObserver;
10618
10619        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10620            super(new UserHandle(stats.userHandle));
10621            mObserver = observer;
10622            mStats = stats;
10623        }
10624
10625        @Override
10626        public String toString() {
10627            return "MeasureParams{"
10628                + Integer.toHexString(System.identityHashCode(this))
10629                + " " + mStats.packageName + "}";
10630        }
10631
10632        @Override
10633        void handleStartCopy() throws RemoteException {
10634            synchronized (mInstallLock) {
10635                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10636            }
10637
10638            if (mSuccess) {
10639                final boolean mounted;
10640                if (Environment.isExternalStorageEmulated()) {
10641                    mounted = true;
10642                } else {
10643                    final String status = Environment.getExternalStorageState();
10644                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10645                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10646                }
10647
10648                if (mounted) {
10649                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10650
10651                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10652                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10653
10654                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10655                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10656
10657                    // Always subtract cache size, since it's a subdirectory
10658                    mStats.externalDataSize -= mStats.externalCacheSize;
10659
10660                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10661                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10662
10663                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10664                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10665                }
10666            }
10667        }
10668
10669        @Override
10670        void handleReturnCode() {
10671            if (mObserver != null) {
10672                try {
10673                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10674                } catch (RemoteException e) {
10675                    Slog.i(TAG, "Observer no longer exists.");
10676                }
10677            }
10678        }
10679
10680        @Override
10681        void handleServiceError() {
10682            Slog.e(TAG, "Could not measure application " + mStats.packageName
10683                            + " external storage");
10684        }
10685    }
10686
10687    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10688            throws RemoteException {
10689        long result = 0;
10690        for (File path : paths) {
10691            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10692        }
10693        return result;
10694    }
10695
10696    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10697        for (File path : paths) {
10698            try {
10699                mcs.clearDirectory(path.getAbsolutePath());
10700            } catch (RemoteException e) {
10701            }
10702        }
10703    }
10704
10705    static class OriginInfo {
10706        /**
10707         * Location where install is coming from, before it has been
10708         * copied/renamed into place. This could be a single monolithic APK
10709         * file, or a cluster directory. This location may be untrusted.
10710         */
10711        final File file;
10712        final String cid;
10713
10714        /**
10715         * Flag indicating that {@link #file} or {@link #cid} has already been
10716         * staged, meaning downstream users don't need to defensively copy the
10717         * contents.
10718         */
10719        final boolean staged;
10720
10721        /**
10722         * Flag indicating that {@link #file} or {@link #cid} is an already
10723         * installed app that is being moved.
10724         */
10725        final boolean existing;
10726
10727        final String resolvedPath;
10728        final File resolvedFile;
10729
10730        static OriginInfo fromNothing() {
10731            return new OriginInfo(null, null, false, false);
10732        }
10733
10734        static OriginInfo fromUntrustedFile(File file) {
10735            return new OriginInfo(file, null, false, false);
10736        }
10737
10738        static OriginInfo fromExistingFile(File file) {
10739            return new OriginInfo(file, null, false, true);
10740        }
10741
10742        static OriginInfo fromStagedFile(File file) {
10743            return new OriginInfo(file, null, true, false);
10744        }
10745
10746        static OriginInfo fromStagedContainer(String cid) {
10747            return new OriginInfo(null, cid, true, false);
10748        }
10749
10750        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10751            this.file = file;
10752            this.cid = cid;
10753            this.staged = staged;
10754            this.existing = existing;
10755
10756            if (cid != null) {
10757                resolvedPath = PackageHelper.getSdDir(cid);
10758                resolvedFile = new File(resolvedPath);
10759            } else if (file != null) {
10760                resolvedPath = file.getAbsolutePath();
10761                resolvedFile = file;
10762            } else {
10763                resolvedPath = null;
10764                resolvedFile = null;
10765            }
10766        }
10767    }
10768
10769    class MoveInfo {
10770        final int moveId;
10771        final String fromUuid;
10772        final String toUuid;
10773        final String packageName;
10774        final String dataAppName;
10775        final int appId;
10776        final String seinfo;
10777
10778        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10779                String dataAppName, int appId, String seinfo) {
10780            this.moveId = moveId;
10781            this.fromUuid = fromUuid;
10782            this.toUuid = toUuid;
10783            this.packageName = packageName;
10784            this.dataAppName = dataAppName;
10785            this.appId = appId;
10786            this.seinfo = seinfo;
10787        }
10788    }
10789
10790    class InstallParams extends HandlerParams {
10791        final OriginInfo origin;
10792        final MoveInfo move;
10793        final IPackageInstallObserver2 observer;
10794        int installFlags;
10795        final String installerPackageName;
10796        final String volumeUuid;
10797        final VerificationParams verificationParams;
10798        private InstallArgs mArgs;
10799        private int mRet;
10800        final String packageAbiOverride;
10801        final String[] grantedRuntimePermissions;
10802
10803        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10804                int installFlags, String installerPackageName, String volumeUuid,
10805                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10806                String[] grantedPermissions) {
10807            super(user);
10808            this.origin = origin;
10809            this.move = move;
10810            this.observer = observer;
10811            this.installFlags = installFlags;
10812            this.installerPackageName = installerPackageName;
10813            this.volumeUuid = volumeUuid;
10814            this.verificationParams = verificationParams;
10815            this.packageAbiOverride = packageAbiOverride;
10816            this.grantedRuntimePermissions = grantedPermissions;
10817        }
10818
10819        @Override
10820        public String toString() {
10821            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10822                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10823        }
10824
10825        public ManifestDigest getManifestDigest() {
10826            if (verificationParams == null) {
10827                return null;
10828            }
10829            return verificationParams.getManifestDigest();
10830        }
10831
10832        private int installLocationPolicy(PackageInfoLite pkgLite) {
10833            String packageName = pkgLite.packageName;
10834            int installLocation = pkgLite.installLocation;
10835            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10836            // reader
10837            synchronized (mPackages) {
10838                PackageParser.Package pkg = mPackages.get(packageName);
10839                if (pkg != null) {
10840                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10841                        // Check for downgrading.
10842                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10843                            try {
10844                                checkDowngrade(pkg, pkgLite);
10845                            } catch (PackageManagerException e) {
10846                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10847                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10848                            }
10849                        }
10850                        // Check for updated system application.
10851                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10852                            if (onSd) {
10853                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10854                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10855                            }
10856                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10857                        } else {
10858                            if (onSd) {
10859                                // Install flag overrides everything.
10860                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10861                            }
10862                            // If current upgrade specifies particular preference
10863                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10864                                // Application explicitly specified internal.
10865                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10866                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10867                                // App explictly prefers external. Let policy decide
10868                            } else {
10869                                // Prefer previous location
10870                                if (isExternal(pkg)) {
10871                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10872                                }
10873                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10874                            }
10875                        }
10876                    } else {
10877                        // Invalid install. Return error code
10878                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10879                    }
10880                }
10881            }
10882            // All the special cases have been taken care of.
10883            // Return result based on recommended install location.
10884            if (onSd) {
10885                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10886            }
10887            return pkgLite.recommendedInstallLocation;
10888        }
10889
10890        /*
10891         * Invoke remote method to get package information and install
10892         * location values. Override install location based on default
10893         * policy if needed and then create install arguments based
10894         * on the install location.
10895         */
10896        public void handleStartCopy() throws RemoteException {
10897            int ret = PackageManager.INSTALL_SUCCEEDED;
10898
10899            // If we're already staged, we've firmly committed to an install location
10900            if (origin.staged) {
10901                if (origin.file != null) {
10902                    installFlags |= PackageManager.INSTALL_INTERNAL;
10903                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10904                } else if (origin.cid != null) {
10905                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10906                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10907                } else {
10908                    throw new IllegalStateException("Invalid stage location");
10909                }
10910            }
10911
10912            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10913            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10914            PackageInfoLite pkgLite = null;
10915
10916            if (onInt && onSd) {
10917                // Check if both bits are set.
10918                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10919                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10920            } else {
10921                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10922                        packageAbiOverride);
10923
10924                /*
10925                 * If we have too little free space, try to free cache
10926                 * before giving up.
10927                 */
10928                if (!origin.staged && pkgLite.recommendedInstallLocation
10929                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10930                    // TODO: focus freeing disk space on the target device
10931                    final StorageManager storage = StorageManager.from(mContext);
10932                    final long lowThreshold = storage.getStorageLowBytes(
10933                            Environment.getDataDirectory());
10934
10935                    final long sizeBytes = mContainerService.calculateInstalledSize(
10936                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10937
10938                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10939                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10940                                installFlags, packageAbiOverride);
10941                    }
10942
10943                    /*
10944                     * The cache free must have deleted the file we
10945                     * downloaded to install.
10946                     *
10947                     * TODO: fix the "freeCache" call to not delete
10948                     *       the file we care about.
10949                     */
10950                    if (pkgLite.recommendedInstallLocation
10951                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10952                        pkgLite.recommendedInstallLocation
10953                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10954                    }
10955                }
10956            }
10957
10958            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10959                int loc = pkgLite.recommendedInstallLocation;
10960                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10961                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10962                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10963                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10964                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10965                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10966                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10967                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10968                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10969                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10970                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10971                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10972                } else {
10973                    // Override with defaults if needed.
10974                    loc = installLocationPolicy(pkgLite);
10975                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10976                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10977                    } else if (!onSd && !onInt) {
10978                        // Override install location with flags
10979                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10980                            // Set the flag to install on external media.
10981                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10982                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10983                        } else {
10984                            // Make sure the flag for installing on external
10985                            // media is unset
10986                            installFlags |= PackageManager.INSTALL_INTERNAL;
10987                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10988                        }
10989                    }
10990                }
10991            }
10992
10993            final InstallArgs args = createInstallArgs(this);
10994            mArgs = args;
10995
10996            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10997                // TODO: http://b/22976637
10998                // Apps installed for "all" users use the device owner to verify the app
10999                UserHandle verifierUser = getUser();
11000                if (verifierUser == UserHandle.ALL) {
11001                    verifierUser = UserHandle.SYSTEM;
11002                }
11003
11004                /*
11005                 * Determine if we have any installed package verifiers. If we
11006                 * do, then we'll defer to them to verify the packages.
11007                 */
11008                final int requiredUid = mRequiredVerifierPackage == null ? -1
11009                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11010                if (!origin.existing && requiredUid != -1
11011                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11012                    final Intent verification = new Intent(
11013                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11014                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11015                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11016                            PACKAGE_MIME_TYPE);
11017                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11018
11019                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11020                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11021                            verifierUser.getIdentifier());
11022
11023                    if (DEBUG_VERIFY) {
11024                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11025                                + verification.toString() + " with " + pkgLite.verifiers.length
11026                                + " optional verifiers");
11027                    }
11028
11029                    final int verificationId = mPendingVerificationToken++;
11030
11031                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11032
11033                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11034                            installerPackageName);
11035
11036                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11037                            installFlags);
11038
11039                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11040                            pkgLite.packageName);
11041
11042                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11043                            pkgLite.versionCode);
11044
11045                    if (verificationParams != null) {
11046                        if (verificationParams.getVerificationURI() != null) {
11047                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11048                                 verificationParams.getVerificationURI());
11049                        }
11050                        if (verificationParams.getOriginatingURI() != null) {
11051                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11052                                  verificationParams.getOriginatingURI());
11053                        }
11054                        if (verificationParams.getReferrer() != null) {
11055                            verification.putExtra(Intent.EXTRA_REFERRER,
11056                                  verificationParams.getReferrer());
11057                        }
11058                        if (verificationParams.getOriginatingUid() >= 0) {
11059                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11060                                  verificationParams.getOriginatingUid());
11061                        }
11062                        if (verificationParams.getInstallerUid() >= 0) {
11063                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11064                                  verificationParams.getInstallerUid());
11065                        }
11066                    }
11067
11068                    final PackageVerificationState verificationState = new PackageVerificationState(
11069                            requiredUid, args);
11070
11071                    mPendingVerification.append(verificationId, verificationState);
11072
11073                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11074                            receivers, verificationState);
11075
11076                    /*
11077                     * If any sufficient verifiers were listed in the package
11078                     * manifest, attempt to ask them.
11079                     */
11080                    if (sufficientVerifiers != null) {
11081                        final int N = sufficientVerifiers.size();
11082                        if (N == 0) {
11083                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11084                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11085                        } else {
11086                            for (int i = 0; i < N; i++) {
11087                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11088
11089                                final Intent sufficientIntent = new Intent(verification);
11090                                sufficientIntent.setComponent(verifierComponent);
11091                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11092                            }
11093                        }
11094                    }
11095
11096                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11097                            mRequiredVerifierPackage, receivers);
11098                    if (ret == PackageManager.INSTALL_SUCCEEDED
11099                            && mRequiredVerifierPackage != null) {
11100                        Trace.asyncTraceBegin(
11101                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11102                        /*
11103                         * Send the intent to the required verification agent,
11104                         * but only start the verification timeout after the
11105                         * target BroadcastReceivers have run.
11106                         */
11107                        verification.setComponent(requiredVerifierComponent);
11108                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11109                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11110                                new BroadcastReceiver() {
11111                                    @Override
11112                                    public void onReceive(Context context, Intent intent) {
11113                                        final Message msg = mHandler
11114                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11115                                        msg.arg1 = verificationId;
11116                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11117                                    }
11118                                }, null, 0, null, null);
11119
11120                        /*
11121                         * We don't want the copy to proceed until verification
11122                         * succeeds, so null out this field.
11123                         */
11124                        mArgs = null;
11125                    }
11126                } else {
11127                    /*
11128                     * No package verification is enabled, so immediately start
11129                     * the remote call to initiate copy using temporary file.
11130                     */
11131                    ret = args.copyApk(mContainerService, true);
11132                }
11133            }
11134
11135            mRet = ret;
11136        }
11137
11138        @Override
11139        void handleReturnCode() {
11140            // If mArgs is null, then MCS couldn't be reached. When it
11141            // reconnects, it will try again to install. At that point, this
11142            // will succeed.
11143            if (mArgs != null) {
11144                processPendingInstall(mArgs, mRet);
11145            }
11146        }
11147
11148        @Override
11149        void handleServiceError() {
11150            mArgs = createInstallArgs(this);
11151            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11152        }
11153
11154        public boolean isForwardLocked() {
11155            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11156        }
11157    }
11158
11159    /**
11160     * Used during creation of InstallArgs
11161     *
11162     * @param installFlags package installation flags
11163     * @return true if should be installed on external storage
11164     */
11165    private static boolean installOnExternalAsec(int installFlags) {
11166        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11167            return false;
11168        }
11169        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11170            return true;
11171        }
11172        return false;
11173    }
11174
11175    /**
11176     * Used during creation of InstallArgs
11177     *
11178     * @param installFlags package installation flags
11179     * @return true if should be installed as forward locked
11180     */
11181    private static boolean installForwardLocked(int installFlags) {
11182        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11183    }
11184
11185    private InstallArgs createInstallArgs(InstallParams params) {
11186        if (params.move != null) {
11187            return new MoveInstallArgs(params);
11188        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11189            return new AsecInstallArgs(params);
11190        } else {
11191            return new FileInstallArgs(params);
11192        }
11193    }
11194
11195    /**
11196     * Create args that describe an existing installed package. Typically used
11197     * when cleaning up old installs, or used as a move source.
11198     */
11199    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11200            String resourcePath, String[] instructionSets) {
11201        final boolean isInAsec;
11202        if (installOnExternalAsec(installFlags)) {
11203            /* Apps on SD card are always in ASEC containers. */
11204            isInAsec = true;
11205        } else if (installForwardLocked(installFlags)
11206                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11207            /*
11208             * Forward-locked apps are only in ASEC containers if they're the
11209             * new style
11210             */
11211            isInAsec = true;
11212        } else {
11213            isInAsec = false;
11214        }
11215
11216        if (isInAsec) {
11217            return new AsecInstallArgs(codePath, instructionSets,
11218                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11219        } else {
11220            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11221        }
11222    }
11223
11224    static abstract class InstallArgs {
11225        /** @see InstallParams#origin */
11226        final OriginInfo origin;
11227        /** @see InstallParams#move */
11228        final MoveInfo move;
11229
11230        final IPackageInstallObserver2 observer;
11231        // Always refers to PackageManager flags only
11232        final int installFlags;
11233        final String installerPackageName;
11234        final String volumeUuid;
11235        final ManifestDigest manifestDigest;
11236        final UserHandle user;
11237        final String abiOverride;
11238        final String[] installGrantPermissions;
11239        /** If non-null, drop an async trace when the install completes */
11240        final String traceMethod;
11241        final int traceCookie;
11242
11243        // The list of instruction sets supported by this app. This is currently
11244        // only used during the rmdex() phase to clean up resources. We can get rid of this
11245        // if we move dex files under the common app path.
11246        /* nullable */ String[] instructionSets;
11247
11248        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11249                int installFlags, String installerPackageName, String volumeUuid,
11250                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11251                String abiOverride, String[] installGrantPermissions,
11252                String traceMethod, int traceCookie) {
11253            this.origin = origin;
11254            this.move = move;
11255            this.installFlags = installFlags;
11256            this.observer = observer;
11257            this.installerPackageName = installerPackageName;
11258            this.volumeUuid = volumeUuid;
11259            this.manifestDigest = manifestDigest;
11260            this.user = user;
11261            this.instructionSets = instructionSets;
11262            this.abiOverride = abiOverride;
11263            this.installGrantPermissions = installGrantPermissions;
11264            this.traceMethod = traceMethod;
11265            this.traceCookie = traceCookie;
11266        }
11267
11268        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11269        abstract int doPreInstall(int status);
11270
11271        /**
11272         * Rename package into final resting place. All paths on the given
11273         * scanned package should be updated to reflect the rename.
11274         */
11275        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11276        abstract int doPostInstall(int status, int uid);
11277
11278        /** @see PackageSettingBase#codePathString */
11279        abstract String getCodePath();
11280        /** @see PackageSettingBase#resourcePathString */
11281        abstract String getResourcePath();
11282
11283        // Need installer lock especially for dex file removal.
11284        abstract void cleanUpResourcesLI();
11285        abstract boolean doPostDeleteLI(boolean delete);
11286
11287        /**
11288         * Called before the source arguments are copied. This is used mostly
11289         * for MoveParams when it needs to read the source file to put it in the
11290         * destination.
11291         */
11292        int doPreCopy() {
11293            return PackageManager.INSTALL_SUCCEEDED;
11294        }
11295
11296        /**
11297         * Called after the source arguments are copied. This is used mostly for
11298         * MoveParams when it needs to read the source file to put it in the
11299         * destination.
11300         *
11301         * @return
11302         */
11303        int doPostCopy(int uid) {
11304            return PackageManager.INSTALL_SUCCEEDED;
11305        }
11306
11307        protected boolean isFwdLocked() {
11308            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11309        }
11310
11311        protected boolean isExternalAsec() {
11312            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11313        }
11314
11315        UserHandle getUser() {
11316            return user;
11317        }
11318    }
11319
11320    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11321        if (!allCodePaths.isEmpty()) {
11322            if (instructionSets == null) {
11323                throw new IllegalStateException("instructionSet == null");
11324            }
11325            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11326            for (String codePath : allCodePaths) {
11327                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11328                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11329                    if (retCode < 0) {
11330                        Slog.w(TAG, "Couldn't remove dex file for package: "
11331                                + " at location " + codePath + ", retcode=" + retCode);
11332                        // we don't consider this to be a failure of the core package deletion
11333                    }
11334                }
11335            }
11336        }
11337    }
11338
11339    /**
11340     * Logic to handle installation of non-ASEC applications, including copying
11341     * and renaming logic.
11342     */
11343    class FileInstallArgs extends InstallArgs {
11344        private File codeFile;
11345        private File resourceFile;
11346
11347        // Example topology:
11348        // /data/app/com.example/base.apk
11349        // /data/app/com.example/split_foo.apk
11350        // /data/app/com.example/lib/arm/libfoo.so
11351        // /data/app/com.example/lib/arm64/libfoo.so
11352        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11353
11354        /** New install */
11355        FileInstallArgs(InstallParams params) {
11356            super(params.origin, params.move, params.observer, params.installFlags,
11357                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11358                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11359                    params.grantedRuntimePermissions,
11360                    params.traceMethod, params.traceCookie);
11361            if (isFwdLocked()) {
11362                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11363            }
11364        }
11365
11366        /** Existing install */
11367        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11368            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11369                    null, null, null, 0);
11370            this.codeFile = (codePath != null) ? new File(codePath) : null;
11371            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11372        }
11373
11374        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11375            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11376            try {
11377                return doCopyApk(imcs, temp);
11378            } finally {
11379                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11380            }
11381        }
11382
11383        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11384            if (origin.staged) {
11385                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11386                codeFile = origin.file;
11387                resourceFile = origin.file;
11388                return PackageManager.INSTALL_SUCCEEDED;
11389            }
11390
11391            try {
11392                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11393                codeFile = tempDir;
11394                resourceFile = tempDir;
11395            } catch (IOException e) {
11396                Slog.w(TAG, "Failed to create copy file: " + e);
11397                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11398            }
11399
11400            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11401                @Override
11402                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11403                    if (!FileUtils.isValidExtFilename(name)) {
11404                        throw new IllegalArgumentException("Invalid filename: " + name);
11405                    }
11406                    try {
11407                        final File file = new File(codeFile, name);
11408                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11409                                O_RDWR | O_CREAT, 0644);
11410                        Os.chmod(file.getAbsolutePath(), 0644);
11411                        return new ParcelFileDescriptor(fd);
11412                    } catch (ErrnoException e) {
11413                        throw new RemoteException("Failed to open: " + e.getMessage());
11414                    }
11415                }
11416            };
11417
11418            int ret = PackageManager.INSTALL_SUCCEEDED;
11419            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11420            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11421                Slog.e(TAG, "Failed to copy package");
11422                return ret;
11423            }
11424
11425            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11426            NativeLibraryHelper.Handle handle = null;
11427            try {
11428                handle = NativeLibraryHelper.Handle.create(codeFile);
11429                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11430                        abiOverride);
11431            } catch (IOException e) {
11432                Slog.e(TAG, "Copying native libraries failed", e);
11433                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11434            } finally {
11435                IoUtils.closeQuietly(handle);
11436            }
11437
11438            return ret;
11439        }
11440
11441        int doPreInstall(int status) {
11442            if (status != PackageManager.INSTALL_SUCCEEDED) {
11443                cleanUp();
11444            }
11445            return status;
11446        }
11447
11448        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11449            if (status != PackageManager.INSTALL_SUCCEEDED) {
11450                cleanUp();
11451                return false;
11452            }
11453
11454            final File targetDir = codeFile.getParentFile();
11455            final File beforeCodeFile = codeFile;
11456            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11457
11458            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11459            try {
11460                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11461            } catch (ErrnoException e) {
11462                Slog.w(TAG, "Failed to rename", e);
11463                return false;
11464            }
11465
11466            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11467                Slog.w(TAG, "Failed to restorecon");
11468                return false;
11469            }
11470
11471            // Reflect the rename internally
11472            codeFile = afterCodeFile;
11473            resourceFile = afterCodeFile;
11474
11475            // Reflect the rename in scanned details
11476            pkg.codePath = afterCodeFile.getAbsolutePath();
11477            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11478                    pkg.baseCodePath);
11479            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11480                    pkg.splitCodePaths);
11481
11482            // Reflect the rename in app info
11483            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11484            pkg.applicationInfo.setCodePath(pkg.codePath);
11485            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11486            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11487            pkg.applicationInfo.setResourcePath(pkg.codePath);
11488            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11489            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11490
11491            return true;
11492        }
11493
11494        int doPostInstall(int status, int uid) {
11495            if (status != PackageManager.INSTALL_SUCCEEDED) {
11496                cleanUp();
11497            }
11498            return status;
11499        }
11500
11501        @Override
11502        String getCodePath() {
11503            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11504        }
11505
11506        @Override
11507        String getResourcePath() {
11508            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11509        }
11510
11511        private boolean cleanUp() {
11512            if (codeFile == null || !codeFile.exists()) {
11513                return false;
11514            }
11515
11516            if (codeFile.isDirectory()) {
11517                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11518            } else {
11519                codeFile.delete();
11520            }
11521
11522            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11523                resourceFile.delete();
11524            }
11525
11526            return true;
11527        }
11528
11529        void cleanUpResourcesLI() {
11530            // Try enumerating all code paths before deleting
11531            List<String> allCodePaths = Collections.EMPTY_LIST;
11532            if (codeFile != null && codeFile.exists()) {
11533                try {
11534                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11535                    allCodePaths = pkg.getAllCodePaths();
11536                } catch (PackageParserException e) {
11537                    // Ignored; we tried our best
11538                }
11539            }
11540
11541            cleanUp();
11542            removeDexFiles(allCodePaths, instructionSets);
11543        }
11544
11545        boolean doPostDeleteLI(boolean delete) {
11546            // XXX err, shouldn't we respect the delete flag?
11547            cleanUpResourcesLI();
11548            return true;
11549        }
11550    }
11551
11552    private boolean isAsecExternal(String cid) {
11553        final String asecPath = PackageHelper.getSdFilesystem(cid);
11554        return !asecPath.startsWith(mAsecInternalPath);
11555    }
11556
11557    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11558            PackageManagerException {
11559        if (copyRet < 0) {
11560            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11561                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11562                throw new PackageManagerException(copyRet, message);
11563            }
11564        }
11565    }
11566
11567    /**
11568     * Extract the MountService "container ID" from the full code path of an
11569     * .apk.
11570     */
11571    static String cidFromCodePath(String fullCodePath) {
11572        int eidx = fullCodePath.lastIndexOf("/");
11573        String subStr1 = fullCodePath.substring(0, eidx);
11574        int sidx = subStr1.lastIndexOf("/");
11575        return subStr1.substring(sidx+1, eidx);
11576    }
11577
11578    /**
11579     * Logic to handle installation of ASEC applications, including copying and
11580     * renaming logic.
11581     */
11582    class AsecInstallArgs extends InstallArgs {
11583        static final String RES_FILE_NAME = "pkg.apk";
11584        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11585
11586        String cid;
11587        String packagePath;
11588        String resourcePath;
11589
11590        /** New install */
11591        AsecInstallArgs(InstallParams params) {
11592            super(params.origin, params.move, params.observer, params.installFlags,
11593                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11594                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11595                    params.grantedRuntimePermissions,
11596                    params.traceMethod, params.traceCookie);
11597        }
11598
11599        /** Existing install */
11600        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11601                        boolean isExternal, boolean isForwardLocked) {
11602            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11603                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11604                    instructionSets, null, null, null, 0);
11605            // Hackily pretend we're still looking at a full code path
11606            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11607                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11608            }
11609
11610            // Extract cid from fullCodePath
11611            int eidx = fullCodePath.lastIndexOf("/");
11612            String subStr1 = fullCodePath.substring(0, eidx);
11613            int sidx = subStr1.lastIndexOf("/");
11614            cid = subStr1.substring(sidx+1, eidx);
11615            setMountPath(subStr1);
11616        }
11617
11618        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11619            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11620                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11621                    instructionSets, null, null, null, 0);
11622            this.cid = cid;
11623            setMountPath(PackageHelper.getSdDir(cid));
11624        }
11625
11626        void createCopyFile() {
11627            cid = mInstallerService.allocateExternalStageCidLegacy();
11628        }
11629
11630        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11631            if (origin.staged) {
11632                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11633                cid = origin.cid;
11634                setMountPath(PackageHelper.getSdDir(cid));
11635                return PackageManager.INSTALL_SUCCEEDED;
11636            }
11637
11638            if (temp) {
11639                createCopyFile();
11640            } else {
11641                /*
11642                 * Pre-emptively destroy the container since it's destroyed if
11643                 * copying fails due to it existing anyway.
11644                 */
11645                PackageHelper.destroySdDir(cid);
11646            }
11647
11648            final String newMountPath = imcs.copyPackageToContainer(
11649                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11650                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11651
11652            if (newMountPath != null) {
11653                setMountPath(newMountPath);
11654                return PackageManager.INSTALL_SUCCEEDED;
11655            } else {
11656                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11657            }
11658        }
11659
11660        @Override
11661        String getCodePath() {
11662            return packagePath;
11663        }
11664
11665        @Override
11666        String getResourcePath() {
11667            return resourcePath;
11668        }
11669
11670        int doPreInstall(int status) {
11671            if (status != PackageManager.INSTALL_SUCCEEDED) {
11672                // Destroy container
11673                PackageHelper.destroySdDir(cid);
11674            } else {
11675                boolean mounted = PackageHelper.isContainerMounted(cid);
11676                if (!mounted) {
11677                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11678                            Process.SYSTEM_UID);
11679                    if (newMountPath != null) {
11680                        setMountPath(newMountPath);
11681                    } else {
11682                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11683                    }
11684                }
11685            }
11686            return status;
11687        }
11688
11689        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11690            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11691            String newMountPath = null;
11692            if (PackageHelper.isContainerMounted(cid)) {
11693                // Unmount the container
11694                if (!PackageHelper.unMountSdDir(cid)) {
11695                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11696                    return false;
11697                }
11698            }
11699            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11700                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11701                        " which might be stale. Will try to clean up.");
11702                // Clean up the stale container and proceed to recreate.
11703                if (!PackageHelper.destroySdDir(newCacheId)) {
11704                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11705                    return false;
11706                }
11707                // Successfully cleaned up stale container. Try to rename again.
11708                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11709                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11710                            + " inspite of cleaning it up.");
11711                    return false;
11712                }
11713            }
11714            if (!PackageHelper.isContainerMounted(newCacheId)) {
11715                Slog.w(TAG, "Mounting container " + newCacheId);
11716                newMountPath = PackageHelper.mountSdDir(newCacheId,
11717                        getEncryptKey(), Process.SYSTEM_UID);
11718            } else {
11719                newMountPath = PackageHelper.getSdDir(newCacheId);
11720            }
11721            if (newMountPath == null) {
11722                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11723                return false;
11724            }
11725            Log.i(TAG, "Succesfully renamed " + cid +
11726                    " to " + newCacheId +
11727                    " at new path: " + newMountPath);
11728            cid = newCacheId;
11729
11730            final File beforeCodeFile = new File(packagePath);
11731            setMountPath(newMountPath);
11732            final File afterCodeFile = new File(packagePath);
11733
11734            // Reflect the rename in scanned details
11735            pkg.codePath = afterCodeFile.getAbsolutePath();
11736            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11737                    pkg.baseCodePath);
11738            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11739                    pkg.splitCodePaths);
11740
11741            // Reflect the rename in app info
11742            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11743            pkg.applicationInfo.setCodePath(pkg.codePath);
11744            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11745            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11746            pkg.applicationInfo.setResourcePath(pkg.codePath);
11747            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11748            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11749
11750            return true;
11751        }
11752
11753        private void setMountPath(String mountPath) {
11754            final File mountFile = new File(mountPath);
11755
11756            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11757            if (monolithicFile.exists()) {
11758                packagePath = monolithicFile.getAbsolutePath();
11759                if (isFwdLocked()) {
11760                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11761                } else {
11762                    resourcePath = packagePath;
11763                }
11764            } else {
11765                packagePath = mountFile.getAbsolutePath();
11766                resourcePath = packagePath;
11767            }
11768        }
11769
11770        int doPostInstall(int status, int uid) {
11771            if (status != PackageManager.INSTALL_SUCCEEDED) {
11772                cleanUp();
11773            } else {
11774                final int groupOwner;
11775                final String protectedFile;
11776                if (isFwdLocked()) {
11777                    groupOwner = UserHandle.getSharedAppGid(uid);
11778                    protectedFile = RES_FILE_NAME;
11779                } else {
11780                    groupOwner = -1;
11781                    protectedFile = null;
11782                }
11783
11784                if (uid < Process.FIRST_APPLICATION_UID
11785                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11786                    Slog.e(TAG, "Failed to finalize " + cid);
11787                    PackageHelper.destroySdDir(cid);
11788                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11789                }
11790
11791                boolean mounted = PackageHelper.isContainerMounted(cid);
11792                if (!mounted) {
11793                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11794                }
11795            }
11796            return status;
11797        }
11798
11799        private void cleanUp() {
11800            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11801
11802            // Destroy secure container
11803            PackageHelper.destroySdDir(cid);
11804        }
11805
11806        private List<String> getAllCodePaths() {
11807            final File codeFile = new File(getCodePath());
11808            if (codeFile != null && codeFile.exists()) {
11809                try {
11810                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11811                    return pkg.getAllCodePaths();
11812                } catch (PackageParserException e) {
11813                    // Ignored; we tried our best
11814                }
11815            }
11816            return Collections.EMPTY_LIST;
11817        }
11818
11819        void cleanUpResourcesLI() {
11820            // Enumerate all code paths before deleting
11821            cleanUpResourcesLI(getAllCodePaths());
11822        }
11823
11824        private void cleanUpResourcesLI(List<String> allCodePaths) {
11825            cleanUp();
11826            removeDexFiles(allCodePaths, instructionSets);
11827        }
11828
11829        String getPackageName() {
11830            return getAsecPackageName(cid);
11831        }
11832
11833        boolean doPostDeleteLI(boolean delete) {
11834            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11835            final List<String> allCodePaths = getAllCodePaths();
11836            boolean mounted = PackageHelper.isContainerMounted(cid);
11837            if (mounted) {
11838                // Unmount first
11839                if (PackageHelper.unMountSdDir(cid)) {
11840                    mounted = false;
11841                }
11842            }
11843            if (!mounted && delete) {
11844                cleanUpResourcesLI(allCodePaths);
11845            }
11846            return !mounted;
11847        }
11848
11849        @Override
11850        int doPreCopy() {
11851            if (isFwdLocked()) {
11852                if (!PackageHelper.fixSdPermissions(cid,
11853                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11854                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11855                }
11856            }
11857
11858            return PackageManager.INSTALL_SUCCEEDED;
11859        }
11860
11861        @Override
11862        int doPostCopy(int uid) {
11863            if (isFwdLocked()) {
11864                if (uid < Process.FIRST_APPLICATION_UID
11865                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11866                                RES_FILE_NAME)) {
11867                    Slog.e(TAG, "Failed to finalize " + cid);
11868                    PackageHelper.destroySdDir(cid);
11869                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11870                }
11871            }
11872
11873            return PackageManager.INSTALL_SUCCEEDED;
11874        }
11875    }
11876
11877    /**
11878     * Logic to handle movement of existing installed applications.
11879     */
11880    class MoveInstallArgs extends InstallArgs {
11881        private File codeFile;
11882        private File resourceFile;
11883
11884        /** New install */
11885        MoveInstallArgs(InstallParams params) {
11886            super(params.origin, params.move, params.observer, params.installFlags,
11887                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11888                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11889                    params.grantedRuntimePermissions,
11890                    params.traceMethod, params.traceCookie);
11891        }
11892
11893        int copyApk(IMediaContainerService imcs, boolean temp) {
11894            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11895                    + move.fromUuid + " to " + move.toUuid);
11896            synchronized (mInstaller) {
11897                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11898                        move.dataAppName, move.appId, move.seinfo) != 0) {
11899                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11900                }
11901            }
11902
11903            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11904            resourceFile = codeFile;
11905            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11906
11907            return PackageManager.INSTALL_SUCCEEDED;
11908        }
11909
11910        int doPreInstall(int status) {
11911            if (status != PackageManager.INSTALL_SUCCEEDED) {
11912                cleanUp(move.toUuid);
11913            }
11914            return status;
11915        }
11916
11917        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11918            if (status != PackageManager.INSTALL_SUCCEEDED) {
11919                cleanUp(move.toUuid);
11920                return false;
11921            }
11922
11923            // Reflect the move in app info
11924            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11925            pkg.applicationInfo.setCodePath(pkg.codePath);
11926            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11927            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11928            pkg.applicationInfo.setResourcePath(pkg.codePath);
11929            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11930            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11931
11932            return true;
11933        }
11934
11935        int doPostInstall(int status, int uid) {
11936            if (status == PackageManager.INSTALL_SUCCEEDED) {
11937                cleanUp(move.fromUuid);
11938            } else {
11939                cleanUp(move.toUuid);
11940            }
11941            return status;
11942        }
11943
11944        @Override
11945        String getCodePath() {
11946            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11947        }
11948
11949        @Override
11950        String getResourcePath() {
11951            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11952        }
11953
11954        private boolean cleanUp(String volumeUuid) {
11955            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11956                    move.dataAppName);
11957            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11958            synchronized (mInstallLock) {
11959                // Clean up both app data and code
11960                removeDataDirsLI(volumeUuid, move.packageName);
11961                if (codeFile.isDirectory()) {
11962                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11963                } else {
11964                    codeFile.delete();
11965                }
11966            }
11967            return true;
11968        }
11969
11970        void cleanUpResourcesLI() {
11971            throw new UnsupportedOperationException();
11972        }
11973
11974        boolean doPostDeleteLI(boolean delete) {
11975            throw new UnsupportedOperationException();
11976        }
11977    }
11978
11979    static String getAsecPackageName(String packageCid) {
11980        int idx = packageCid.lastIndexOf("-");
11981        if (idx == -1) {
11982            return packageCid;
11983        }
11984        return packageCid.substring(0, idx);
11985    }
11986
11987    // Utility method used to create code paths based on package name and available index.
11988    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11989        String idxStr = "";
11990        int idx = 1;
11991        // Fall back to default value of idx=1 if prefix is not
11992        // part of oldCodePath
11993        if (oldCodePath != null) {
11994            String subStr = oldCodePath;
11995            // Drop the suffix right away
11996            if (suffix != null && subStr.endsWith(suffix)) {
11997                subStr = subStr.substring(0, subStr.length() - suffix.length());
11998            }
11999            // If oldCodePath already contains prefix find out the
12000            // ending index to either increment or decrement.
12001            int sidx = subStr.lastIndexOf(prefix);
12002            if (sidx != -1) {
12003                subStr = subStr.substring(sidx + prefix.length());
12004                if (subStr != null) {
12005                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12006                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12007                    }
12008                    try {
12009                        idx = Integer.parseInt(subStr);
12010                        if (idx <= 1) {
12011                            idx++;
12012                        } else {
12013                            idx--;
12014                        }
12015                    } catch(NumberFormatException e) {
12016                    }
12017                }
12018            }
12019        }
12020        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12021        return prefix + idxStr;
12022    }
12023
12024    private File getNextCodePath(File targetDir, String packageName) {
12025        int suffix = 1;
12026        File result;
12027        do {
12028            result = new File(targetDir, packageName + "-" + suffix);
12029            suffix++;
12030        } while (result.exists());
12031        return result;
12032    }
12033
12034    // Utility method that returns the relative package path with respect
12035    // to the installation directory. Like say for /data/data/com.test-1.apk
12036    // string com.test-1 is returned.
12037    static String deriveCodePathName(String codePath) {
12038        if (codePath == null) {
12039            return null;
12040        }
12041        final File codeFile = new File(codePath);
12042        final String name = codeFile.getName();
12043        if (codeFile.isDirectory()) {
12044            return name;
12045        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12046            final int lastDot = name.lastIndexOf('.');
12047            return name.substring(0, lastDot);
12048        } else {
12049            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12050            return null;
12051        }
12052    }
12053
12054    class PackageInstalledInfo {
12055        String name;
12056        int uid;
12057        // The set of users that originally had this package installed.
12058        int[] origUsers;
12059        // The set of users that now have this package installed.
12060        int[] newUsers;
12061        PackageParser.Package pkg;
12062        int returnCode;
12063        String returnMsg;
12064        PackageRemovedInfo removedInfo;
12065
12066        public void setError(int code, String msg) {
12067            returnCode = code;
12068            returnMsg = msg;
12069            Slog.w(TAG, msg);
12070        }
12071
12072        public void setError(String msg, PackageParserException e) {
12073            returnCode = e.error;
12074            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12075            Slog.w(TAG, msg, e);
12076        }
12077
12078        public void setError(String msg, PackageManagerException e) {
12079            returnCode = e.error;
12080            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12081            Slog.w(TAG, msg, e);
12082        }
12083
12084        // In some error cases we want to convey more info back to the observer
12085        String origPackage;
12086        String origPermission;
12087    }
12088
12089    /*
12090     * Install a non-existing package.
12091     */
12092    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12093            UserHandle user, String installerPackageName, String volumeUuid,
12094            PackageInstalledInfo res) {
12095        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12096
12097        // Remember this for later, in case we need to rollback this install
12098        String pkgName = pkg.packageName;
12099
12100        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12101        // TODO: b/23350563
12102        final boolean dataDirExists = Environment
12103                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12104
12105        synchronized(mPackages) {
12106            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12107                // A package with the same name is already installed, though
12108                // it has been renamed to an older name.  The package we
12109                // are trying to install should be installed as an update to
12110                // the existing one, but that has not been requested, so bail.
12111                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12112                        + " without first uninstalling package running as "
12113                        + mSettings.mRenamedPackages.get(pkgName));
12114                return;
12115            }
12116            if (mPackages.containsKey(pkgName)) {
12117                // Don't allow installation over an existing package with the same name.
12118                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12119                        + " without first uninstalling.");
12120                return;
12121            }
12122        }
12123
12124        try {
12125            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12126                    System.currentTimeMillis(), user);
12127
12128            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12129            // delete the partially installed application. the data directory will have to be
12130            // restored if it was already existing
12131            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12132                // remove package from internal structures.  Note that we want deletePackageX to
12133                // delete the package data and cache directories that it created in
12134                // scanPackageLocked, unless those directories existed before we even tried to
12135                // install.
12136                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12137                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12138                                res.removedInfo, true);
12139            }
12140
12141        } catch (PackageManagerException e) {
12142            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12143        }
12144
12145        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12146    }
12147
12148    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12149        // Can't rotate keys during boot or if sharedUser.
12150        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12151                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12152            return false;
12153        }
12154        // app is using upgradeKeySets; make sure all are valid
12155        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12156        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12157        for (int i = 0; i < upgradeKeySets.length; i++) {
12158            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12159                Slog.wtf(TAG, "Package "
12160                         + (oldPs.name != null ? oldPs.name : "<null>")
12161                         + " contains upgrade-key-set reference to unknown key-set: "
12162                         + upgradeKeySets[i]
12163                         + " reverting to signatures check.");
12164                return false;
12165            }
12166        }
12167        return true;
12168    }
12169
12170    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12171        // Upgrade keysets are being used.  Determine if new package has a superset of the
12172        // required keys.
12173        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12174        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12175        for (int i = 0; i < upgradeKeySets.length; i++) {
12176            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12177            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12178                return true;
12179            }
12180        }
12181        return false;
12182    }
12183
12184    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12185            UserHandle user, String installerPackageName, String volumeUuid,
12186            PackageInstalledInfo res) {
12187        final PackageParser.Package oldPackage;
12188        final String pkgName = pkg.packageName;
12189        final int[] allUsers;
12190        final boolean[] perUserInstalled;
12191
12192        // First find the old package info and check signatures
12193        synchronized(mPackages) {
12194            oldPackage = mPackages.get(pkgName);
12195            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12196            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12197            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12198                if(!checkUpgradeKeySetLP(ps, pkg)) {
12199                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12200                            "New package not signed by keys specified by upgrade-keysets: "
12201                            + pkgName);
12202                    return;
12203                }
12204            } else {
12205                // default to original signature matching
12206                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12207                    != PackageManager.SIGNATURE_MATCH) {
12208                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12209                            "New package has a different signature: " + pkgName);
12210                    return;
12211                }
12212            }
12213
12214            // In case of rollback, remember per-user/profile install state
12215            allUsers = sUserManager.getUserIds();
12216            perUserInstalled = new boolean[allUsers.length];
12217            for (int i = 0; i < allUsers.length; i++) {
12218                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12219            }
12220        }
12221
12222        boolean sysPkg = (isSystemApp(oldPackage));
12223        if (sysPkg) {
12224            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12225                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12226        } else {
12227            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12228                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12229        }
12230    }
12231
12232    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12233            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12234            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12235            String volumeUuid, PackageInstalledInfo res) {
12236        String pkgName = deletedPackage.packageName;
12237        boolean deletedPkg = true;
12238        boolean updatedSettings = false;
12239
12240        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12241                + deletedPackage);
12242        long origUpdateTime;
12243        if (pkg.mExtras != null) {
12244            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12245        } else {
12246            origUpdateTime = 0;
12247        }
12248
12249        // First delete the existing package while retaining the data directory
12250        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12251                res.removedInfo, true)) {
12252            // If the existing package wasn't successfully deleted
12253            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12254            deletedPkg = false;
12255        } else {
12256            // Successfully deleted the old package; proceed with replace.
12257
12258            // If deleted package lived in a container, give users a chance to
12259            // relinquish resources before killing.
12260            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12261                if (DEBUG_INSTALL) {
12262                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12263                }
12264                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12265                final ArrayList<String> pkgList = new ArrayList<String>(1);
12266                pkgList.add(deletedPackage.applicationInfo.packageName);
12267                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12268            }
12269
12270            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12271            try {
12272                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12273                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12274                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12275                        perUserInstalled, res, user);
12276                updatedSettings = true;
12277            } catch (PackageManagerException e) {
12278                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12279            }
12280        }
12281
12282        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12283            // remove package from internal structures.  Note that we want deletePackageX to
12284            // delete the package data and cache directories that it created in
12285            // scanPackageLocked, unless those directories existed before we even tried to
12286            // install.
12287            if(updatedSettings) {
12288                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12289                deletePackageLI(
12290                        pkgName, null, true, allUsers, perUserInstalled,
12291                        PackageManager.DELETE_KEEP_DATA,
12292                                res.removedInfo, true);
12293            }
12294            // Since we failed to install the new package we need to restore the old
12295            // package that we deleted.
12296            if (deletedPkg) {
12297                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12298                File restoreFile = new File(deletedPackage.codePath);
12299                // Parse old package
12300                boolean oldExternal = isExternal(deletedPackage);
12301                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12302                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12303                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12304                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12305                try {
12306                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12307                            null);
12308                } catch (PackageManagerException e) {
12309                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12310                            + e.getMessage());
12311                    return;
12312                }
12313                // Restore of old package succeeded. Update permissions.
12314                // writer
12315                synchronized (mPackages) {
12316                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12317                            UPDATE_PERMISSIONS_ALL);
12318                    // can downgrade to reader
12319                    mSettings.writeLPr();
12320                }
12321                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12322            }
12323        }
12324    }
12325
12326    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12327            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12328            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12329            String volumeUuid, PackageInstalledInfo res) {
12330        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12331                + ", old=" + deletedPackage);
12332        boolean disabledSystem = false;
12333        boolean updatedSettings = false;
12334        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12335        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12336                != 0) {
12337            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12338        }
12339        String packageName = deletedPackage.packageName;
12340        if (packageName == null) {
12341            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12342                    "Attempt to delete null packageName.");
12343            return;
12344        }
12345        PackageParser.Package oldPkg;
12346        PackageSetting oldPkgSetting;
12347        // reader
12348        synchronized (mPackages) {
12349            oldPkg = mPackages.get(packageName);
12350            oldPkgSetting = mSettings.mPackages.get(packageName);
12351            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12352                    (oldPkgSetting == null)) {
12353                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12354                        "Couldn't find package:" + packageName + " information");
12355                return;
12356            }
12357        }
12358
12359        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12360
12361        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12362        res.removedInfo.removedPackage = packageName;
12363        // Remove existing system package
12364        removePackageLI(oldPkgSetting, true);
12365        // writer
12366        synchronized (mPackages) {
12367            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12368            if (!disabledSystem && deletedPackage != null) {
12369                // We didn't need to disable the .apk as a current system package,
12370                // which means we are replacing another update that is already
12371                // installed.  We need to make sure to delete the older one's .apk.
12372                res.removedInfo.args = createInstallArgsForExisting(0,
12373                        deletedPackage.applicationInfo.getCodePath(),
12374                        deletedPackage.applicationInfo.getResourcePath(),
12375                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12376            } else {
12377                res.removedInfo.args = null;
12378            }
12379        }
12380
12381        // Successfully disabled the old package. Now proceed with re-installation
12382        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12383
12384        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12385        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12386
12387        PackageParser.Package newPackage = null;
12388        try {
12389            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12390            if (newPackage.mExtras != null) {
12391                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12392                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12393                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12394
12395                // is the update attempting to change shared user? that isn't going to work...
12396                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12397                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12398                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12399                            + " to " + newPkgSetting.sharedUser);
12400                    updatedSettings = true;
12401                }
12402            }
12403
12404            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12405                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12406                        perUserInstalled, res, user);
12407                updatedSettings = true;
12408            }
12409
12410        } catch (PackageManagerException e) {
12411            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12412        }
12413
12414        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12415            // Re installation failed. Restore old information
12416            // Remove new pkg information
12417            if (newPackage != null) {
12418                removeInstalledPackageLI(newPackage, true);
12419            }
12420            // Add back the old system package
12421            try {
12422                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12423            } catch (PackageManagerException e) {
12424                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12425            }
12426            // Restore the old system information in Settings
12427            synchronized (mPackages) {
12428                if (disabledSystem) {
12429                    mSettings.enableSystemPackageLPw(packageName);
12430                }
12431                if (updatedSettings) {
12432                    mSettings.setInstallerPackageName(packageName,
12433                            oldPkgSetting.installerPackageName);
12434                }
12435                mSettings.writeLPr();
12436            }
12437        }
12438    }
12439
12440    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12441        // Collect all used permissions in the UID
12442        ArraySet<String> usedPermissions = new ArraySet<>();
12443        final int packageCount = su.packages.size();
12444        for (int i = 0; i < packageCount; i++) {
12445            PackageSetting ps = su.packages.valueAt(i);
12446            if (ps.pkg == null) {
12447                continue;
12448            }
12449            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12450            for (int j = 0; j < requestedPermCount; j++) {
12451                String permission = ps.pkg.requestedPermissions.get(j);
12452                BasePermission bp = mSettings.mPermissions.get(permission);
12453                if (bp != null) {
12454                    usedPermissions.add(permission);
12455                }
12456            }
12457        }
12458
12459        PermissionsState permissionsState = su.getPermissionsState();
12460        // Prune install permissions
12461        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12462        final int installPermCount = installPermStates.size();
12463        for (int i = installPermCount - 1; i >= 0;  i--) {
12464            PermissionState permissionState = installPermStates.get(i);
12465            if (!usedPermissions.contains(permissionState.getName())) {
12466                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12467                if (bp != null) {
12468                    permissionsState.revokeInstallPermission(bp);
12469                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12470                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12471                }
12472            }
12473        }
12474
12475        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12476
12477        // Prune runtime permissions
12478        for (int userId : allUserIds) {
12479            List<PermissionState> runtimePermStates = permissionsState
12480                    .getRuntimePermissionStates(userId);
12481            final int runtimePermCount = runtimePermStates.size();
12482            for (int i = runtimePermCount - 1; i >= 0; i--) {
12483                PermissionState permissionState = runtimePermStates.get(i);
12484                if (!usedPermissions.contains(permissionState.getName())) {
12485                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12486                    if (bp != null) {
12487                        permissionsState.revokeRuntimePermission(bp, userId);
12488                        permissionsState.updatePermissionFlags(bp, userId,
12489                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12490                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12491                                runtimePermissionChangedUserIds, userId);
12492                    }
12493                }
12494            }
12495        }
12496
12497        return runtimePermissionChangedUserIds;
12498    }
12499
12500    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12501            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12502            UserHandle user) {
12503        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12504
12505        String pkgName = newPackage.packageName;
12506        synchronized (mPackages) {
12507            //write settings. the installStatus will be incomplete at this stage.
12508            //note that the new package setting would have already been
12509            //added to mPackages. It hasn't been persisted yet.
12510            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12511            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12512            mSettings.writeLPr();
12513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12514        }
12515
12516        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12517        synchronized (mPackages) {
12518            updatePermissionsLPw(newPackage.packageName, newPackage,
12519                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12520                            ? UPDATE_PERMISSIONS_ALL : 0));
12521            // For system-bundled packages, we assume that installing an upgraded version
12522            // of the package implies that the user actually wants to run that new code,
12523            // so we enable the package.
12524            PackageSetting ps = mSettings.mPackages.get(pkgName);
12525            if (ps != null) {
12526                if (isSystemApp(newPackage)) {
12527                    // NB: implicit assumption that system package upgrades apply to all users
12528                    if (DEBUG_INSTALL) {
12529                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12530                    }
12531                    if (res.origUsers != null) {
12532                        for (int userHandle : res.origUsers) {
12533                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12534                                    userHandle, installerPackageName);
12535                        }
12536                    }
12537                    // Also convey the prior install/uninstall state
12538                    if (allUsers != null && perUserInstalled != null) {
12539                        for (int i = 0; i < allUsers.length; i++) {
12540                            if (DEBUG_INSTALL) {
12541                                Slog.d(TAG, "    user " + allUsers[i]
12542                                        + " => " + perUserInstalled[i]);
12543                            }
12544                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12545                        }
12546                        // these install state changes will be persisted in the
12547                        // upcoming call to mSettings.writeLPr().
12548                    }
12549                }
12550                // It's implied that when a user requests installation, they want the app to be
12551                // installed and enabled.
12552                int userId = user.getIdentifier();
12553                if (userId != UserHandle.USER_ALL) {
12554                    ps.setInstalled(true, userId);
12555                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12556                }
12557            }
12558            res.name = pkgName;
12559            res.uid = newPackage.applicationInfo.uid;
12560            res.pkg = newPackage;
12561            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12562            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12563            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12564            //to update install status
12565            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12566            mSettings.writeLPr();
12567            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12568        }
12569
12570        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12571    }
12572
12573    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12574        try {
12575            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12576            installPackageLI(args, res);
12577        } finally {
12578            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12579        }
12580    }
12581
12582    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12583        final int installFlags = args.installFlags;
12584        final String installerPackageName = args.installerPackageName;
12585        final String volumeUuid = args.volumeUuid;
12586        final File tmpPackageFile = new File(args.getCodePath());
12587        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12588        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12589                || (args.volumeUuid != null));
12590        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12591        boolean replace = false;
12592        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12593        if (args.move != null) {
12594            // moving a complete application; perfom an initial scan on the new install location
12595            scanFlags |= SCAN_INITIAL;
12596        }
12597        // Result object to be returned
12598        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12599
12600        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12601
12602        // Retrieve PackageSettings and parse package
12603        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12604                | PackageParser.PARSE_ENFORCE_CODE
12605                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12606                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12607                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0);
12608        PackageParser pp = new PackageParser();
12609        pp.setSeparateProcesses(mSeparateProcesses);
12610        pp.setDisplayMetrics(mMetrics);
12611
12612        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12613        final PackageParser.Package pkg;
12614        try {
12615            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12616        } catch (PackageParserException e) {
12617            res.setError("Failed parse during installPackageLI", e);
12618            return;
12619        } finally {
12620            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12621        }
12622
12623        // Mark that we have an install time CPU ABI override.
12624        pkg.cpuAbiOverride = args.abiOverride;
12625
12626        String pkgName = res.name = pkg.packageName;
12627        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12628            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12629                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12630                return;
12631            }
12632        }
12633
12634        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12635        try {
12636            pp.collectCertificates(pkg, parseFlags);
12637        } catch (PackageParserException e) {
12638            res.setError("Failed collect during installPackageLI", e);
12639            return;
12640        } finally {
12641            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12642        }
12643
12644        /* If the installer passed in a manifest digest, compare it now. */
12645        if (args.manifestDigest != null) {
12646            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12647            try {
12648                pp.collectManifestDigest(pkg);
12649            } catch (PackageParserException e) {
12650                res.setError("Failed collect during installPackageLI", e);
12651                return;
12652            } finally {
12653                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12654            }
12655
12656            if (DEBUG_INSTALL) {
12657                final String parsedManifest = pkg.manifestDigest == null ? "null"
12658                        : pkg.manifestDigest.toString();
12659                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12660                        + parsedManifest);
12661            }
12662
12663            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12664                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12665                return;
12666            }
12667        } else if (DEBUG_INSTALL) {
12668            final String parsedManifest = pkg.manifestDigest == null
12669                    ? "null" : pkg.manifestDigest.toString();
12670            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12671        }
12672
12673        // Get rid of all references to package scan path via parser.
12674        pp = null;
12675        String oldCodePath = null;
12676        boolean systemApp = false;
12677        synchronized (mPackages) {
12678            // Check if installing already existing package
12679            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12680                String oldName = mSettings.mRenamedPackages.get(pkgName);
12681                if (pkg.mOriginalPackages != null
12682                        && pkg.mOriginalPackages.contains(oldName)
12683                        && mPackages.containsKey(oldName)) {
12684                    // This package is derived from an original package,
12685                    // and this device has been updating from that original
12686                    // name.  We must continue using the original name, so
12687                    // rename the new package here.
12688                    pkg.setPackageName(oldName);
12689                    pkgName = pkg.packageName;
12690                    replace = true;
12691                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12692                            + oldName + " pkgName=" + pkgName);
12693                } else if (mPackages.containsKey(pkgName)) {
12694                    // This package, under its official name, already exists
12695                    // on the device; we should replace it.
12696                    replace = true;
12697                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12698                }
12699
12700                // Prevent apps opting out from runtime permissions
12701                if (replace) {
12702                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12703                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12704                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12705                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12706                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12707                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12708                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12709                                        + " doesn't support runtime permissions but the old"
12710                                        + " target SDK " + oldTargetSdk + " does.");
12711                        return;
12712                    }
12713                }
12714            }
12715
12716            PackageSetting ps = mSettings.mPackages.get(pkgName);
12717            if (ps != null) {
12718                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12719
12720                // Quick sanity check that we're signed correctly if updating;
12721                // we'll check this again later when scanning, but we want to
12722                // bail early here before tripping over redefined permissions.
12723                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12724                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12725                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12726                                + pkg.packageName + " upgrade keys do not match the "
12727                                + "previously installed version");
12728                        return;
12729                    }
12730                } else {
12731                    try {
12732                        verifySignaturesLP(ps, pkg);
12733                    } catch (PackageManagerException e) {
12734                        res.setError(e.error, e.getMessage());
12735                        return;
12736                    }
12737                }
12738
12739                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12740                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12741                    systemApp = (ps.pkg.applicationInfo.flags &
12742                            ApplicationInfo.FLAG_SYSTEM) != 0;
12743                }
12744                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12745            }
12746
12747            // Check whether the newly-scanned package wants to define an already-defined perm
12748            int N = pkg.permissions.size();
12749            for (int i = N-1; i >= 0; i--) {
12750                PackageParser.Permission perm = pkg.permissions.get(i);
12751                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12752                if (bp != null) {
12753                    // If the defining package is signed with our cert, it's okay.  This
12754                    // also includes the "updating the same package" case, of course.
12755                    // "updating same package" could also involve key-rotation.
12756                    final boolean sigsOk;
12757                    if (bp.sourcePackage.equals(pkg.packageName)
12758                            && (bp.packageSetting instanceof PackageSetting)
12759                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12760                                    scanFlags))) {
12761                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12762                    } else {
12763                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12764                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12765                    }
12766                    if (!sigsOk) {
12767                        // If the owning package is the system itself, we log but allow
12768                        // install to proceed; we fail the install on all other permission
12769                        // redefinitions.
12770                        if (!bp.sourcePackage.equals("android")) {
12771                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12772                                    + pkg.packageName + " attempting to redeclare permission "
12773                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12774                            res.origPermission = perm.info.name;
12775                            res.origPackage = bp.sourcePackage;
12776                            return;
12777                        } else {
12778                            Slog.w(TAG, "Package " + pkg.packageName
12779                                    + " attempting to redeclare system permission "
12780                                    + perm.info.name + "; ignoring new declaration");
12781                            pkg.permissions.remove(i);
12782                        }
12783                    }
12784                }
12785            }
12786
12787        }
12788
12789        if (systemApp && onExternal) {
12790            // Disable updates to system apps on sdcard
12791            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12792                    "Cannot install updates to system apps on sdcard");
12793            return;
12794        }
12795
12796        if (args.move != null) {
12797            // We did an in-place move, so dex is ready to roll
12798            scanFlags |= SCAN_NO_DEX;
12799            scanFlags |= SCAN_MOVE;
12800
12801            synchronized (mPackages) {
12802                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12803                if (ps == null) {
12804                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12805                            "Missing settings for moved package " + pkgName);
12806                }
12807
12808                // We moved the entire application as-is, so bring over the
12809                // previously derived ABI information.
12810                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12811                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12812            }
12813
12814        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12815            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12816            scanFlags |= SCAN_NO_DEX;
12817
12818            try {
12819                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12820                        true /* extract libs */);
12821            } catch (PackageManagerException pme) {
12822                Slog.e(TAG, "Error deriving application ABI", pme);
12823                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12824                return;
12825            }
12826        }
12827
12828        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12829            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12830            return;
12831        }
12832
12833        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12834
12835        if (replace) {
12836            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12837                    installerPackageName, volumeUuid, res);
12838        } else {
12839            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12840                    args.user, installerPackageName, volumeUuid, res);
12841        }
12842        synchronized (mPackages) {
12843            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12844            if (ps != null) {
12845                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12846            }
12847        }
12848    }
12849
12850    private void startIntentFilterVerifications(int userId, boolean replacing,
12851            PackageParser.Package pkg) {
12852        if (mIntentFilterVerifierComponent == null) {
12853            Slog.w(TAG, "No IntentFilter verification will not be done as "
12854                    + "there is no IntentFilterVerifier available!");
12855            return;
12856        }
12857
12858        final int verifierUid = getPackageUid(
12859                mIntentFilterVerifierComponent.getPackageName(),
12860                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12861
12862        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12863        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12864        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12865        mHandler.sendMessage(msg);
12866    }
12867
12868    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12869            PackageParser.Package pkg) {
12870        int size = pkg.activities.size();
12871        if (size == 0) {
12872            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12873                    "No activity, so no need to verify any IntentFilter!");
12874            return;
12875        }
12876
12877        final boolean hasDomainURLs = hasDomainURLs(pkg);
12878        if (!hasDomainURLs) {
12879            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12880                    "No domain URLs, so no need to verify any IntentFilter!");
12881            return;
12882        }
12883
12884        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12885                + " if any IntentFilter from the " + size
12886                + " Activities needs verification ...");
12887
12888        int count = 0;
12889        final String packageName = pkg.packageName;
12890
12891        synchronized (mPackages) {
12892            // If this is a new install and we see that we've already run verification for this
12893            // package, we have nothing to do: it means the state was restored from backup.
12894            if (!replacing) {
12895                IntentFilterVerificationInfo ivi =
12896                        mSettings.getIntentFilterVerificationLPr(packageName);
12897                if (ivi != null) {
12898                    if (DEBUG_DOMAIN_VERIFICATION) {
12899                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12900                                + ivi.getStatusString());
12901                    }
12902                    return;
12903                }
12904            }
12905
12906            // If any filters need to be verified, then all need to be.
12907            boolean needToVerify = false;
12908            for (PackageParser.Activity a : pkg.activities) {
12909                for (ActivityIntentInfo filter : a.intents) {
12910                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12911                        if (DEBUG_DOMAIN_VERIFICATION) {
12912                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12913                        }
12914                        needToVerify = true;
12915                        break;
12916                    }
12917                }
12918            }
12919
12920            if (needToVerify) {
12921                final int verificationId = mIntentFilterVerificationToken++;
12922                for (PackageParser.Activity a : pkg.activities) {
12923                    for (ActivityIntentInfo filter : a.intents) {
12924                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12925                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12926                                    "Verification needed for IntentFilter:" + filter.toString());
12927                            mIntentFilterVerifier.addOneIntentFilterVerification(
12928                                    verifierUid, userId, verificationId, filter, packageName);
12929                            count++;
12930                        }
12931                    }
12932                }
12933            }
12934        }
12935
12936        if (count > 0) {
12937            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12938                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12939                    +  " for userId:" + userId);
12940            mIntentFilterVerifier.startVerifications(userId);
12941        } else {
12942            if (DEBUG_DOMAIN_VERIFICATION) {
12943                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12944            }
12945        }
12946    }
12947
12948    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12949        final ComponentName cn  = filter.activity.getComponentName();
12950        final String packageName = cn.getPackageName();
12951
12952        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12953                packageName);
12954        if (ivi == null) {
12955            return true;
12956        }
12957        int status = ivi.getStatus();
12958        switch (status) {
12959            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12960            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12961                return true;
12962
12963            default:
12964                // Nothing to do
12965                return false;
12966        }
12967    }
12968
12969    private static boolean isMultiArch(PackageSetting ps) {
12970        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12971    }
12972
12973    private static boolean isMultiArch(ApplicationInfo info) {
12974        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12975    }
12976
12977    private static boolean isExternal(PackageParser.Package pkg) {
12978        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12979    }
12980
12981    private static boolean isExternal(PackageSetting ps) {
12982        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12983    }
12984
12985    private static boolean isExternal(ApplicationInfo info) {
12986        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12987    }
12988
12989    private static boolean isSystemApp(PackageParser.Package pkg) {
12990        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12991    }
12992
12993    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12994        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12995    }
12996
12997    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12998        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12999    }
13000
13001    private static boolean isSystemApp(PackageSetting ps) {
13002        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13003    }
13004
13005    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13006        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13007    }
13008
13009    private int packageFlagsToInstallFlags(PackageSetting ps) {
13010        int installFlags = 0;
13011        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13012            // This existing package was an external ASEC install when we have
13013            // the external flag without a UUID
13014            installFlags |= PackageManager.INSTALL_EXTERNAL;
13015        }
13016        if (ps.isForwardLocked()) {
13017            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13018        }
13019        return installFlags;
13020    }
13021
13022    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13023        if (isExternal(pkg)) {
13024            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13025                return StorageManager.UUID_PRIMARY_PHYSICAL;
13026            } else {
13027                return pkg.volumeUuid;
13028            }
13029        } else {
13030            return StorageManager.UUID_PRIVATE_INTERNAL;
13031        }
13032    }
13033
13034    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13035        if (isExternal(pkg)) {
13036            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13037                return mSettings.getExternalVersion();
13038            } else {
13039                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13040            }
13041        } else {
13042            return mSettings.getInternalVersion();
13043        }
13044    }
13045
13046    private void deleteTempPackageFiles() {
13047        final FilenameFilter filter = new FilenameFilter() {
13048            public boolean accept(File dir, String name) {
13049                return name.startsWith("vmdl") && name.endsWith(".tmp");
13050            }
13051        };
13052        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13053            file.delete();
13054        }
13055    }
13056
13057    @Override
13058    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13059            int flags) {
13060        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13061                flags);
13062    }
13063
13064    @Override
13065    public void deletePackage(final String packageName,
13066            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13067        mContext.enforceCallingOrSelfPermission(
13068                android.Manifest.permission.DELETE_PACKAGES, null);
13069        Preconditions.checkNotNull(packageName);
13070        Preconditions.checkNotNull(observer);
13071        final int uid = Binder.getCallingUid();
13072        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13073        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13074        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13075            mContext.enforceCallingOrSelfPermission(
13076                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13077                    "deletePackage for user " + userId);
13078        }
13079
13080        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13081            try {
13082                observer.onPackageDeleted(packageName,
13083                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13084            } catch (RemoteException re) {
13085            }
13086            return;
13087        }
13088
13089        for (int currentUserId : users) {
13090            if (getBlockUninstallForUser(packageName, currentUserId)) {
13091                try {
13092                    observer.onPackageDeleted(packageName,
13093                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13094                } catch (RemoteException re) {
13095                }
13096                return;
13097            }
13098        }
13099
13100        if (DEBUG_REMOVE) {
13101            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13102        }
13103        // Queue up an async operation since the package deletion may take a little while.
13104        mHandler.post(new Runnable() {
13105            public void run() {
13106                mHandler.removeCallbacks(this);
13107                final int returnCode = deletePackageX(packageName, userId, flags);
13108                try {
13109                    observer.onPackageDeleted(packageName, returnCode, null);
13110                } catch (RemoteException e) {
13111                    Log.i(TAG, "Observer no longer exists.");
13112                } //end catch
13113            } //end run
13114        });
13115    }
13116
13117    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13118        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13119                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13120        try {
13121            if (dpm != null) {
13122                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13123                        /* callingUserOnly =*/ false);
13124                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13125                        : deviceOwnerComponentName.getPackageName();
13126                // Does the package contains the device owner?
13127                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13128                // this check is probably not needed, since DO should be registered as a device
13129                // admin on some user too. (Original bug for this: b/17657954)
13130                if (packageName.equals(deviceOwnerPackageName)) {
13131                    return true;
13132                }
13133                // Does it contain a device admin for any user?
13134                int[] users;
13135                if (userId == UserHandle.USER_ALL) {
13136                    users = sUserManager.getUserIds();
13137                } else {
13138                    users = new int[]{userId};
13139                }
13140                for (int i = 0; i < users.length; ++i) {
13141                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13142                        return true;
13143                    }
13144                }
13145            }
13146        } catch (RemoteException e) {
13147        }
13148        return false;
13149    }
13150
13151    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13152        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13153    }
13154
13155    /**
13156     *  This method is an internal method that could be get invoked either
13157     *  to delete an installed package or to clean up a failed installation.
13158     *  After deleting an installed package, a broadcast is sent to notify any
13159     *  listeners that the package has been installed. For cleaning up a failed
13160     *  installation, the broadcast is not necessary since the package's
13161     *  installation wouldn't have sent the initial broadcast either
13162     *  The key steps in deleting a package are
13163     *  deleting the package information in internal structures like mPackages,
13164     *  deleting the packages base directories through installd
13165     *  updating mSettings to reflect current status
13166     *  persisting settings for later use
13167     *  sending a broadcast if necessary
13168     */
13169    private int deletePackageX(String packageName, int userId, int flags) {
13170        final PackageRemovedInfo info = new PackageRemovedInfo();
13171        final boolean res;
13172
13173        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13174                ? UserHandle.ALL : new UserHandle(userId);
13175
13176        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13177            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13178            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13179        }
13180
13181        boolean removedForAllUsers = false;
13182        boolean systemUpdate = false;
13183
13184        // for the uninstall-updates case and restricted profiles, remember the per-
13185        // userhandle installed state
13186        int[] allUsers;
13187        boolean[] perUserInstalled;
13188        synchronized (mPackages) {
13189            PackageSetting ps = mSettings.mPackages.get(packageName);
13190            allUsers = sUserManager.getUserIds();
13191            perUserInstalled = new boolean[allUsers.length];
13192            for (int i = 0; i < allUsers.length; i++) {
13193                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13194            }
13195        }
13196
13197        synchronized (mInstallLock) {
13198            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13199            res = deletePackageLI(packageName, removeForUser,
13200                    true, allUsers, perUserInstalled,
13201                    flags | REMOVE_CHATTY, info, true);
13202            systemUpdate = info.isRemovedPackageSystemUpdate;
13203            if (res && !systemUpdate && mPackages.get(packageName) == null) {
13204                removedForAllUsers = true;
13205            }
13206            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13207                    + " removedForAllUsers=" + removedForAllUsers);
13208        }
13209
13210        if (res) {
13211            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13212
13213            // If the removed package was a system update, the old system package
13214            // was re-enabled; we need to broadcast this information
13215            if (systemUpdate) {
13216                Bundle extras = new Bundle(1);
13217                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13218                        ? info.removedAppId : info.uid);
13219                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13220
13221                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13222                        extras, 0, null, null, null);
13223                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13224                        extras, 0, null, null, null);
13225                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13226                        null, 0, packageName, null, null);
13227            }
13228        }
13229        // Force a gc here.
13230        Runtime.getRuntime().gc();
13231        // Delete the resources here after sending the broadcast to let
13232        // other processes clean up before deleting resources.
13233        if (info.args != null) {
13234            synchronized (mInstallLock) {
13235                info.args.doPostDeleteLI(true);
13236            }
13237        }
13238
13239        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13240    }
13241
13242    class PackageRemovedInfo {
13243        String removedPackage;
13244        int uid = -1;
13245        int removedAppId = -1;
13246        int[] removedUsers = null;
13247        boolean isRemovedPackageSystemUpdate = false;
13248        // Clean up resources deleted packages.
13249        InstallArgs args = null;
13250
13251        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13252            Bundle extras = new Bundle(1);
13253            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13254            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13255            if (replacing) {
13256                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13257            }
13258            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13259            if (removedPackage != null) {
13260                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13261                        extras, 0, null, null, removedUsers);
13262                if (fullRemove && !replacing) {
13263                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13264                            extras, 0, null, null, removedUsers);
13265                }
13266            }
13267            if (removedAppId >= 0) {
13268                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13269                        removedUsers);
13270            }
13271        }
13272    }
13273
13274    /*
13275     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13276     * flag is not set, the data directory is removed as well.
13277     * make sure this flag is set for partially installed apps. If not its meaningless to
13278     * delete a partially installed application.
13279     */
13280    private void removePackageDataLI(PackageSetting ps,
13281            int[] allUserHandles, boolean[] perUserInstalled,
13282            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13283        String packageName = ps.name;
13284        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13285        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13286        // Retrieve object to delete permissions for shared user later on
13287        final PackageSetting deletedPs;
13288        // reader
13289        synchronized (mPackages) {
13290            deletedPs = mSettings.mPackages.get(packageName);
13291            if (outInfo != null) {
13292                outInfo.removedPackage = packageName;
13293                outInfo.removedUsers = deletedPs != null
13294                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13295                        : null;
13296            }
13297        }
13298        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13299            removeDataDirsLI(ps.volumeUuid, packageName);
13300            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13301        }
13302        // writer
13303        synchronized (mPackages) {
13304            if (deletedPs != null) {
13305                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13306                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13307                    clearDefaultBrowserIfNeeded(packageName);
13308                    if (outInfo != null) {
13309                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13310                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13311                    }
13312                    updatePermissionsLPw(deletedPs.name, null, 0);
13313                    if (deletedPs.sharedUser != null) {
13314                        // Remove permissions associated with package. Since runtime
13315                        // permissions are per user we have to kill the removed package
13316                        // or packages running under the shared user of the removed
13317                        // package if revoking the permissions requested only by the removed
13318                        // package is successful and this causes a change in gids.
13319                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13320                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13321                                    userId);
13322                            if (userIdToKill == UserHandle.USER_ALL
13323                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13324                                // If gids changed for this user, kill all affected packages.
13325                                mHandler.post(new Runnable() {
13326                                    @Override
13327                                    public void run() {
13328                                        // This has to happen with no lock held.
13329                                        killApplication(deletedPs.name, deletedPs.appId,
13330                                                KILL_APP_REASON_GIDS_CHANGED);
13331                                    }
13332                                });
13333                                break;
13334                            }
13335                        }
13336                    }
13337                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13338                }
13339                // make sure to preserve per-user disabled state if this removal was just
13340                // a downgrade of a system app to the factory package
13341                if (allUserHandles != null && perUserInstalled != null) {
13342                    if (DEBUG_REMOVE) {
13343                        Slog.d(TAG, "Propagating install state across downgrade");
13344                    }
13345                    for (int i = 0; i < allUserHandles.length; i++) {
13346                        if (DEBUG_REMOVE) {
13347                            Slog.d(TAG, "    user " + allUserHandles[i]
13348                                    + " => " + perUserInstalled[i]);
13349                        }
13350                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13351                    }
13352                }
13353            }
13354            // can downgrade to reader
13355            if (writeSettings) {
13356                // Save settings now
13357                mSettings.writeLPr();
13358            }
13359        }
13360        if (outInfo != null) {
13361            // A user ID was deleted here. Go through all users and remove it
13362            // from KeyStore.
13363            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13364        }
13365    }
13366
13367    static boolean locationIsPrivileged(File path) {
13368        try {
13369            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13370                    .getCanonicalPath();
13371            return path.getCanonicalPath().startsWith(privilegedAppDir);
13372        } catch (IOException e) {
13373            Slog.e(TAG, "Unable to access code path " + path);
13374        }
13375        return false;
13376    }
13377
13378    /*
13379     * Tries to delete system package.
13380     */
13381    private boolean deleteSystemPackageLI(PackageSetting newPs,
13382            int[] allUserHandles, boolean[] perUserInstalled,
13383            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13384        final boolean applyUserRestrictions
13385                = (allUserHandles != null) && (perUserInstalled != null);
13386        PackageSetting disabledPs = null;
13387        // Confirm if the system package has been updated
13388        // An updated system app can be deleted. This will also have to restore
13389        // the system pkg from system partition
13390        // reader
13391        synchronized (mPackages) {
13392            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13393        }
13394        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13395                + " disabledPs=" + disabledPs);
13396        if (disabledPs == null) {
13397            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13398            return false;
13399        } else if (DEBUG_REMOVE) {
13400            Slog.d(TAG, "Deleting system pkg from data partition");
13401        }
13402        if (DEBUG_REMOVE) {
13403            if (applyUserRestrictions) {
13404                Slog.d(TAG, "Remembering install states:");
13405                for (int i = 0; i < allUserHandles.length; i++) {
13406                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13407                }
13408            }
13409        }
13410        // Delete the updated package
13411        outInfo.isRemovedPackageSystemUpdate = true;
13412        if (disabledPs.versionCode < newPs.versionCode) {
13413            // Delete data for downgrades
13414            flags &= ~PackageManager.DELETE_KEEP_DATA;
13415        } else {
13416            // Preserve data by setting flag
13417            flags |= PackageManager.DELETE_KEEP_DATA;
13418        }
13419        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13420                allUserHandles, perUserInstalled, outInfo, writeSettings);
13421        if (!ret) {
13422            return false;
13423        }
13424        // writer
13425        synchronized (mPackages) {
13426            // Reinstate the old system package
13427            mSettings.enableSystemPackageLPw(newPs.name);
13428            // Remove any native libraries from the upgraded package.
13429            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13430        }
13431        // Install the system package
13432        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13433        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13434        if (locationIsPrivileged(disabledPs.codePath)) {
13435            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13436        }
13437
13438        final PackageParser.Package newPkg;
13439        try {
13440            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13441        } catch (PackageManagerException e) {
13442            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13443            return false;
13444        }
13445
13446        // writer
13447        synchronized (mPackages) {
13448            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13449
13450            // Propagate the permissions state as we do not want to drop on the floor
13451            // runtime permissions. The update permissions method below will take
13452            // care of removing obsolete permissions and grant install permissions.
13453            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13454            updatePermissionsLPw(newPkg.packageName, newPkg,
13455                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13456
13457            if (applyUserRestrictions) {
13458                if (DEBUG_REMOVE) {
13459                    Slog.d(TAG, "Propagating install state across reinstall");
13460                }
13461                for (int i = 0; i < allUserHandles.length; i++) {
13462                    if (DEBUG_REMOVE) {
13463                        Slog.d(TAG, "    user " + allUserHandles[i]
13464                                + " => " + perUserInstalled[i]);
13465                    }
13466                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13467
13468                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13469                }
13470                // Regardless of writeSettings we need to ensure that this restriction
13471                // state propagation is persisted
13472                mSettings.writeAllUsersPackageRestrictionsLPr();
13473            }
13474            // can downgrade to reader here
13475            if (writeSettings) {
13476                mSettings.writeLPr();
13477            }
13478        }
13479        return true;
13480    }
13481
13482    private boolean deleteInstalledPackageLI(PackageSetting ps,
13483            boolean deleteCodeAndResources, int flags,
13484            int[] allUserHandles, boolean[] perUserInstalled,
13485            PackageRemovedInfo outInfo, boolean writeSettings) {
13486        if (outInfo != null) {
13487            outInfo.uid = ps.appId;
13488        }
13489
13490        // Delete package data from internal structures and also remove data if flag is set
13491        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13492
13493        // Delete application code and resources
13494        if (deleteCodeAndResources && (outInfo != null)) {
13495            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13496                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13497            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13498        }
13499        return true;
13500    }
13501
13502    @Override
13503    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13504            int userId) {
13505        mContext.enforceCallingOrSelfPermission(
13506                android.Manifest.permission.DELETE_PACKAGES, null);
13507        synchronized (mPackages) {
13508            PackageSetting ps = mSettings.mPackages.get(packageName);
13509            if (ps == null) {
13510                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13511                return false;
13512            }
13513            if (!ps.getInstalled(userId)) {
13514                // Can't block uninstall for an app that is not installed or enabled.
13515                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13516                return false;
13517            }
13518            ps.setBlockUninstall(blockUninstall, userId);
13519            mSettings.writePackageRestrictionsLPr(userId);
13520        }
13521        return true;
13522    }
13523
13524    @Override
13525    public boolean getBlockUninstallForUser(String packageName, int userId) {
13526        synchronized (mPackages) {
13527            PackageSetting ps = mSettings.mPackages.get(packageName);
13528            if (ps == null) {
13529                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13530                return false;
13531            }
13532            return ps.getBlockUninstall(userId);
13533        }
13534    }
13535
13536    /*
13537     * This method handles package deletion in general
13538     */
13539    private boolean deletePackageLI(String packageName, UserHandle user,
13540            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13541            int flags, PackageRemovedInfo outInfo,
13542            boolean writeSettings) {
13543        if (packageName == null) {
13544            Slog.w(TAG, "Attempt to delete null packageName.");
13545            return false;
13546        }
13547        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13548        PackageSetting ps;
13549        boolean dataOnly = false;
13550        int removeUser = -1;
13551        int appId = -1;
13552        synchronized (mPackages) {
13553            ps = mSettings.mPackages.get(packageName);
13554            if (ps == null) {
13555                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13556                return false;
13557            }
13558            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13559                    && user.getIdentifier() != UserHandle.USER_ALL) {
13560                // The caller is asking that the package only be deleted for a single
13561                // user.  To do this, we just mark its uninstalled state and delete
13562                // its data.  If this is a system app, we only allow this to happen if
13563                // they have set the special DELETE_SYSTEM_APP which requests different
13564                // semantics than normal for uninstalling system apps.
13565                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13566                final int userId = user.getIdentifier();
13567                ps.setUserState(userId,
13568                        COMPONENT_ENABLED_STATE_DEFAULT,
13569                        false, //installed
13570                        true,  //stopped
13571                        true,  //notLaunched
13572                        false, //hidden
13573                        null, null, null,
13574                        false, // blockUninstall
13575                        ps.readUserState(userId).domainVerificationStatus, 0);
13576                if (!isSystemApp(ps)) {
13577                    // Do not uninstall the APK if an app should be cached
13578                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13579                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13580                        // Other user still have this package installed, so all
13581                        // we need to do is clear this user's data and save that
13582                        // it is uninstalled.
13583                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13584                        removeUser = user.getIdentifier();
13585                        appId = ps.appId;
13586                        scheduleWritePackageRestrictionsLocked(removeUser);
13587                    } else {
13588                        // We need to set it back to 'installed' so the uninstall
13589                        // broadcasts will be sent correctly.
13590                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13591                        ps.setInstalled(true, user.getIdentifier());
13592                    }
13593                } else {
13594                    // This is a system app, so we assume that the
13595                    // other users still have this package installed, so all
13596                    // we need to do is clear this user's data and save that
13597                    // it is uninstalled.
13598                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13599                    removeUser = user.getIdentifier();
13600                    appId = ps.appId;
13601                    scheduleWritePackageRestrictionsLocked(removeUser);
13602                }
13603            }
13604        }
13605
13606        if (removeUser >= 0) {
13607            // From above, we determined that we are deleting this only
13608            // for a single user.  Continue the work here.
13609            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13610            if (outInfo != null) {
13611                outInfo.removedPackage = packageName;
13612                outInfo.removedAppId = appId;
13613                outInfo.removedUsers = new int[] {removeUser};
13614            }
13615            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13616            removeKeystoreDataIfNeeded(removeUser, appId);
13617            schedulePackageCleaning(packageName, removeUser, false);
13618            synchronized (mPackages) {
13619                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13620                    scheduleWritePackageRestrictionsLocked(removeUser);
13621                }
13622                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13623            }
13624            return true;
13625        }
13626
13627        if (dataOnly) {
13628            // Delete application data first
13629            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13630            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13631            return true;
13632        }
13633
13634        boolean ret = false;
13635        if (isSystemApp(ps)) {
13636            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13637            // When an updated system application is deleted we delete the existing resources as well and
13638            // fall back to existing code in system partition
13639            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13640                    flags, outInfo, writeSettings);
13641        } else {
13642            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13643            // Kill application pre-emptively especially for apps on sd.
13644            killApplication(packageName, ps.appId, "uninstall pkg");
13645            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13646                    allUserHandles, perUserInstalled,
13647                    outInfo, writeSettings);
13648        }
13649
13650        return ret;
13651    }
13652
13653    private final class ClearStorageConnection implements ServiceConnection {
13654        IMediaContainerService mContainerService;
13655
13656        @Override
13657        public void onServiceConnected(ComponentName name, IBinder service) {
13658            synchronized (this) {
13659                mContainerService = IMediaContainerService.Stub.asInterface(service);
13660                notifyAll();
13661            }
13662        }
13663
13664        @Override
13665        public void onServiceDisconnected(ComponentName name) {
13666        }
13667    }
13668
13669    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13670        final boolean mounted;
13671        if (Environment.isExternalStorageEmulated()) {
13672            mounted = true;
13673        } else {
13674            final String status = Environment.getExternalStorageState();
13675
13676            mounted = status.equals(Environment.MEDIA_MOUNTED)
13677                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13678        }
13679
13680        if (!mounted) {
13681            return;
13682        }
13683
13684        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13685        int[] users;
13686        if (userId == UserHandle.USER_ALL) {
13687            users = sUserManager.getUserIds();
13688        } else {
13689            users = new int[] { userId };
13690        }
13691        final ClearStorageConnection conn = new ClearStorageConnection();
13692        if (mContext.bindServiceAsUser(
13693                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13694            try {
13695                for (int curUser : users) {
13696                    long timeout = SystemClock.uptimeMillis() + 5000;
13697                    synchronized (conn) {
13698                        long now = SystemClock.uptimeMillis();
13699                        while (conn.mContainerService == null && now < timeout) {
13700                            try {
13701                                conn.wait(timeout - now);
13702                            } catch (InterruptedException e) {
13703                            }
13704                        }
13705                    }
13706                    if (conn.mContainerService == null) {
13707                        return;
13708                    }
13709
13710                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13711                    clearDirectory(conn.mContainerService,
13712                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13713                    if (allData) {
13714                        clearDirectory(conn.mContainerService,
13715                                userEnv.buildExternalStorageAppDataDirs(packageName));
13716                        clearDirectory(conn.mContainerService,
13717                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13718                    }
13719                }
13720            } finally {
13721                mContext.unbindService(conn);
13722            }
13723        }
13724    }
13725
13726    @Override
13727    public void clearApplicationUserData(final String packageName,
13728            final IPackageDataObserver observer, final int userId) {
13729        mContext.enforceCallingOrSelfPermission(
13730                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13731        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13732        // Queue up an async operation since the package deletion may take a little while.
13733        mHandler.post(new Runnable() {
13734            public void run() {
13735                mHandler.removeCallbacks(this);
13736                final boolean succeeded;
13737                synchronized (mInstallLock) {
13738                    succeeded = clearApplicationUserDataLI(packageName, userId);
13739                }
13740                clearExternalStorageDataSync(packageName, userId, true);
13741                if (succeeded) {
13742                    // invoke DeviceStorageMonitor's update method to clear any notifications
13743                    DeviceStorageMonitorInternal
13744                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13745                    if (dsm != null) {
13746                        dsm.checkMemory();
13747                    }
13748                }
13749                if(observer != null) {
13750                    try {
13751                        observer.onRemoveCompleted(packageName, succeeded);
13752                    } catch (RemoteException e) {
13753                        Log.i(TAG, "Observer no longer exists.");
13754                    }
13755                } //end if observer
13756            } //end run
13757        });
13758    }
13759
13760    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13761        if (packageName == null) {
13762            Slog.w(TAG, "Attempt to delete null packageName.");
13763            return false;
13764        }
13765
13766        // Try finding details about the requested package
13767        PackageParser.Package pkg;
13768        synchronized (mPackages) {
13769            pkg = mPackages.get(packageName);
13770            if (pkg == null) {
13771                final PackageSetting ps = mSettings.mPackages.get(packageName);
13772                if (ps != null) {
13773                    pkg = ps.pkg;
13774                }
13775            }
13776
13777            if (pkg == null) {
13778                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13779                return false;
13780            }
13781
13782            PackageSetting ps = (PackageSetting) pkg.mExtras;
13783            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13784        }
13785
13786        // Always delete data directories for package, even if we found no other
13787        // record of app. This helps users recover from UID mismatches without
13788        // resorting to a full data wipe.
13789        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13790        if (retCode < 0) {
13791            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13792            return false;
13793        }
13794
13795        final int appId = pkg.applicationInfo.uid;
13796        removeKeystoreDataIfNeeded(userId, appId);
13797
13798        // Create a native library symlink only if we have native libraries
13799        // and if the native libraries are 32 bit libraries. We do not provide
13800        // this symlink for 64 bit libraries.
13801        if (pkg.applicationInfo.primaryCpuAbi != null &&
13802                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13803            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13804            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13805                    nativeLibPath, userId) < 0) {
13806                Slog.w(TAG, "Failed linking native library dir");
13807                return false;
13808            }
13809        }
13810
13811        return true;
13812    }
13813
13814    /**
13815     * Reverts user permission state changes (permissions and flags) in
13816     * all packages for a given user.
13817     *
13818     * @param userId The device user for which to do a reset.
13819     */
13820    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13821        final int packageCount = mPackages.size();
13822        for (int i = 0; i < packageCount; i++) {
13823            PackageParser.Package pkg = mPackages.valueAt(i);
13824            PackageSetting ps = (PackageSetting) pkg.mExtras;
13825            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13826        }
13827    }
13828
13829    /**
13830     * Reverts user permission state changes (permissions and flags).
13831     *
13832     * @param ps The package for which to reset.
13833     * @param userId The device user for which to do a reset.
13834     */
13835    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13836            final PackageSetting ps, final int userId) {
13837        if (ps.pkg == null) {
13838            return;
13839        }
13840
13841        // These are flags that can change base on user actions.
13842        final int userSettableMask = FLAG_PERMISSION_USER_SET
13843                | FLAG_PERMISSION_USER_FIXED
13844                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
13845                | FLAG_PERMISSION_REVIEW_REQUIRED;
13846
13847        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13848                | FLAG_PERMISSION_POLICY_FIXED;
13849
13850        boolean writeInstallPermissions = false;
13851        boolean writeRuntimePermissions = false;
13852
13853        final int permissionCount = ps.pkg.requestedPermissions.size();
13854        for (int i = 0; i < permissionCount; i++) {
13855            String permission = ps.pkg.requestedPermissions.get(i);
13856
13857            BasePermission bp = mSettings.mPermissions.get(permission);
13858            if (bp == null) {
13859                continue;
13860            }
13861
13862            // If shared user we just reset the state to which only this app contributed.
13863            if (ps.sharedUser != null) {
13864                boolean used = false;
13865                final int packageCount = ps.sharedUser.packages.size();
13866                for (int j = 0; j < packageCount; j++) {
13867                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13868                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13869                            && pkg.pkg.requestedPermissions.contains(permission)) {
13870                        used = true;
13871                        break;
13872                    }
13873                }
13874                if (used) {
13875                    continue;
13876                }
13877            }
13878
13879            PermissionsState permissionsState = ps.getPermissionsState();
13880
13881            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13882
13883            // Always clear the user settable flags.
13884            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13885                    bp.name) != null;
13886            // If permission review is enabled and this is a legacy app, mark the
13887            // permission as requiring a review as this is the initial state.
13888            int flags = 0;
13889            if (Build.PERMISSIONS_REVIEW_REQUIRED
13890                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13891                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13892            }
13893            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
13894                if (hasInstallState) {
13895                    writeInstallPermissions = true;
13896                } else {
13897                    writeRuntimePermissions = true;
13898                }
13899            }
13900
13901            // Below is only runtime permission handling.
13902            if (!bp.isRuntime()) {
13903                continue;
13904            }
13905
13906            // Never clobber system or policy.
13907            if ((oldFlags & policyOrSystemFlags) != 0) {
13908                continue;
13909            }
13910
13911            // If this permission was granted by default, make sure it is.
13912            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13913                if (permissionsState.grantRuntimePermission(bp, userId)
13914                        != PERMISSION_OPERATION_FAILURE) {
13915                    writeRuntimePermissions = true;
13916                }
13917            // If permission review is enabled the permissions for a legacy apps
13918            // are represented as constantly granted runtime ones, so don't revoke.
13919            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13920                // Otherwise, reset the permission.
13921                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13922                switch (revokeResult) {
13923                    case PERMISSION_OPERATION_SUCCESS: {
13924                        writeRuntimePermissions = true;
13925                    } break;
13926
13927                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13928                        writeRuntimePermissions = true;
13929                        final int appId = ps.appId;
13930                        mHandler.post(new Runnable() {
13931                            @Override
13932                            public void run() {
13933                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13934                            }
13935                        });
13936                    } break;
13937                }
13938            }
13939        }
13940
13941        // Synchronously write as we are taking permissions away.
13942        if (writeRuntimePermissions) {
13943            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13944        }
13945
13946        // Synchronously write as we are taking permissions away.
13947        if (writeInstallPermissions) {
13948            mSettings.writeLPr();
13949        }
13950    }
13951
13952    /**
13953     * Remove entries from the keystore daemon. Will only remove it if the
13954     * {@code appId} is valid.
13955     */
13956    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13957        if (appId < 0) {
13958            return;
13959        }
13960
13961        final KeyStore keyStore = KeyStore.getInstance();
13962        if (keyStore != null) {
13963            if (userId == UserHandle.USER_ALL) {
13964                for (final int individual : sUserManager.getUserIds()) {
13965                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13966                }
13967            } else {
13968                keyStore.clearUid(UserHandle.getUid(userId, appId));
13969            }
13970        } else {
13971            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13972        }
13973    }
13974
13975    @Override
13976    public void deleteApplicationCacheFiles(final String packageName,
13977            final IPackageDataObserver observer) {
13978        mContext.enforceCallingOrSelfPermission(
13979                android.Manifest.permission.DELETE_CACHE_FILES, null);
13980        // Queue up an async operation since the package deletion may take a little while.
13981        final int userId = UserHandle.getCallingUserId();
13982        mHandler.post(new Runnable() {
13983            public void run() {
13984                mHandler.removeCallbacks(this);
13985                final boolean succeded;
13986                synchronized (mInstallLock) {
13987                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13988                }
13989                clearExternalStorageDataSync(packageName, userId, false);
13990                if (observer != null) {
13991                    try {
13992                        observer.onRemoveCompleted(packageName, succeded);
13993                    } catch (RemoteException e) {
13994                        Log.i(TAG, "Observer no longer exists.");
13995                    }
13996                } //end if observer
13997            } //end run
13998        });
13999    }
14000
14001    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14002        if (packageName == null) {
14003            Slog.w(TAG, "Attempt to delete null packageName.");
14004            return false;
14005        }
14006        PackageParser.Package p;
14007        synchronized (mPackages) {
14008            p = mPackages.get(packageName);
14009        }
14010        if (p == null) {
14011            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14012            return false;
14013        }
14014        final ApplicationInfo applicationInfo = p.applicationInfo;
14015        if (applicationInfo == null) {
14016            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14017            return false;
14018        }
14019        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14020        if (retCode < 0) {
14021            Slog.w(TAG, "Couldn't remove cache files for package: "
14022                       + packageName + " u" + userId);
14023            return false;
14024        }
14025        return true;
14026    }
14027
14028    @Override
14029    public void getPackageSizeInfo(final String packageName, int userHandle,
14030            final IPackageStatsObserver observer) {
14031        mContext.enforceCallingOrSelfPermission(
14032                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14033        if (packageName == null) {
14034            throw new IllegalArgumentException("Attempt to get size of null packageName");
14035        }
14036
14037        PackageStats stats = new PackageStats(packageName, userHandle);
14038
14039        /*
14040         * Queue up an async operation since the package measurement may take a
14041         * little while.
14042         */
14043        Message msg = mHandler.obtainMessage(INIT_COPY);
14044        msg.obj = new MeasureParams(stats, observer);
14045        mHandler.sendMessage(msg);
14046    }
14047
14048    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14049            PackageStats pStats) {
14050        if (packageName == null) {
14051            Slog.w(TAG, "Attempt to get size of null packageName.");
14052            return false;
14053        }
14054        PackageParser.Package p;
14055        boolean dataOnly = false;
14056        String libDirRoot = null;
14057        String asecPath = null;
14058        PackageSetting ps = null;
14059        synchronized (mPackages) {
14060            p = mPackages.get(packageName);
14061            ps = mSettings.mPackages.get(packageName);
14062            if(p == null) {
14063                dataOnly = true;
14064                if((ps == null) || (ps.pkg == null)) {
14065                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14066                    return false;
14067                }
14068                p = ps.pkg;
14069            }
14070            if (ps != null) {
14071                libDirRoot = ps.legacyNativeLibraryPathString;
14072            }
14073            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14074                final long token = Binder.clearCallingIdentity();
14075                try {
14076                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14077                    if (secureContainerId != null) {
14078                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14079                    }
14080                } finally {
14081                    Binder.restoreCallingIdentity(token);
14082                }
14083            }
14084        }
14085        String publicSrcDir = null;
14086        if(!dataOnly) {
14087            final ApplicationInfo applicationInfo = p.applicationInfo;
14088            if (applicationInfo == null) {
14089                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14090                return false;
14091            }
14092            if (p.isForwardLocked()) {
14093                publicSrcDir = applicationInfo.getBaseResourcePath();
14094            }
14095        }
14096        // TODO: extend to measure size of split APKs
14097        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14098        // not just the first level.
14099        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14100        // just the primary.
14101        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14102
14103        String apkPath;
14104        File packageDir = new File(p.codePath);
14105
14106        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14107            apkPath = packageDir.getAbsolutePath();
14108            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14109            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14110                libDirRoot = null;
14111            }
14112        } else {
14113            apkPath = p.baseCodePath;
14114        }
14115
14116        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14117                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14118        if (res < 0) {
14119            return false;
14120        }
14121
14122        // Fix-up for forward-locked applications in ASEC containers.
14123        if (!isExternal(p)) {
14124            pStats.codeSize += pStats.externalCodeSize;
14125            pStats.externalCodeSize = 0L;
14126        }
14127
14128        return true;
14129    }
14130
14131
14132    @Override
14133    public void addPackageToPreferred(String packageName) {
14134        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14135    }
14136
14137    @Override
14138    public void removePackageFromPreferred(String packageName) {
14139        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14140    }
14141
14142    @Override
14143    public List<PackageInfo> getPreferredPackages(int flags) {
14144        return new ArrayList<PackageInfo>();
14145    }
14146
14147    private int getUidTargetSdkVersionLockedLPr(int uid) {
14148        Object obj = mSettings.getUserIdLPr(uid);
14149        if (obj instanceof SharedUserSetting) {
14150            final SharedUserSetting sus = (SharedUserSetting) obj;
14151            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14152            final Iterator<PackageSetting> it = sus.packages.iterator();
14153            while (it.hasNext()) {
14154                final PackageSetting ps = it.next();
14155                if (ps.pkg != null) {
14156                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14157                    if (v < vers) vers = v;
14158                }
14159            }
14160            return vers;
14161        } else if (obj instanceof PackageSetting) {
14162            final PackageSetting ps = (PackageSetting) obj;
14163            if (ps.pkg != null) {
14164                return ps.pkg.applicationInfo.targetSdkVersion;
14165            }
14166        }
14167        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14168    }
14169
14170    @Override
14171    public void addPreferredActivity(IntentFilter filter, int match,
14172            ComponentName[] set, ComponentName activity, int userId) {
14173        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14174                "Adding preferred");
14175    }
14176
14177    private void addPreferredActivityInternal(IntentFilter filter, int match,
14178            ComponentName[] set, ComponentName activity, boolean always, int userId,
14179            String opname) {
14180        // writer
14181        int callingUid = Binder.getCallingUid();
14182        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14183        if (filter.countActions() == 0) {
14184            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14185            return;
14186        }
14187        synchronized (mPackages) {
14188            if (mContext.checkCallingOrSelfPermission(
14189                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14190                    != PackageManager.PERMISSION_GRANTED) {
14191                if (getUidTargetSdkVersionLockedLPr(callingUid)
14192                        < Build.VERSION_CODES.FROYO) {
14193                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14194                            + callingUid);
14195                    return;
14196                }
14197                mContext.enforceCallingOrSelfPermission(
14198                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14199            }
14200
14201            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14202            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14203                    + userId + ":");
14204            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14205            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14206            scheduleWritePackageRestrictionsLocked(userId);
14207        }
14208    }
14209
14210    @Override
14211    public void replacePreferredActivity(IntentFilter filter, int match,
14212            ComponentName[] set, ComponentName activity, int userId) {
14213        if (filter.countActions() != 1) {
14214            throw new IllegalArgumentException(
14215                    "replacePreferredActivity expects filter to have only 1 action.");
14216        }
14217        if (filter.countDataAuthorities() != 0
14218                || filter.countDataPaths() != 0
14219                || filter.countDataSchemes() > 1
14220                || filter.countDataTypes() != 0) {
14221            throw new IllegalArgumentException(
14222                    "replacePreferredActivity expects filter to have no data authorities, " +
14223                    "paths, or types; and at most one scheme.");
14224        }
14225
14226        final int callingUid = Binder.getCallingUid();
14227        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14228        synchronized (mPackages) {
14229            if (mContext.checkCallingOrSelfPermission(
14230                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14231                    != PackageManager.PERMISSION_GRANTED) {
14232                if (getUidTargetSdkVersionLockedLPr(callingUid)
14233                        < Build.VERSION_CODES.FROYO) {
14234                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14235                            + Binder.getCallingUid());
14236                    return;
14237                }
14238                mContext.enforceCallingOrSelfPermission(
14239                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14240            }
14241
14242            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14243            if (pir != null) {
14244                // Get all of the existing entries that exactly match this filter.
14245                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14246                if (existing != null && existing.size() == 1) {
14247                    PreferredActivity cur = existing.get(0);
14248                    if (DEBUG_PREFERRED) {
14249                        Slog.i(TAG, "Checking replace of preferred:");
14250                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14251                        if (!cur.mPref.mAlways) {
14252                            Slog.i(TAG, "  -- CUR; not mAlways!");
14253                        } else {
14254                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14255                            Slog.i(TAG, "  -- CUR: mSet="
14256                                    + Arrays.toString(cur.mPref.mSetComponents));
14257                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14258                            Slog.i(TAG, "  -- NEW: mMatch="
14259                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14260                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14261                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14262                        }
14263                    }
14264                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14265                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14266                            && cur.mPref.sameSet(set)) {
14267                        // Setting the preferred activity to what it happens to be already
14268                        if (DEBUG_PREFERRED) {
14269                            Slog.i(TAG, "Replacing with same preferred activity "
14270                                    + cur.mPref.mShortComponent + " for user "
14271                                    + userId + ":");
14272                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14273                        }
14274                        return;
14275                    }
14276                }
14277
14278                if (existing != null) {
14279                    if (DEBUG_PREFERRED) {
14280                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14281                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14282                    }
14283                    for (int i = 0; i < existing.size(); i++) {
14284                        PreferredActivity pa = existing.get(i);
14285                        if (DEBUG_PREFERRED) {
14286                            Slog.i(TAG, "Removing existing preferred activity "
14287                                    + pa.mPref.mComponent + ":");
14288                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14289                        }
14290                        pir.removeFilter(pa);
14291                    }
14292                }
14293            }
14294            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14295                    "Replacing preferred");
14296        }
14297    }
14298
14299    @Override
14300    public void clearPackagePreferredActivities(String packageName) {
14301        final int uid = Binder.getCallingUid();
14302        // writer
14303        synchronized (mPackages) {
14304            PackageParser.Package pkg = mPackages.get(packageName);
14305            if (pkg == null || pkg.applicationInfo.uid != uid) {
14306                if (mContext.checkCallingOrSelfPermission(
14307                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14308                        != PackageManager.PERMISSION_GRANTED) {
14309                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14310                            < Build.VERSION_CODES.FROYO) {
14311                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14312                                + Binder.getCallingUid());
14313                        return;
14314                    }
14315                    mContext.enforceCallingOrSelfPermission(
14316                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14317                }
14318            }
14319
14320            int user = UserHandle.getCallingUserId();
14321            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14322                scheduleWritePackageRestrictionsLocked(user);
14323            }
14324        }
14325    }
14326
14327    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14328    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14329        ArrayList<PreferredActivity> removed = null;
14330        boolean changed = false;
14331        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14332            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14333            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14334            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14335                continue;
14336            }
14337            Iterator<PreferredActivity> it = pir.filterIterator();
14338            while (it.hasNext()) {
14339                PreferredActivity pa = it.next();
14340                // Mark entry for removal only if it matches the package name
14341                // and the entry is of type "always".
14342                if (packageName == null ||
14343                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14344                                && pa.mPref.mAlways)) {
14345                    if (removed == null) {
14346                        removed = new ArrayList<PreferredActivity>();
14347                    }
14348                    removed.add(pa);
14349                }
14350            }
14351            if (removed != null) {
14352                for (int j=0; j<removed.size(); j++) {
14353                    PreferredActivity pa = removed.get(j);
14354                    pir.removeFilter(pa);
14355                }
14356                changed = true;
14357            }
14358        }
14359        return changed;
14360    }
14361
14362    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14363    private void clearIntentFilterVerificationsLPw(int userId) {
14364        final int packageCount = mPackages.size();
14365        for (int i = 0; i < packageCount; i++) {
14366            PackageParser.Package pkg = mPackages.valueAt(i);
14367            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14368        }
14369    }
14370
14371    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14372    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14373        if (userId == UserHandle.USER_ALL) {
14374            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14375                    sUserManager.getUserIds())) {
14376                for (int oneUserId : sUserManager.getUserIds()) {
14377                    scheduleWritePackageRestrictionsLocked(oneUserId);
14378                }
14379            }
14380        } else {
14381            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14382                scheduleWritePackageRestrictionsLocked(userId);
14383            }
14384        }
14385    }
14386
14387    void clearDefaultBrowserIfNeeded(String packageName) {
14388        for (int oneUserId : sUserManager.getUserIds()) {
14389            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14390            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14391            if (packageName.equals(defaultBrowserPackageName)) {
14392                setDefaultBrowserPackageName(null, oneUserId);
14393            }
14394        }
14395    }
14396
14397    @Override
14398    public void resetApplicationPreferences(int userId) {
14399        mContext.enforceCallingOrSelfPermission(
14400                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14401        // writer
14402        synchronized (mPackages) {
14403            final long identity = Binder.clearCallingIdentity();
14404            try {
14405                clearPackagePreferredActivitiesLPw(null, userId);
14406                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14407                // TODO: We have to reset the default SMS and Phone. This requires
14408                // significant refactoring to keep all default apps in the package
14409                // manager (cleaner but more work) or have the services provide
14410                // callbacks to the package manager to request a default app reset.
14411                applyFactoryDefaultBrowserLPw(userId);
14412                clearIntentFilterVerificationsLPw(userId);
14413                primeDomainVerificationsLPw(userId);
14414                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14415                scheduleWritePackageRestrictionsLocked(userId);
14416            } finally {
14417                Binder.restoreCallingIdentity(identity);
14418            }
14419        }
14420    }
14421
14422    @Override
14423    public int getPreferredActivities(List<IntentFilter> outFilters,
14424            List<ComponentName> outActivities, String packageName) {
14425
14426        int num = 0;
14427        final int userId = UserHandle.getCallingUserId();
14428        // reader
14429        synchronized (mPackages) {
14430            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14431            if (pir != null) {
14432                final Iterator<PreferredActivity> it = pir.filterIterator();
14433                while (it.hasNext()) {
14434                    final PreferredActivity pa = it.next();
14435                    if (packageName == null
14436                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14437                                    && pa.mPref.mAlways)) {
14438                        if (outFilters != null) {
14439                            outFilters.add(new IntentFilter(pa));
14440                        }
14441                        if (outActivities != null) {
14442                            outActivities.add(pa.mPref.mComponent);
14443                        }
14444                    }
14445                }
14446            }
14447        }
14448
14449        return num;
14450    }
14451
14452    @Override
14453    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14454            int userId) {
14455        int callingUid = Binder.getCallingUid();
14456        if (callingUid != Process.SYSTEM_UID) {
14457            throw new SecurityException(
14458                    "addPersistentPreferredActivity can only be run by the system");
14459        }
14460        if (filter.countActions() == 0) {
14461            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14462            return;
14463        }
14464        synchronized (mPackages) {
14465            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14466                    " :");
14467            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14468            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14469                    new PersistentPreferredActivity(filter, activity));
14470            scheduleWritePackageRestrictionsLocked(userId);
14471        }
14472    }
14473
14474    @Override
14475    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14476        int callingUid = Binder.getCallingUid();
14477        if (callingUid != Process.SYSTEM_UID) {
14478            throw new SecurityException(
14479                    "clearPackagePersistentPreferredActivities can only be run by the system");
14480        }
14481        ArrayList<PersistentPreferredActivity> removed = null;
14482        boolean changed = false;
14483        synchronized (mPackages) {
14484            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14485                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14486                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14487                        .valueAt(i);
14488                if (userId != thisUserId) {
14489                    continue;
14490                }
14491                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14492                while (it.hasNext()) {
14493                    PersistentPreferredActivity ppa = it.next();
14494                    // Mark entry for removal only if it matches the package name.
14495                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14496                        if (removed == null) {
14497                            removed = new ArrayList<PersistentPreferredActivity>();
14498                        }
14499                        removed.add(ppa);
14500                    }
14501                }
14502                if (removed != null) {
14503                    for (int j=0; j<removed.size(); j++) {
14504                        PersistentPreferredActivity ppa = removed.get(j);
14505                        ppir.removeFilter(ppa);
14506                    }
14507                    changed = true;
14508                }
14509            }
14510
14511            if (changed) {
14512                scheduleWritePackageRestrictionsLocked(userId);
14513            }
14514        }
14515    }
14516
14517    /**
14518     * Common machinery for picking apart a restored XML blob and passing
14519     * it to a caller-supplied functor to be applied to the running system.
14520     */
14521    private void restoreFromXml(XmlPullParser parser, int userId,
14522            String expectedStartTag, BlobXmlRestorer functor)
14523            throws IOException, XmlPullParserException {
14524        int type;
14525        while ((type = parser.next()) != XmlPullParser.START_TAG
14526                && type != XmlPullParser.END_DOCUMENT) {
14527        }
14528        if (type != XmlPullParser.START_TAG) {
14529            // oops didn't find a start tag?!
14530            if (DEBUG_BACKUP) {
14531                Slog.e(TAG, "Didn't find start tag during restore");
14532            }
14533            return;
14534        }
14535
14536        // this is supposed to be TAG_PREFERRED_BACKUP
14537        if (!expectedStartTag.equals(parser.getName())) {
14538            if (DEBUG_BACKUP) {
14539                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14540            }
14541            return;
14542        }
14543
14544        // skip interfering stuff, then we're aligned with the backing implementation
14545        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14546        functor.apply(parser, userId);
14547    }
14548
14549    private interface BlobXmlRestorer {
14550        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14551    }
14552
14553    /**
14554     * Non-Binder method, support for the backup/restore mechanism: write the
14555     * full set of preferred activities in its canonical XML format.  Returns the
14556     * XML output as a byte array, or null if there is none.
14557     */
14558    @Override
14559    public byte[] getPreferredActivityBackup(int userId) {
14560        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14561            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14562        }
14563
14564        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14565        try {
14566            final XmlSerializer serializer = new FastXmlSerializer();
14567            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14568            serializer.startDocument(null, true);
14569            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14570
14571            synchronized (mPackages) {
14572                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14573            }
14574
14575            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14576            serializer.endDocument();
14577            serializer.flush();
14578        } catch (Exception e) {
14579            if (DEBUG_BACKUP) {
14580                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14581            }
14582            return null;
14583        }
14584
14585        return dataStream.toByteArray();
14586    }
14587
14588    @Override
14589    public void restorePreferredActivities(byte[] backup, int userId) {
14590        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14591            throw new SecurityException("Only the system may call restorePreferredActivities()");
14592        }
14593
14594        try {
14595            final XmlPullParser parser = Xml.newPullParser();
14596            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14597            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14598                    new BlobXmlRestorer() {
14599                        @Override
14600                        public void apply(XmlPullParser parser, int userId)
14601                                throws XmlPullParserException, IOException {
14602                            synchronized (mPackages) {
14603                                mSettings.readPreferredActivitiesLPw(parser, userId);
14604                            }
14605                        }
14606                    } );
14607        } catch (Exception e) {
14608            if (DEBUG_BACKUP) {
14609                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14610            }
14611        }
14612    }
14613
14614    /**
14615     * Non-Binder method, support for the backup/restore mechanism: write the
14616     * default browser (etc) settings in its canonical XML format.  Returns the default
14617     * browser XML representation as a byte array, or null if there is none.
14618     */
14619    @Override
14620    public byte[] getDefaultAppsBackup(int userId) {
14621        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14622            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14623        }
14624
14625        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14626        try {
14627            final XmlSerializer serializer = new FastXmlSerializer();
14628            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14629            serializer.startDocument(null, true);
14630            serializer.startTag(null, TAG_DEFAULT_APPS);
14631
14632            synchronized (mPackages) {
14633                mSettings.writeDefaultAppsLPr(serializer, userId);
14634            }
14635
14636            serializer.endTag(null, TAG_DEFAULT_APPS);
14637            serializer.endDocument();
14638            serializer.flush();
14639        } catch (Exception e) {
14640            if (DEBUG_BACKUP) {
14641                Slog.e(TAG, "Unable to write default apps for backup", e);
14642            }
14643            return null;
14644        }
14645
14646        return dataStream.toByteArray();
14647    }
14648
14649    @Override
14650    public void restoreDefaultApps(byte[] backup, int userId) {
14651        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14652            throw new SecurityException("Only the system may call restoreDefaultApps()");
14653        }
14654
14655        try {
14656            final XmlPullParser parser = Xml.newPullParser();
14657            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14658            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14659                    new BlobXmlRestorer() {
14660                        @Override
14661                        public void apply(XmlPullParser parser, int userId)
14662                                throws XmlPullParserException, IOException {
14663                            synchronized (mPackages) {
14664                                mSettings.readDefaultAppsLPw(parser, userId);
14665                            }
14666                        }
14667                    } );
14668        } catch (Exception e) {
14669            if (DEBUG_BACKUP) {
14670                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14671            }
14672        }
14673    }
14674
14675    @Override
14676    public byte[] getIntentFilterVerificationBackup(int userId) {
14677        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14678            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
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_INTENT_FILTER_VERIFICATION);
14687
14688            synchronized (mPackages) {
14689                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14690            }
14691
14692            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14693            serializer.endDocument();
14694            serializer.flush();
14695        } catch (Exception e) {
14696            if (DEBUG_BACKUP) {
14697                Slog.e(TAG, "Unable to write default apps for backup", e);
14698            }
14699            return null;
14700        }
14701
14702        return dataStream.toByteArray();
14703    }
14704
14705    @Override
14706    public void restoreIntentFilterVerification(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_INTENT_FILTER_VERIFICATION,
14715                    new BlobXmlRestorer() {
14716                        @Override
14717                        public void apply(XmlPullParser parser, int userId)
14718                                throws XmlPullParserException, IOException {
14719                            synchronized (mPackages) {
14720                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14721                                mSettings.writeLPr();
14722                            }
14723                        }
14724                    } );
14725        } catch (Exception e) {
14726            if (DEBUG_BACKUP) {
14727                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14728            }
14729        }
14730    }
14731
14732    @Override
14733    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14734            int sourceUserId, int targetUserId, int flags) {
14735        mContext.enforceCallingOrSelfPermission(
14736                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14737        int callingUid = Binder.getCallingUid();
14738        enforceOwnerRights(ownerPackage, callingUid);
14739        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14740        if (intentFilter.countActions() == 0) {
14741            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14742            return;
14743        }
14744        synchronized (mPackages) {
14745            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14746                    ownerPackage, targetUserId, flags);
14747            CrossProfileIntentResolver resolver =
14748                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14749            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14750            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14751            if (existing != null) {
14752                int size = existing.size();
14753                for (int i = 0; i < size; i++) {
14754                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14755                        return;
14756                    }
14757                }
14758            }
14759            resolver.addFilter(newFilter);
14760            scheduleWritePackageRestrictionsLocked(sourceUserId);
14761        }
14762    }
14763
14764    @Override
14765    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14766        mContext.enforceCallingOrSelfPermission(
14767                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14768        int callingUid = Binder.getCallingUid();
14769        enforceOwnerRights(ownerPackage, callingUid);
14770        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14771        synchronized (mPackages) {
14772            CrossProfileIntentResolver resolver =
14773                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14774            ArraySet<CrossProfileIntentFilter> set =
14775                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14776            for (CrossProfileIntentFilter filter : set) {
14777                if (filter.getOwnerPackage().equals(ownerPackage)) {
14778                    resolver.removeFilter(filter);
14779                }
14780            }
14781            scheduleWritePackageRestrictionsLocked(sourceUserId);
14782        }
14783    }
14784
14785    // Enforcing that callingUid is owning pkg on userId
14786    private void enforceOwnerRights(String pkg, int callingUid) {
14787        // The system owns everything.
14788        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14789            return;
14790        }
14791        int callingUserId = UserHandle.getUserId(callingUid);
14792        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14793        if (pi == null) {
14794            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14795                    + callingUserId);
14796        }
14797        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14798            throw new SecurityException("Calling uid " + callingUid
14799                    + " does not own package " + pkg);
14800        }
14801    }
14802
14803    @Override
14804    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14805        Intent intent = new Intent(Intent.ACTION_MAIN);
14806        intent.addCategory(Intent.CATEGORY_HOME);
14807
14808        final int callingUserId = UserHandle.getCallingUserId();
14809        List<ResolveInfo> list = queryIntentActivities(intent, null,
14810                PackageManager.GET_META_DATA, callingUserId);
14811        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14812                true, false, false, callingUserId);
14813
14814        allHomeCandidates.clear();
14815        if (list != null) {
14816            for (ResolveInfo ri : list) {
14817                allHomeCandidates.add(ri);
14818            }
14819        }
14820        return (preferred == null || preferred.activityInfo == null)
14821                ? null
14822                : new ComponentName(preferred.activityInfo.packageName,
14823                        preferred.activityInfo.name);
14824    }
14825
14826    @Override
14827    public void setApplicationEnabledSetting(String appPackageName,
14828            int newState, int flags, int userId, String callingPackage) {
14829        if (!sUserManager.exists(userId)) return;
14830        if (callingPackage == null) {
14831            callingPackage = Integer.toString(Binder.getCallingUid());
14832        }
14833        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14834    }
14835
14836    @Override
14837    public void setComponentEnabledSetting(ComponentName componentName,
14838            int newState, int flags, int userId) {
14839        if (!sUserManager.exists(userId)) return;
14840        setEnabledSetting(componentName.getPackageName(),
14841                componentName.getClassName(), newState, flags, userId, null);
14842    }
14843
14844    private void setEnabledSetting(final String packageName, String className, int newState,
14845            final int flags, int userId, String callingPackage) {
14846        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14847              || newState == COMPONENT_ENABLED_STATE_ENABLED
14848              || newState == COMPONENT_ENABLED_STATE_DISABLED
14849              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14850              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14851            throw new IllegalArgumentException("Invalid new component state: "
14852                    + newState);
14853        }
14854        PackageSetting pkgSetting;
14855        final int uid = Binder.getCallingUid();
14856        final int permission = mContext.checkCallingOrSelfPermission(
14857                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14858        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14859        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14860        boolean sendNow = false;
14861        boolean isApp = (className == null);
14862        String componentName = isApp ? packageName : className;
14863        int packageUid = -1;
14864        ArrayList<String> components;
14865
14866        // writer
14867        synchronized (mPackages) {
14868            pkgSetting = mSettings.mPackages.get(packageName);
14869            if (pkgSetting == null) {
14870                if (className == null) {
14871                    throw new IllegalArgumentException(
14872                            "Unknown package: " + packageName);
14873                }
14874                throw new IllegalArgumentException(
14875                        "Unknown component: " + packageName
14876                        + "/" + className);
14877            }
14878            // Allow root and verify that userId is not being specified by a different user
14879            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14880                throw new SecurityException(
14881                        "Permission Denial: attempt to change component state from pid="
14882                        + Binder.getCallingPid()
14883                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14884            }
14885            if (className == null) {
14886                // We're dealing with an application/package level state change
14887                if (pkgSetting.getEnabled(userId) == newState) {
14888                    // Nothing to do
14889                    return;
14890                }
14891                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14892                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14893                    // Don't care about who enables an app.
14894                    callingPackage = null;
14895                }
14896                pkgSetting.setEnabled(newState, userId, callingPackage);
14897                // pkgSetting.pkg.mSetEnabled = newState;
14898            } else {
14899                // We're dealing with a component level state change
14900                // First, verify that this is a valid class name.
14901                PackageParser.Package pkg = pkgSetting.pkg;
14902                if (pkg == null || !pkg.hasComponentClassName(className)) {
14903                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14904                        throw new IllegalArgumentException("Component class " + className
14905                                + " does not exist in " + packageName);
14906                    } else {
14907                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14908                                + className + " does not exist in " + packageName);
14909                    }
14910                }
14911                switch (newState) {
14912                case COMPONENT_ENABLED_STATE_ENABLED:
14913                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14914                        return;
14915                    }
14916                    break;
14917                case COMPONENT_ENABLED_STATE_DISABLED:
14918                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14919                        return;
14920                    }
14921                    break;
14922                case COMPONENT_ENABLED_STATE_DEFAULT:
14923                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14924                        return;
14925                    }
14926                    break;
14927                default:
14928                    Slog.e(TAG, "Invalid new component state: " + newState);
14929                    return;
14930                }
14931            }
14932            scheduleWritePackageRestrictionsLocked(userId);
14933            components = mPendingBroadcasts.get(userId, packageName);
14934            final boolean newPackage = components == null;
14935            if (newPackage) {
14936                components = new ArrayList<String>();
14937            }
14938            if (!components.contains(componentName)) {
14939                components.add(componentName);
14940            }
14941            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14942                sendNow = true;
14943                // Purge entry from pending broadcast list if another one exists already
14944                // since we are sending one right away.
14945                mPendingBroadcasts.remove(userId, packageName);
14946            } else {
14947                if (newPackage) {
14948                    mPendingBroadcasts.put(userId, packageName, components);
14949                }
14950                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14951                    // Schedule a message
14952                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14953                }
14954            }
14955        }
14956
14957        long callingId = Binder.clearCallingIdentity();
14958        try {
14959            if (sendNow) {
14960                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14961                sendPackageChangedBroadcast(packageName,
14962                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14963            }
14964        } finally {
14965            Binder.restoreCallingIdentity(callingId);
14966        }
14967    }
14968
14969    private void sendPackageChangedBroadcast(String packageName,
14970            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14971        if (DEBUG_INSTALL)
14972            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14973                    + componentNames);
14974        Bundle extras = new Bundle(4);
14975        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14976        String nameList[] = new String[componentNames.size()];
14977        componentNames.toArray(nameList);
14978        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14979        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14980        extras.putInt(Intent.EXTRA_UID, packageUid);
14981        // If this is not reporting a change of the overall package, then only send it
14982        // to registered receivers.  We don't want to launch a swath of apps for every
14983        // little component state change.
14984        final int flags = !componentNames.contains(packageName)
14985                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
14986        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
14987                new int[] {UserHandle.getUserId(packageUid)});
14988    }
14989
14990    @Override
14991    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14992        if (!sUserManager.exists(userId)) return;
14993        final int uid = Binder.getCallingUid();
14994        final int permission = mContext.checkCallingOrSelfPermission(
14995                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14996        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14997        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14998        // writer
14999        synchronized (mPackages) {
15000            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15001                    allowedByPermission, uid, userId)) {
15002                scheduleWritePackageRestrictionsLocked(userId);
15003            }
15004        }
15005    }
15006
15007    @Override
15008    public String getInstallerPackageName(String packageName) {
15009        // reader
15010        synchronized (mPackages) {
15011            return mSettings.getInstallerPackageNameLPr(packageName);
15012        }
15013    }
15014
15015    @Override
15016    public int getApplicationEnabledSetting(String packageName, int userId) {
15017        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15018        int uid = Binder.getCallingUid();
15019        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15020        // reader
15021        synchronized (mPackages) {
15022            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15023        }
15024    }
15025
15026    @Override
15027    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15028        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15029        int uid = Binder.getCallingUid();
15030        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15031        // reader
15032        synchronized (mPackages) {
15033            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15034        }
15035    }
15036
15037    @Override
15038    public void enterSafeMode() {
15039        enforceSystemOrRoot("Only the system can request entering safe mode");
15040
15041        if (!mSystemReady) {
15042            mSafeMode = true;
15043        }
15044    }
15045
15046    @Override
15047    public void systemReady() {
15048        mSystemReady = true;
15049
15050        // Read the compatibilty setting when the system is ready.
15051        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15052                mContext.getContentResolver(),
15053                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15054        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15055        if (DEBUG_SETTINGS) {
15056            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15057        }
15058
15059        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15060
15061        synchronized (mPackages) {
15062            // Verify that all of the preferred activity components actually
15063            // exist.  It is possible for applications to be updated and at
15064            // that point remove a previously declared activity component that
15065            // had been set as a preferred activity.  We try to clean this up
15066            // the next time we encounter that preferred activity, but it is
15067            // possible for the user flow to never be able to return to that
15068            // situation so here we do a sanity check to make sure we haven't
15069            // left any junk around.
15070            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15071            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15072                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15073                removed.clear();
15074                for (PreferredActivity pa : pir.filterSet()) {
15075                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15076                        removed.add(pa);
15077                    }
15078                }
15079                if (removed.size() > 0) {
15080                    for (int r=0; r<removed.size(); r++) {
15081                        PreferredActivity pa = removed.get(r);
15082                        Slog.w(TAG, "Removing dangling preferred activity: "
15083                                + pa.mPref.mComponent);
15084                        pir.removeFilter(pa);
15085                    }
15086                    mSettings.writePackageRestrictionsLPr(
15087                            mSettings.mPreferredActivities.keyAt(i));
15088                }
15089            }
15090
15091            for (int userId : UserManagerService.getInstance().getUserIds()) {
15092                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15093                    grantPermissionsUserIds = ArrayUtils.appendInt(
15094                            grantPermissionsUserIds, userId);
15095                }
15096            }
15097        }
15098        sUserManager.systemReady();
15099
15100        // If we upgraded grant all default permissions before kicking off.
15101        for (int userId : grantPermissionsUserIds) {
15102            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15103        }
15104
15105        // Kick off any messages waiting for system ready
15106        if (mPostSystemReadyMessages != null) {
15107            for (Message msg : mPostSystemReadyMessages) {
15108                msg.sendToTarget();
15109            }
15110            mPostSystemReadyMessages = null;
15111        }
15112
15113        // Watch for external volumes that come and go over time
15114        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15115        storage.registerListener(mStorageListener);
15116
15117        mInstallerService.systemReady();
15118        mPackageDexOptimizer.systemReady();
15119
15120        MountServiceInternal mountServiceInternal = LocalServices.getService(
15121                MountServiceInternal.class);
15122        mountServiceInternal.addExternalStoragePolicy(
15123                new MountServiceInternal.ExternalStorageMountPolicy() {
15124            @Override
15125            public int getMountMode(int uid, String packageName) {
15126                if (Process.isIsolated(uid)) {
15127                    return Zygote.MOUNT_EXTERNAL_NONE;
15128                }
15129                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15130                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15131                }
15132                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15133                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15134                }
15135                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15136                    return Zygote.MOUNT_EXTERNAL_READ;
15137                }
15138                return Zygote.MOUNT_EXTERNAL_WRITE;
15139            }
15140
15141            @Override
15142            public boolean hasExternalStorage(int uid, String packageName) {
15143                return true;
15144            }
15145        });
15146    }
15147
15148    @Override
15149    public boolean isSafeMode() {
15150        return mSafeMode;
15151    }
15152
15153    @Override
15154    public boolean hasSystemUidErrors() {
15155        return mHasSystemUidErrors;
15156    }
15157
15158    static String arrayToString(int[] array) {
15159        StringBuffer buf = new StringBuffer(128);
15160        buf.append('[');
15161        if (array != null) {
15162            for (int i=0; i<array.length; i++) {
15163                if (i > 0) buf.append(", ");
15164                buf.append(array[i]);
15165            }
15166        }
15167        buf.append(']');
15168        return buf.toString();
15169    }
15170
15171    static class DumpState {
15172        public static final int DUMP_LIBS = 1 << 0;
15173        public static final int DUMP_FEATURES = 1 << 1;
15174        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15175        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15176        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15177        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15178        public static final int DUMP_PERMISSIONS = 1 << 6;
15179        public static final int DUMP_PACKAGES = 1 << 7;
15180        public static final int DUMP_SHARED_USERS = 1 << 8;
15181        public static final int DUMP_MESSAGES = 1 << 9;
15182        public static final int DUMP_PROVIDERS = 1 << 10;
15183        public static final int DUMP_VERIFIERS = 1 << 11;
15184        public static final int DUMP_PREFERRED = 1 << 12;
15185        public static final int DUMP_PREFERRED_XML = 1 << 13;
15186        public static final int DUMP_KEYSETS = 1 << 14;
15187        public static final int DUMP_VERSION = 1 << 15;
15188        public static final int DUMP_INSTALLS = 1 << 16;
15189        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15190        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15191
15192        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15193
15194        private int mTypes;
15195
15196        private int mOptions;
15197
15198        private boolean mTitlePrinted;
15199
15200        private SharedUserSetting mSharedUser;
15201
15202        public boolean isDumping(int type) {
15203            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15204                return true;
15205            }
15206
15207            return (mTypes & type) != 0;
15208        }
15209
15210        public void setDump(int type) {
15211            mTypes |= type;
15212        }
15213
15214        public boolean isOptionEnabled(int option) {
15215            return (mOptions & option) != 0;
15216        }
15217
15218        public void setOptionEnabled(int option) {
15219            mOptions |= option;
15220        }
15221
15222        public boolean onTitlePrinted() {
15223            final boolean printed = mTitlePrinted;
15224            mTitlePrinted = true;
15225            return printed;
15226        }
15227
15228        public boolean getTitlePrinted() {
15229            return mTitlePrinted;
15230        }
15231
15232        public void setTitlePrinted(boolean enabled) {
15233            mTitlePrinted = enabled;
15234        }
15235
15236        public SharedUserSetting getSharedUser() {
15237            return mSharedUser;
15238        }
15239
15240        public void setSharedUser(SharedUserSetting user) {
15241            mSharedUser = user;
15242        }
15243    }
15244
15245    @Override
15246    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15247            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15248        (new PackageManagerShellCommand(this)).exec(
15249                this, in, out, err, args, resultReceiver);
15250    }
15251
15252    @Override
15253    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15254        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15255                != PackageManager.PERMISSION_GRANTED) {
15256            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15257                    + Binder.getCallingPid()
15258                    + ", uid=" + Binder.getCallingUid()
15259                    + " without permission "
15260                    + android.Manifest.permission.DUMP);
15261            return;
15262        }
15263
15264        DumpState dumpState = new DumpState();
15265        boolean fullPreferred = false;
15266        boolean checkin = false;
15267
15268        String packageName = null;
15269        ArraySet<String> permissionNames = null;
15270
15271        int opti = 0;
15272        while (opti < args.length) {
15273            String opt = args[opti];
15274            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15275                break;
15276            }
15277            opti++;
15278
15279            if ("-a".equals(opt)) {
15280                // Right now we only know how to print all.
15281            } else if ("-h".equals(opt)) {
15282                pw.println("Package manager dump options:");
15283                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15284                pw.println("    --checkin: dump for a checkin");
15285                pw.println("    -f: print details of intent filters");
15286                pw.println("    -h: print this help");
15287                pw.println("  cmd may be one of:");
15288                pw.println("    l[ibraries]: list known shared libraries");
15289                pw.println("    f[eatures]: list device features");
15290                pw.println("    k[eysets]: print known keysets");
15291                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15292                pw.println("    perm[issions]: dump permissions");
15293                pw.println("    permission [name ...]: dump declaration and use of given permission");
15294                pw.println("    pref[erred]: print preferred package settings");
15295                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15296                pw.println("    prov[iders]: dump content providers");
15297                pw.println("    p[ackages]: dump installed packages");
15298                pw.println("    s[hared-users]: dump shared user IDs");
15299                pw.println("    m[essages]: print collected runtime messages");
15300                pw.println("    v[erifiers]: print package verifier info");
15301                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15302                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15303                pw.println("    version: print database version info");
15304                pw.println("    write: write current settings now");
15305                pw.println("    installs: details about install sessions");
15306                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15307                pw.println("    <package.name>: info about given package");
15308                return;
15309            } else if ("--checkin".equals(opt)) {
15310                checkin = true;
15311            } else if ("-f".equals(opt)) {
15312                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15313            } else {
15314                pw.println("Unknown argument: " + opt + "; use -h for help");
15315            }
15316        }
15317
15318        // Is the caller requesting to dump a particular piece of data?
15319        if (opti < args.length) {
15320            String cmd = args[opti];
15321            opti++;
15322            // Is this a package name?
15323            if ("android".equals(cmd) || cmd.contains(".")) {
15324                packageName = cmd;
15325                // When dumping a single package, we always dump all of its
15326                // filter information since the amount of data will be reasonable.
15327                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15328            } else if ("check-permission".equals(cmd)) {
15329                if (opti >= args.length) {
15330                    pw.println("Error: check-permission missing permission argument");
15331                    return;
15332                }
15333                String perm = args[opti];
15334                opti++;
15335                if (opti >= args.length) {
15336                    pw.println("Error: check-permission missing package argument");
15337                    return;
15338                }
15339                String pkg = args[opti];
15340                opti++;
15341                int user = UserHandle.getUserId(Binder.getCallingUid());
15342                if (opti < args.length) {
15343                    try {
15344                        user = Integer.parseInt(args[opti]);
15345                    } catch (NumberFormatException e) {
15346                        pw.println("Error: check-permission user argument is not a number: "
15347                                + args[opti]);
15348                        return;
15349                    }
15350                }
15351                pw.println(checkPermission(perm, pkg, user));
15352                return;
15353            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15354                dumpState.setDump(DumpState.DUMP_LIBS);
15355            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15356                dumpState.setDump(DumpState.DUMP_FEATURES);
15357            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15358                if (opti >= args.length) {
15359                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15360                            | DumpState.DUMP_SERVICE_RESOLVERS
15361                            | DumpState.DUMP_RECEIVER_RESOLVERS
15362                            | DumpState.DUMP_CONTENT_RESOLVERS);
15363                } else {
15364                    while (opti < args.length) {
15365                        String name = args[opti];
15366                        if ("a".equals(name) || "activity".equals(name)) {
15367                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15368                        } else if ("s".equals(name) || "service".equals(name)) {
15369                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15370                        } else if ("r".equals(name) || "receiver".equals(name)) {
15371                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15372                        } else if ("c".equals(name) || "content".equals(name)) {
15373                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15374                        } else {
15375                            pw.println("Error: unknown resolver table type: " + name);
15376                            return;
15377                        }
15378                        opti++;
15379                    }
15380                }
15381            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15382                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15383            } else if ("permission".equals(cmd)) {
15384                if (opti >= args.length) {
15385                    pw.println("Error: permission requires permission name");
15386                    return;
15387                }
15388                permissionNames = new ArraySet<>();
15389                while (opti < args.length) {
15390                    permissionNames.add(args[opti]);
15391                    opti++;
15392                }
15393                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15394                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15395            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15396                dumpState.setDump(DumpState.DUMP_PREFERRED);
15397            } else if ("preferred-xml".equals(cmd)) {
15398                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15399                if (opti < args.length && "--full".equals(args[opti])) {
15400                    fullPreferred = true;
15401                    opti++;
15402                }
15403            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15404                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15405            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15406                dumpState.setDump(DumpState.DUMP_PACKAGES);
15407            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15408                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15409            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15410                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15411            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15412                dumpState.setDump(DumpState.DUMP_MESSAGES);
15413            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15414                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15415            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15416                    || "intent-filter-verifiers".equals(cmd)) {
15417                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15418            } else if ("version".equals(cmd)) {
15419                dumpState.setDump(DumpState.DUMP_VERSION);
15420            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15421                dumpState.setDump(DumpState.DUMP_KEYSETS);
15422            } else if ("installs".equals(cmd)) {
15423                dumpState.setDump(DumpState.DUMP_INSTALLS);
15424            } else if ("write".equals(cmd)) {
15425                synchronized (mPackages) {
15426                    mSettings.writeLPr();
15427                    pw.println("Settings written.");
15428                    return;
15429                }
15430            }
15431        }
15432
15433        if (checkin) {
15434            pw.println("vers,1");
15435        }
15436
15437        // reader
15438        synchronized (mPackages) {
15439            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15440                if (!checkin) {
15441                    if (dumpState.onTitlePrinted())
15442                        pw.println();
15443                    pw.println("Database versions:");
15444                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15445                }
15446            }
15447
15448            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15449                if (!checkin) {
15450                    if (dumpState.onTitlePrinted())
15451                        pw.println();
15452                    pw.println("Verifiers:");
15453                    pw.print("  Required: ");
15454                    pw.print(mRequiredVerifierPackage);
15455                    pw.print(" (uid=");
15456                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15457                    pw.println(")");
15458                } else if (mRequiredVerifierPackage != null) {
15459                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15460                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15461                }
15462            }
15463
15464            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15465                    packageName == null) {
15466                if (mIntentFilterVerifierComponent != null) {
15467                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15468                    if (!checkin) {
15469                        if (dumpState.onTitlePrinted())
15470                            pw.println();
15471                        pw.println("Intent Filter Verifier:");
15472                        pw.print("  Using: ");
15473                        pw.print(verifierPackageName);
15474                        pw.print(" (uid=");
15475                        pw.print(getPackageUid(verifierPackageName, 0));
15476                        pw.println(")");
15477                    } else if (verifierPackageName != null) {
15478                        pw.print("ifv,"); pw.print(verifierPackageName);
15479                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15480                    }
15481                } else {
15482                    pw.println();
15483                    pw.println("No Intent Filter Verifier available!");
15484                }
15485            }
15486
15487            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15488                boolean printedHeader = false;
15489                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15490                while (it.hasNext()) {
15491                    String name = it.next();
15492                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15493                    if (!checkin) {
15494                        if (!printedHeader) {
15495                            if (dumpState.onTitlePrinted())
15496                                pw.println();
15497                            pw.println("Libraries:");
15498                            printedHeader = true;
15499                        }
15500                        pw.print("  ");
15501                    } else {
15502                        pw.print("lib,");
15503                    }
15504                    pw.print(name);
15505                    if (!checkin) {
15506                        pw.print(" -> ");
15507                    }
15508                    if (ent.path != null) {
15509                        if (!checkin) {
15510                            pw.print("(jar) ");
15511                            pw.print(ent.path);
15512                        } else {
15513                            pw.print(",jar,");
15514                            pw.print(ent.path);
15515                        }
15516                    } else {
15517                        if (!checkin) {
15518                            pw.print("(apk) ");
15519                            pw.print(ent.apk);
15520                        } else {
15521                            pw.print(",apk,");
15522                            pw.print(ent.apk);
15523                        }
15524                    }
15525                    pw.println();
15526                }
15527            }
15528
15529            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15530                if (dumpState.onTitlePrinted())
15531                    pw.println();
15532                if (!checkin) {
15533                    pw.println("Features:");
15534                }
15535                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15536                while (it.hasNext()) {
15537                    String name = it.next();
15538                    if (!checkin) {
15539                        pw.print("  ");
15540                    } else {
15541                        pw.print("feat,");
15542                    }
15543                    pw.println(name);
15544                }
15545            }
15546
15547            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15548                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15549                        : "Activity Resolver Table:", "  ", packageName,
15550                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15551                    dumpState.setTitlePrinted(true);
15552                }
15553            }
15554            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15555                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15556                        : "Receiver Resolver Table:", "  ", packageName,
15557                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15558                    dumpState.setTitlePrinted(true);
15559                }
15560            }
15561            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15562                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15563                        : "Service Resolver Table:", "  ", packageName,
15564                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15565                    dumpState.setTitlePrinted(true);
15566                }
15567            }
15568            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15569                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15570                        : "Provider Resolver Table:", "  ", packageName,
15571                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15572                    dumpState.setTitlePrinted(true);
15573                }
15574            }
15575
15576            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15577                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15578                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15579                    int user = mSettings.mPreferredActivities.keyAt(i);
15580                    if (pir.dump(pw,
15581                            dumpState.getTitlePrinted()
15582                                ? "\nPreferred Activities User " + user + ":"
15583                                : "Preferred Activities User " + user + ":", "  ",
15584                            packageName, true, false)) {
15585                        dumpState.setTitlePrinted(true);
15586                    }
15587                }
15588            }
15589
15590            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15591                pw.flush();
15592                FileOutputStream fout = new FileOutputStream(fd);
15593                BufferedOutputStream str = new BufferedOutputStream(fout);
15594                XmlSerializer serializer = new FastXmlSerializer();
15595                try {
15596                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15597                    serializer.startDocument(null, true);
15598                    serializer.setFeature(
15599                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15600                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15601                    serializer.endDocument();
15602                    serializer.flush();
15603                } catch (IllegalArgumentException e) {
15604                    pw.println("Failed writing: " + e);
15605                } catch (IllegalStateException e) {
15606                    pw.println("Failed writing: " + e);
15607                } catch (IOException e) {
15608                    pw.println("Failed writing: " + e);
15609                }
15610            }
15611
15612            if (!checkin
15613                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15614                    && packageName == null) {
15615                pw.println();
15616                int count = mSettings.mPackages.size();
15617                if (count == 0) {
15618                    pw.println("No applications!");
15619                    pw.println();
15620                } else {
15621                    final String prefix = "  ";
15622                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15623                    if (allPackageSettings.size() == 0) {
15624                        pw.println("No domain preferred apps!");
15625                        pw.println();
15626                    } else {
15627                        pw.println("App verification status:");
15628                        pw.println();
15629                        count = 0;
15630                        for (PackageSetting ps : allPackageSettings) {
15631                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15632                            if (ivi == null || ivi.getPackageName() == null) continue;
15633                            pw.println(prefix + "Package: " + ivi.getPackageName());
15634                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15635                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15636                            pw.println();
15637                            count++;
15638                        }
15639                        if (count == 0) {
15640                            pw.println(prefix + "No app verification established.");
15641                            pw.println();
15642                        }
15643                        for (int userId : sUserManager.getUserIds()) {
15644                            pw.println("App linkages for user " + userId + ":");
15645                            pw.println();
15646                            count = 0;
15647                            for (PackageSetting ps : allPackageSettings) {
15648                                final long status = ps.getDomainVerificationStatusForUser(userId);
15649                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15650                                    continue;
15651                                }
15652                                pw.println(prefix + "Package: " + ps.name);
15653                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15654                                String statusStr = IntentFilterVerificationInfo.
15655                                        getStatusStringFromValue(status);
15656                                pw.println(prefix + "Status:  " + statusStr);
15657                                pw.println();
15658                                count++;
15659                            }
15660                            if (count == 0) {
15661                                pw.println(prefix + "No configured app linkages.");
15662                                pw.println();
15663                            }
15664                        }
15665                    }
15666                }
15667            }
15668
15669            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15670                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15671                if (packageName == null && permissionNames == null) {
15672                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15673                        if (iperm == 0) {
15674                            if (dumpState.onTitlePrinted())
15675                                pw.println();
15676                            pw.println("AppOp Permissions:");
15677                        }
15678                        pw.print("  AppOp Permission ");
15679                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15680                        pw.println(":");
15681                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15682                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15683                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15684                        }
15685                    }
15686                }
15687            }
15688
15689            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15690                boolean printedSomething = false;
15691                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15692                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15693                        continue;
15694                    }
15695                    if (!printedSomething) {
15696                        if (dumpState.onTitlePrinted())
15697                            pw.println();
15698                        pw.println("Registered ContentProviders:");
15699                        printedSomething = true;
15700                    }
15701                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15702                    pw.print("    "); pw.println(p.toString());
15703                }
15704                printedSomething = false;
15705                for (Map.Entry<String, PackageParser.Provider> entry :
15706                        mProvidersByAuthority.entrySet()) {
15707                    PackageParser.Provider p = entry.getValue();
15708                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15709                        continue;
15710                    }
15711                    if (!printedSomething) {
15712                        if (dumpState.onTitlePrinted())
15713                            pw.println();
15714                        pw.println("ContentProvider Authorities:");
15715                        printedSomething = true;
15716                    }
15717                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15718                    pw.print("    "); pw.println(p.toString());
15719                    if (p.info != null && p.info.applicationInfo != null) {
15720                        final String appInfo = p.info.applicationInfo.toString();
15721                        pw.print("      applicationInfo="); pw.println(appInfo);
15722                    }
15723                }
15724            }
15725
15726            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15727                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15728            }
15729
15730            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15731                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15732            }
15733
15734            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15735                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15736            }
15737
15738            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15739                // XXX should handle packageName != null by dumping only install data that
15740                // the given package is involved with.
15741                if (dumpState.onTitlePrinted()) pw.println();
15742                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15743            }
15744
15745            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15746                if (dumpState.onTitlePrinted()) pw.println();
15747                mSettings.dumpReadMessagesLPr(pw, dumpState);
15748
15749                pw.println();
15750                pw.println("Package warning messages:");
15751                BufferedReader in = null;
15752                String line = null;
15753                try {
15754                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15755                    while ((line = in.readLine()) != null) {
15756                        if (line.contains("ignored: updated version")) continue;
15757                        pw.println(line);
15758                    }
15759                } catch (IOException ignored) {
15760                } finally {
15761                    IoUtils.closeQuietly(in);
15762                }
15763            }
15764
15765            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15766                BufferedReader in = null;
15767                String line = null;
15768                try {
15769                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15770                    while ((line = in.readLine()) != null) {
15771                        if (line.contains("ignored: updated version")) continue;
15772                        pw.print("msg,");
15773                        pw.println(line);
15774                    }
15775                } catch (IOException ignored) {
15776                } finally {
15777                    IoUtils.closeQuietly(in);
15778                }
15779            }
15780        }
15781    }
15782
15783    private String dumpDomainString(String packageName) {
15784        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15785        List<IntentFilter> filters = getAllIntentFilters(packageName);
15786
15787        ArraySet<String> result = new ArraySet<>();
15788        if (iviList.size() > 0) {
15789            for (IntentFilterVerificationInfo ivi : iviList) {
15790                for (String host : ivi.getDomains()) {
15791                    result.add(host);
15792                }
15793            }
15794        }
15795        if (filters != null && filters.size() > 0) {
15796            for (IntentFilter filter : filters) {
15797                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15798                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15799                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15800                    result.addAll(filter.getHostsList());
15801                }
15802            }
15803        }
15804
15805        StringBuilder sb = new StringBuilder(result.size() * 16);
15806        for (String domain : result) {
15807            if (sb.length() > 0) sb.append(" ");
15808            sb.append(domain);
15809        }
15810        return sb.toString();
15811    }
15812
15813    // ------- apps on sdcard specific code -------
15814    static final boolean DEBUG_SD_INSTALL = false;
15815
15816    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15817
15818    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15819
15820    private boolean mMediaMounted = false;
15821
15822    static String getEncryptKey() {
15823        try {
15824            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15825                    SD_ENCRYPTION_KEYSTORE_NAME);
15826            if (sdEncKey == null) {
15827                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15828                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15829                if (sdEncKey == null) {
15830                    Slog.e(TAG, "Failed to create encryption keys");
15831                    return null;
15832                }
15833            }
15834            return sdEncKey;
15835        } catch (NoSuchAlgorithmException nsae) {
15836            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15837            return null;
15838        } catch (IOException ioe) {
15839            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15840            return null;
15841        }
15842    }
15843
15844    /*
15845     * Update media status on PackageManager.
15846     */
15847    @Override
15848    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15849        int callingUid = Binder.getCallingUid();
15850        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15851            throw new SecurityException("Media status can only be updated by the system");
15852        }
15853        // reader; this apparently protects mMediaMounted, but should probably
15854        // be a different lock in that case.
15855        synchronized (mPackages) {
15856            Log.i(TAG, "Updating external media status from "
15857                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15858                    + (mediaStatus ? "mounted" : "unmounted"));
15859            if (DEBUG_SD_INSTALL)
15860                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15861                        + ", mMediaMounted=" + mMediaMounted);
15862            if (mediaStatus == mMediaMounted) {
15863                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15864                        : 0, -1);
15865                mHandler.sendMessage(msg);
15866                return;
15867            }
15868            mMediaMounted = mediaStatus;
15869        }
15870        // Queue up an async operation since the package installation may take a
15871        // little while.
15872        mHandler.post(new Runnable() {
15873            public void run() {
15874                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15875            }
15876        });
15877    }
15878
15879    /**
15880     * Called by MountService when the initial ASECs to scan are available.
15881     * Should block until all the ASEC containers are finished being scanned.
15882     */
15883    public void scanAvailableAsecs() {
15884        updateExternalMediaStatusInner(true, false, false);
15885        if (mShouldRestoreconData) {
15886            SELinuxMMAC.setRestoreconDone();
15887            mShouldRestoreconData = false;
15888        }
15889    }
15890
15891    /*
15892     * Collect information of applications on external media, map them against
15893     * existing containers and update information based on current mount status.
15894     * Please note that we always have to report status if reportStatus has been
15895     * set to true especially when unloading packages.
15896     */
15897    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15898            boolean externalStorage) {
15899        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15900        int[] uidArr = EmptyArray.INT;
15901
15902        final String[] list = PackageHelper.getSecureContainerList();
15903        if (ArrayUtils.isEmpty(list)) {
15904            Log.i(TAG, "No secure containers found");
15905        } else {
15906            // Process list of secure containers and categorize them
15907            // as active or stale based on their package internal state.
15908
15909            // reader
15910            synchronized (mPackages) {
15911                for (String cid : list) {
15912                    // Leave stages untouched for now; installer service owns them
15913                    if (PackageInstallerService.isStageName(cid)) continue;
15914
15915                    if (DEBUG_SD_INSTALL)
15916                        Log.i(TAG, "Processing container " + cid);
15917                    String pkgName = getAsecPackageName(cid);
15918                    if (pkgName == null) {
15919                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15920                        continue;
15921                    }
15922                    if (DEBUG_SD_INSTALL)
15923                        Log.i(TAG, "Looking for pkg : " + pkgName);
15924
15925                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15926                    if (ps == null) {
15927                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15928                        continue;
15929                    }
15930
15931                    /*
15932                     * Skip packages that are not external if we're unmounting
15933                     * external storage.
15934                     */
15935                    if (externalStorage && !isMounted && !isExternal(ps)) {
15936                        continue;
15937                    }
15938
15939                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15940                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15941                    // The package status is changed only if the code path
15942                    // matches between settings and the container id.
15943                    if (ps.codePathString != null
15944                            && ps.codePathString.startsWith(args.getCodePath())) {
15945                        if (DEBUG_SD_INSTALL) {
15946                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15947                                    + " at code path: " + ps.codePathString);
15948                        }
15949
15950                        // We do have a valid package installed on sdcard
15951                        processCids.put(args, ps.codePathString);
15952                        final int uid = ps.appId;
15953                        if (uid != -1) {
15954                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15955                        }
15956                    } else {
15957                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15958                                + ps.codePathString);
15959                    }
15960                }
15961            }
15962
15963            Arrays.sort(uidArr);
15964        }
15965
15966        // Process packages with valid entries.
15967        if (isMounted) {
15968            if (DEBUG_SD_INSTALL)
15969                Log.i(TAG, "Loading packages");
15970            loadMediaPackages(processCids, uidArr, externalStorage);
15971            startCleaningPackages();
15972            mInstallerService.onSecureContainersAvailable();
15973        } else {
15974            if (DEBUG_SD_INSTALL)
15975                Log.i(TAG, "Unloading packages");
15976            unloadMediaPackages(processCids, uidArr, reportStatus);
15977        }
15978    }
15979
15980    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15981            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15982        final int size = infos.size();
15983        final String[] packageNames = new String[size];
15984        final int[] packageUids = new int[size];
15985        for (int i = 0; i < size; i++) {
15986            final ApplicationInfo info = infos.get(i);
15987            packageNames[i] = info.packageName;
15988            packageUids[i] = info.uid;
15989        }
15990        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15991                finishedReceiver);
15992    }
15993
15994    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15995            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15996        sendResourcesChangedBroadcast(mediaStatus, replacing,
15997                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15998    }
15999
16000    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16001            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16002        int size = pkgList.length;
16003        if (size > 0) {
16004            // Send broadcasts here
16005            Bundle extras = new Bundle();
16006            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16007            if (uidArr != null) {
16008                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16009            }
16010            if (replacing) {
16011                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16012            }
16013            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16014                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16015            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16016        }
16017    }
16018
16019   /*
16020     * Look at potentially valid container ids from processCids If package
16021     * information doesn't match the one on record or package scanning fails,
16022     * the cid is added to list of removeCids. We currently don't delete stale
16023     * containers.
16024     */
16025    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16026            boolean externalStorage) {
16027        ArrayList<String> pkgList = new ArrayList<String>();
16028        Set<AsecInstallArgs> keys = processCids.keySet();
16029
16030        for (AsecInstallArgs args : keys) {
16031            String codePath = processCids.get(args);
16032            if (DEBUG_SD_INSTALL)
16033                Log.i(TAG, "Loading container : " + args.cid);
16034            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16035            try {
16036                // Make sure there are no container errors first.
16037                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16038                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16039                            + " when installing from sdcard");
16040                    continue;
16041                }
16042                // Check code path here.
16043                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16044                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16045                            + " does not match one in settings " + codePath);
16046                    continue;
16047                }
16048                // Parse package
16049                int parseFlags = mDefParseFlags;
16050                if (args.isExternalAsec()) {
16051                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16052                }
16053                if (args.isFwdLocked()) {
16054                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16055                }
16056
16057                synchronized (mInstallLock) {
16058                    PackageParser.Package pkg = null;
16059                    try {
16060                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16061                    } catch (PackageManagerException e) {
16062                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16063                    }
16064                    // Scan the package
16065                    if (pkg != null) {
16066                        /*
16067                         * TODO why is the lock being held? doPostInstall is
16068                         * called in other places without the lock. This needs
16069                         * to be straightened out.
16070                         */
16071                        // writer
16072                        synchronized (mPackages) {
16073                            retCode = PackageManager.INSTALL_SUCCEEDED;
16074                            pkgList.add(pkg.packageName);
16075                            // Post process args
16076                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16077                                    pkg.applicationInfo.uid);
16078                        }
16079                    } else {
16080                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16081                    }
16082                }
16083
16084            } finally {
16085                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16086                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16087                }
16088            }
16089        }
16090        // writer
16091        synchronized (mPackages) {
16092            // If the platform SDK has changed since the last time we booted,
16093            // we need to re-grant app permission to catch any new ones that
16094            // appear. This is really a hack, and means that apps can in some
16095            // cases get permissions that the user didn't initially explicitly
16096            // allow... it would be nice to have some better way to handle
16097            // this situation.
16098            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16099                    : mSettings.getInternalVersion();
16100            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16101                    : StorageManager.UUID_PRIVATE_INTERNAL;
16102
16103            int updateFlags = UPDATE_PERMISSIONS_ALL;
16104            if (ver.sdkVersion != mSdkVersion) {
16105                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16106                        + mSdkVersion + "; regranting permissions for external");
16107                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16108            }
16109            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16110
16111            // Yay, everything is now upgraded
16112            ver.forceCurrent();
16113
16114            // can downgrade to reader
16115            // Persist settings
16116            mSettings.writeLPr();
16117        }
16118        // Send a broadcast to let everyone know we are done processing
16119        if (pkgList.size() > 0) {
16120            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16121        }
16122    }
16123
16124   /*
16125     * Utility method to unload a list of specified containers
16126     */
16127    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16128        // Just unmount all valid containers.
16129        for (AsecInstallArgs arg : cidArgs) {
16130            synchronized (mInstallLock) {
16131                arg.doPostDeleteLI(false);
16132           }
16133       }
16134   }
16135
16136    /*
16137     * Unload packages mounted on external media. This involves deleting package
16138     * data from internal structures, sending broadcasts about diabled packages,
16139     * gc'ing to free up references, unmounting all secure containers
16140     * corresponding to packages on external media, and posting a
16141     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16142     * that we always have to post this message if status has been requested no
16143     * matter what.
16144     */
16145    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16146            final boolean reportStatus) {
16147        if (DEBUG_SD_INSTALL)
16148            Log.i(TAG, "unloading media packages");
16149        ArrayList<String> pkgList = new ArrayList<String>();
16150        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16151        final Set<AsecInstallArgs> keys = processCids.keySet();
16152        for (AsecInstallArgs args : keys) {
16153            String pkgName = args.getPackageName();
16154            if (DEBUG_SD_INSTALL)
16155                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16156            // Delete package internally
16157            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16158            synchronized (mInstallLock) {
16159                boolean res = deletePackageLI(pkgName, null, false, null, null,
16160                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16161                if (res) {
16162                    pkgList.add(pkgName);
16163                } else {
16164                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16165                    failedList.add(args);
16166                }
16167            }
16168        }
16169
16170        // reader
16171        synchronized (mPackages) {
16172            // We didn't update the settings after removing each package;
16173            // write them now for all packages.
16174            mSettings.writeLPr();
16175        }
16176
16177        // We have to absolutely send UPDATED_MEDIA_STATUS only
16178        // after confirming that all the receivers processed the ordered
16179        // broadcast when packages get disabled, force a gc to clean things up.
16180        // and unload all the containers.
16181        if (pkgList.size() > 0) {
16182            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16183                    new IIntentReceiver.Stub() {
16184                public void performReceive(Intent intent, int resultCode, String data,
16185                        Bundle extras, boolean ordered, boolean sticky,
16186                        int sendingUser) throws RemoteException {
16187                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16188                            reportStatus ? 1 : 0, 1, keys);
16189                    mHandler.sendMessage(msg);
16190                }
16191            });
16192        } else {
16193            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16194                    keys);
16195            mHandler.sendMessage(msg);
16196        }
16197    }
16198
16199    private void loadPrivatePackages(final VolumeInfo vol) {
16200        mHandler.post(new Runnable() {
16201            @Override
16202            public void run() {
16203                loadPrivatePackagesInner(vol);
16204            }
16205        });
16206    }
16207
16208    private void loadPrivatePackagesInner(VolumeInfo vol) {
16209        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16210        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16211
16212        final VersionInfo ver;
16213        final List<PackageSetting> packages;
16214        synchronized (mPackages) {
16215            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16216            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16217        }
16218
16219        for (PackageSetting ps : packages) {
16220            synchronized (mInstallLock) {
16221                final PackageParser.Package pkg;
16222                try {
16223                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16224                    loaded.add(pkg.applicationInfo);
16225                } catch (PackageManagerException e) {
16226                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16227                }
16228
16229                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16230                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16231                }
16232            }
16233        }
16234
16235        synchronized (mPackages) {
16236            int updateFlags = UPDATE_PERMISSIONS_ALL;
16237            if (ver.sdkVersion != mSdkVersion) {
16238                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16239                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16240                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16241            }
16242            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16243
16244            // Yay, everything is now upgraded
16245            ver.forceCurrent();
16246
16247            mSettings.writeLPr();
16248        }
16249
16250        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16251        sendResourcesChangedBroadcast(true, false, loaded, null);
16252    }
16253
16254    private void unloadPrivatePackages(final VolumeInfo vol) {
16255        mHandler.post(new Runnable() {
16256            @Override
16257            public void run() {
16258                unloadPrivatePackagesInner(vol);
16259            }
16260        });
16261    }
16262
16263    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16264        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16265        synchronized (mInstallLock) {
16266        synchronized (mPackages) {
16267            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16268            for (PackageSetting ps : packages) {
16269                if (ps.pkg == null) continue;
16270
16271                final ApplicationInfo info = ps.pkg.applicationInfo;
16272                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16273                if (deletePackageLI(ps.name, null, false, null, null,
16274                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16275                    unloaded.add(info);
16276                } else {
16277                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16278                }
16279            }
16280
16281            mSettings.writeLPr();
16282        }
16283        }
16284
16285        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16286        sendResourcesChangedBroadcast(false, false, unloaded, null);
16287    }
16288
16289    /**
16290     * Examine all users present on given mounted volume, and destroy data
16291     * belonging to users that are no longer valid, or whose user ID has been
16292     * recycled.
16293     */
16294    private void reconcileUsers(String volumeUuid) {
16295        final File[] files = FileUtils
16296                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16297        for (File file : files) {
16298            if (!file.isDirectory()) continue;
16299
16300            final int userId;
16301            final UserInfo info;
16302            try {
16303                userId = Integer.parseInt(file.getName());
16304                info = sUserManager.getUserInfo(userId);
16305            } catch (NumberFormatException e) {
16306                Slog.w(TAG, "Invalid user directory " + file);
16307                continue;
16308            }
16309
16310            boolean destroyUser = false;
16311            if (info == null) {
16312                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16313                        + " because no matching user was found");
16314                destroyUser = true;
16315            } else {
16316                try {
16317                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16318                } catch (IOException e) {
16319                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16320                            + " because we failed to enforce serial number: " + e);
16321                    destroyUser = true;
16322                }
16323            }
16324
16325            if (destroyUser) {
16326                synchronized (mInstallLock) {
16327                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16328                }
16329            }
16330        }
16331
16332        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16333        final UserManager um = mContext.getSystemService(UserManager.class);
16334        for (UserInfo user : um.getUsers()) {
16335            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16336            if (userDir.exists()) continue;
16337
16338            try {
16339                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber);
16340                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16341            } catch (IOException e) {
16342                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16343            }
16344        }
16345    }
16346
16347    /**
16348     * Examine all apps present on given mounted volume, and destroy apps that
16349     * aren't expected, either due to uninstallation or reinstallation on
16350     * another volume.
16351     */
16352    private void reconcileApps(String volumeUuid) {
16353        final File[] files = FileUtils
16354                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16355        for (File file : files) {
16356            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16357                    && !PackageInstallerService.isStageName(file.getName());
16358            if (!isPackage) {
16359                // Ignore entries which are not packages
16360                continue;
16361            }
16362
16363            boolean destroyApp = false;
16364            String packageName = null;
16365            try {
16366                final PackageLite pkg = PackageParser.parsePackageLite(file,
16367                        PackageParser.PARSE_MUST_BE_APK);
16368                packageName = pkg.packageName;
16369
16370                synchronized (mPackages) {
16371                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16372                    if (ps == null) {
16373                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16374                                + volumeUuid + " because we found no install record");
16375                        destroyApp = true;
16376                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16377                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16378                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16379                        destroyApp = true;
16380                    }
16381                }
16382
16383            } catch (PackageParserException e) {
16384                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16385                destroyApp = true;
16386            }
16387
16388            if (destroyApp) {
16389                synchronized (mInstallLock) {
16390                    if (packageName != null) {
16391                        removeDataDirsLI(volumeUuid, packageName);
16392                    }
16393                    if (file.isDirectory()) {
16394                        mInstaller.rmPackageDir(file.getAbsolutePath());
16395                    } else {
16396                        file.delete();
16397                    }
16398                }
16399            }
16400        }
16401    }
16402
16403    private void unfreezePackage(String packageName) {
16404        synchronized (mPackages) {
16405            final PackageSetting ps = mSettings.mPackages.get(packageName);
16406            if (ps != null) {
16407                ps.frozen = false;
16408            }
16409        }
16410    }
16411
16412    @Override
16413    public int movePackage(final String packageName, final String volumeUuid) {
16414        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16415
16416        final int moveId = mNextMoveId.getAndIncrement();
16417        mHandler.post(new Runnable() {
16418            @Override
16419            public void run() {
16420                try {
16421                    movePackageInternal(packageName, volumeUuid, moveId);
16422                } catch (PackageManagerException e) {
16423                    Slog.w(TAG, "Failed to move " + packageName, e);
16424                    mMoveCallbacks.notifyStatusChanged(moveId,
16425                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16426                }
16427            }
16428        });
16429        return moveId;
16430    }
16431
16432    private void movePackageInternal(final String packageName, final String volumeUuid,
16433            final int moveId) throws PackageManagerException {
16434        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16435        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16436        final PackageManager pm = mContext.getPackageManager();
16437
16438        final boolean currentAsec;
16439        final String currentVolumeUuid;
16440        final File codeFile;
16441        final String installerPackageName;
16442        final String packageAbiOverride;
16443        final int appId;
16444        final String seinfo;
16445        final String label;
16446
16447        // reader
16448        synchronized (mPackages) {
16449            final PackageParser.Package pkg = mPackages.get(packageName);
16450            final PackageSetting ps = mSettings.mPackages.get(packageName);
16451            if (pkg == null || ps == null) {
16452                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16453            }
16454
16455            if (pkg.applicationInfo.isSystemApp()) {
16456                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16457                        "Cannot move system application");
16458            }
16459
16460            if (pkg.applicationInfo.isExternalAsec()) {
16461                currentAsec = true;
16462                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16463            } else if (pkg.applicationInfo.isForwardLocked()) {
16464                currentAsec = true;
16465                currentVolumeUuid = "forward_locked";
16466            } else {
16467                currentAsec = false;
16468                currentVolumeUuid = ps.volumeUuid;
16469
16470                final File probe = new File(pkg.codePath);
16471                final File probeOat = new File(probe, "oat");
16472                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16473                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16474                            "Move only supported for modern cluster style installs");
16475                }
16476            }
16477
16478            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16479                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16480                        "Package already moved to " + volumeUuid);
16481            }
16482
16483            if (ps.frozen) {
16484                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16485                        "Failed to move already frozen package");
16486            }
16487            ps.frozen = true;
16488
16489            codeFile = new File(pkg.codePath);
16490            installerPackageName = ps.installerPackageName;
16491            packageAbiOverride = ps.cpuAbiOverrideString;
16492            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16493            seinfo = pkg.applicationInfo.seinfo;
16494            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16495        }
16496
16497        // Now that we're guarded by frozen state, kill app during move
16498        final long token = Binder.clearCallingIdentity();
16499        try {
16500            killApplication(packageName, appId, "move pkg");
16501        } finally {
16502            Binder.restoreCallingIdentity(token);
16503        }
16504
16505        final Bundle extras = new Bundle();
16506        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16507        extras.putString(Intent.EXTRA_TITLE, label);
16508        mMoveCallbacks.notifyCreated(moveId, extras);
16509
16510        int installFlags;
16511        final boolean moveCompleteApp;
16512        final File measurePath;
16513
16514        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16515            installFlags = INSTALL_INTERNAL;
16516            moveCompleteApp = !currentAsec;
16517            measurePath = Environment.getDataAppDirectory(volumeUuid);
16518        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16519            installFlags = INSTALL_EXTERNAL;
16520            moveCompleteApp = false;
16521            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16522        } else {
16523            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16524            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16525                    || !volume.isMountedWritable()) {
16526                unfreezePackage(packageName);
16527                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16528                        "Move location not mounted private volume");
16529            }
16530
16531            Preconditions.checkState(!currentAsec);
16532
16533            installFlags = INSTALL_INTERNAL;
16534            moveCompleteApp = true;
16535            measurePath = Environment.getDataAppDirectory(volumeUuid);
16536        }
16537
16538        final PackageStats stats = new PackageStats(null, -1);
16539        synchronized (mInstaller) {
16540            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16541                unfreezePackage(packageName);
16542                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16543                        "Failed to measure package size");
16544            }
16545        }
16546
16547        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16548                + stats.dataSize);
16549
16550        final long startFreeBytes = measurePath.getFreeSpace();
16551        final long sizeBytes;
16552        if (moveCompleteApp) {
16553            sizeBytes = stats.codeSize + stats.dataSize;
16554        } else {
16555            sizeBytes = stats.codeSize;
16556        }
16557
16558        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16559            unfreezePackage(packageName);
16560            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16561                    "Not enough free space to move");
16562        }
16563
16564        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16565
16566        final CountDownLatch installedLatch = new CountDownLatch(1);
16567        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16568            @Override
16569            public void onUserActionRequired(Intent intent) throws RemoteException {
16570                throw new IllegalStateException();
16571            }
16572
16573            @Override
16574            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16575                    Bundle extras) throws RemoteException {
16576                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16577                        + PackageManager.installStatusToString(returnCode, msg));
16578
16579                installedLatch.countDown();
16580
16581                // Regardless of success or failure of the move operation,
16582                // always unfreeze the package
16583                unfreezePackage(packageName);
16584
16585                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16586                switch (status) {
16587                    case PackageInstaller.STATUS_SUCCESS:
16588                        mMoveCallbacks.notifyStatusChanged(moveId,
16589                                PackageManager.MOVE_SUCCEEDED);
16590                        break;
16591                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16592                        mMoveCallbacks.notifyStatusChanged(moveId,
16593                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16594                        break;
16595                    default:
16596                        mMoveCallbacks.notifyStatusChanged(moveId,
16597                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16598                        break;
16599                }
16600            }
16601        };
16602
16603        final MoveInfo move;
16604        if (moveCompleteApp) {
16605            // Kick off a thread to report progress estimates
16606            new Thread() {
16607                @Override
16608                public void run() {
16609                    while (true) {
16610                        try {
16611                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16612                                break;
16613                            }
16614                        } catch (InterruptedException ignored) {
16615                        }
16616
16617                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16618                        final int progress = 10 + (int) MathUtils.constrain(
16619                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16620                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16621                    }
16622                }
16623            }.start();
16624
16625            final String dataAppName = codeFile.getName();
16626            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16627                    dataAppName, appId, seinfo);
16628        } else {
16629            move = null;
16630        }
16631
16632        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16633
16634        final Message msg = mHandler.obtainMessage(INIT_COPY);
16635        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16636        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16637                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16638        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16639        msg.obj = params;
16640
16641        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16642                System.identityHashCode(msg.obj));
16643        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16644                System.identityHashCode(msg.obj));
16645
16646        mHandler.sendMessage(msg);
16647    }
16648
16649    @Override
16650    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16651        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16652
16653        final int realMoveId = mNextMoveId.getAndIncrement();
16654        final Bundle extras = new Bundle();
16655        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16656        mMoveCallbacks.notifyCreated(realMoveId, extras);
16657
16658        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16659            @Override
16660            public void onCreated(int moveId, Bundle extras) {
16661                // Ignored
16662            }
16663
16664            @Override
16665            public void onStatusChanged(int moveId, int status, long estMillis) {
16666                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16667            }
16668        };
16669
16670        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16671        storage.setPrimaryStorageUuid(volumeUuid, callback);
16672        return realMoveId;
16673    }
16674
16675    @Override
16676    public int getMoveStatus(int moveId) {
16677        mContext.enforceCallingOrSelfPermission(
16678                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16679        return mMoveCallbacks.mLastStatus.get(moveId);
16680    }
16681
16682    @Override
16683    public void registerMoveCallback(IPackageMoveObserver callback) {
16684        mContext.enforceCallingOrSelfPermission(
16685                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16686        mMoveCallbacks.register(callback);
16687    }
16688
16689    @Override
16690    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16691        mContext.enforceCallingOrSelfPermission(
16692                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16693        mMoveCallbacks.unregister(callback);
16694    }
16695
16696    @Override
16697    public boolean setInstallLocation(int loc) {
16698        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16699                null);
16700        if (getInstallLocation() == loc) {
16701            return true;
16702        }
16703        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16704                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16705            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16706                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16707            return true;
16708        }
16709        return false;
16710   }
16711
16712    @Override
16713    public int getInstallLocation() {
16714        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16715                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16716                PackageHelper.APP_INSTALL_AUTO);
16717    }
16718
16719    /** Called by UserManagerService */
16720    void cleanUpUser(UserManagerService userManager, int userHandle) {
16721        synchronized (mPackages) {
16722            mDirtyUsers.remove(userHandle);
16723            mUserNeedsBadging.delete(userHandle);
16724            mSettings.removeUserLPw(userHandle);
16725            mPendingBroadcasts.remove(userHandle);
16726        }
16727        synchronized (mInstallLock) {
16728            if (mInstaller != null) {
16729                final StorageManager storage = mContext.getSystemService(StorageManager.class);
16730                for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16731                    final String volumeUuid = vol.getFsUuid();
16732                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16733                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16734                }
16735            }
16736            synchronized (mPackages) {
16737                removeUnusedPackagesLILPw(userManager, userHandle);
16738            }
16739        }
16740    }
16741
16742    /**
16743     * We're removing userHandle and would like to remove any downloaded packages
16744     * that are no longer in use by any other user.
16745     * @param userHandle the user being removed
16746     */
16747    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16748        final boolean DEBUG_CLEAN_APKS = false;
16749        int [] users = userManager.getUserIds();
16750        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16751        while (psit.hasNext()) {
16752            PackageSetting ps = psit.next();
16753            if (ps.pkg == null) {
16754                continue;
16755            }
16756            final String packageName = ps.pkg.packageName;
16757            // Skip over if system app
16758            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16759                continue;
16760            }
16761            if (DEBUG_CLEAN_APKS) {
16762                Slog.i(TAG, "Checking package " + packageName);
16763            }
16764            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16765            if (keep) {
16766                if (DEBUG_CLEAN_APKS) {
16767                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16768                }
16769            } else {
16770                for (int i = 0; i < users.length; i++) {
16771                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16772                        keep = true;
16773                        if (DEBUG_CLEAN_APKS) {
16774                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
16775                                    + users[i]);
16776                        }
16777                        break;
16778                    }
16779                }
16780            }
16781            if (!keep) {
16782                if (DEBUG_CLEAN_APKS) {
16783                    Slog.i(TAG, "  Removing package " + packageName);
16784                }
16785                mHandler.post(new Runnable() {
16786                    public void run() {
16787                        deletePackageX(packageName, userHandle, 0);
16788                    } //end run
16789                });
16790            }
16791        }
16792    }
16793
16794    /** Called by UserManagerService */
16795    void createNewUser(int userHandle) {
16796        if (mInstaller != null) {
16797            synchronized (mInstallLock) {
16798                synchronized (mPackages) {
16799                    mInstaller.createUserConfig(userHandle);
16800                    mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16801                }
16802            }
16803            synchronized (mPackages) {
16804                applyFactoryDefaultBrowserLPw(userHandle);
16805                primeDomainVerificationsLPw(userHandle);
16806            }
16807        }
16808    }
16809
16810    void newUserCreated(final int userHandle) {
16811        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16812        // If permission review for legacy apps is required, we represent
16813        // dagerous permissions for such apps as always granted runtime
16814        // permissions to keep per user flag state whether review is needed.
16815        // Hence, if a new user is added we have to propagate dangerous
16816        // permission grants for these legacy apps.
16817        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
16818            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
16819                    | UPDATE_PERMISSIONS_REPLACE_ALL);
16820        }
16821    }
16822
16823    @Override
16824    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16825        mContext.enforceCallingOrSelfPermission(
16826                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16827                "Only package verification agents can read the verifier device identity");
16828
16829        synchronized (mPackages) {
16830            return mSettings.getVerifierDeviceIdentityLPw();
16831        }
16832    }
16833
16834    @Override
16835    public void setPermissionEnforced(String permission, boolean enforced) {
16836        // TODO: Now that we no longer change GID for storage, this should to away.
16837        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16838                "setPermissionEnforced");
16839        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16840            synchronized (mPackages) {
16841                if (mSettings.mReadExternalStorageEnforced == null
16842                        || mSettings.mReadExternalStorageEnforced != enforced) {
16843                    mSettings.mReadExternalStorageEnforced = enforced;
16844                    mSettings.writeLPr();
16845                }
16846            }
16847            // kill any non-foreground processes so we restart them and
16848            // grant/revoke the GID.
16849            final IActivityManager am = ActivityManagerNative.getDefault();
16850            if (am != null) {
16851                final long token = Binder.clearCallingIdentity();
16852                try {
16853                    am.killProcessesBelowForeground("setPermissionEnforcement");
16854                } catch (RemoteException e) {
16855                } finally {
16856                    Binder.restoreCallingIdentity(token);
16857                }
16858            }
16859        } else {
16860            throw new IllegalArgumentException("No selective enforcement for " + permission);
16861        }
16862    }
16863
16864    @Override
16865    @Deprecated
16866    public boolean isPermissionEnforced(String permission) {
16867        return true;
16868    }
16869
16870    @Override
16871    public boolean isStorageLow() {
16872        final long token = Binder.clearCallingIdentity();
16873        try {
16874            final DeviceStorageMonitorInternal
16875                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16876            if (dsm != null) {
16877                return dsm.isMemoryLow();
16878            } else {
16879                return false;
16880            }
16881        } finally {
16882            Binder.restoreCallingIdentity(token);
16883        }
16884    }
16885
16886    @Override
16887    public IPackageInstaller getPackageInstaller() {
16888        return mInstallerService;
16889    }
16890
16891    private boolean userNeedsBadging(int userId) {
16892        int index = mUserNeedsBadging.indexOfKey(userId);
16893        if (index < 0) {
16894            final UserInfo userInfo;
16895            final long token = Binder.clearCallingIdentity();
16896            try {
16897                userInfo = sUserManager.getUserInfo(userId);
16898            } finally {
16899                Binder.restoreCallingIdentity(token);
16900            }
16901            final boolean b;
16902            if (userInfo != null && userInfo.isManagedProfile()) {
16903                b = true;
16904            } else {
16905                b = false;
16906            }
16907            mUserNeedsBadging.put(userId, b);
16908            return b;
16909        }
16910        return mUserNeedsBadging.valueAt(index);
16911    }
16912
16913    @Override
16914    public KeySet getKeySetByAlias(String packageName, String alias) {
16915        if (packageName == null || alias == null) {
16916            return null;
16917        }
16918        synchronized(mPackages) {
16919            final PackageParser.Package pkg = mPackages.get(packageName);
16920            if (pkg == null) {
16921                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16922                throw new IllegalArgumentException("Unknown package: " + packageName);
16923            }
16924            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16925            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16926        }
16927    }
16928
16929    @Override
16930    public KeySet getSigningKeySet(String packageName) {
16931        if (packageName == null) {
16932            return null;
16933        }
16934        synchronized(mPackages) {
16935            final PackageParser.Package pkg = mPackages.get(packageName);
16936            if (pkg == null) {
16937                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16938                throw new IllegalArgumentException("Unknown package: " + packageName);
16939            }
16940            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16941                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16942                throw new SecurityException("May not access signing KeySet of other apps.");
16943            }
16944            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16945            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16946        }
16947    }
16948
16949    @Override
16950    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16951        if (packageName == null || ks == null) {
16952            return false;
16953        }
16954        synchronized(mPackages) {
16955            final PackageParser.Package pkg = mPackages.get(packageName);
16956            if (pkg == null) {
16957                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16958                throw new IllegalArgumentException("Unknown package: " + packageName);
16959            }
16960            IBinder ksh = ks.getToken();
16961            if (ksh instanceof KeySetHandle) {
16962                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16963                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16964            }
16965            return false;
16966        }
16967    }
16968
16969    @Override
16970    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16971        if (packageName == null || ks == null) {
16972            return false;
16973        }
16974        synchronized(mPackages) {
16975            final PackageParser.Package pkg = mPackages.get(packageName);
16976            if (pkg == null) {
16977                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16978                throw new IllegalArgumentException("Unknown package: " + packageName);
16979            }
16980            IBinder ksh = ks.getToken();
16981            if (ksh instanceof KeySetHandle) {
16982                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16983                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16984            }
16985            return false;
16986        }
16987    }
16988
16989    private void deletePackageIfUnusedLPr(final String packageName) {
16990        PackageSetting ps = mSettings.mPackages.get(packageName);
16991        if (ps == null) {
16992            return;
16993        }
16994        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
16995            // TODO Implement atomic delete if package is unused
16996            // It is currently possible that the package will be deleted even if it is installed
16997            // after this method returns.
16998            mHandler.post(new Runnable() {
16999                public void run() {
17000                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17001                }
17002            });
17003        }
17004    }
17005
17006    /**
17007     * Check and throw if the given before/after packages would be considered a
17008     * downgrade.
17009     */
17010    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17011            throws PackageManagerException {
17012        if (after.versionCode < before.mVersionCode) {
17013            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17014                    "Update version code " + after.versionCode + " is older than current "
17015                    + before.mVersionCode);
17016        } else if (after.versionCode == before.mVersionCode) {
17017            if (after.baseRevisionCode < before.baseRevisionCode) {
17018                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17019                        "Update base revision code " + after.baseRevisionCode
17020                        + " is older than current " + before.baseRevisionCode);
17021            }
17022
17023            if (!ArrayUtils.isEmpty(after.splitNames)) {
17024                for (int i = 0; i < after.splitNames.length; i++) {
17025                    final String splitName = after.splitNames[i];
17026                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17027                    if (j != -1) {
17028                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17029                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17030                                    "Update split " + splitName + " revision code "
17031                                    + after.splitRevisionCodes[i] + " is older than current "
17032                                    + before.splitRevisionCodes[j]);
17033                        }
17034                    }
17035                }
17036            }
17037        }
17038    }
17039
17040    private static class MoveCallbacks extends Handler {
17041        private static final int MSG_CREATED = 1;
17042        private static final int MSG_STATUS_CHANGED = 2;
17043
17044        private final RemoteCallbackList<IPackageMoveObserver>
17045                mCallbacks = new RemoteCallbackList<>();
17046
17047        private final SparseIntArray mLastStatus = new SparseIntArray();
17048
17049        public MoveCallbacks(Looper looper) {
17050            super(looper);
17051        }
17052
17053        public void register(IPackageMoveObserver callback) {
17054            mCallbacks.register(callback);
17055        }
17056
17057        public void unregister(IPackageMoveObserver callback) {
17058            mCallbacks.unregister(callback);
17059        }
17060
17061        @Override
17062        public void handleMessage(Message msg) {
17063            final SomeArgs args = (SomeArgs) msg.obj;
17064            final int n = mCallbacks.beginBroadcast();
17065            for (int i = 0; i < n; i++) {
17066                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17067                try {
17068                    invokeCallback(callback, msg.what, args);
17069                } catch (RemoteException ignored) {
17070                }
17071            }
17072            mCallbacks.finishBroadcast();
17073            args.recycle();
17074        }
17075
17076        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17077                throws RemoteException {
17078            switch (what) {
17079                case MSG_CREATED: {
17080                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17081                    break;
17082                }
17083                case MSG_STATUS_CHANGED: {
17084                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17085                    break;
17086                }
17087            }
17088        }
17089
17090        private void notifyCreated(int moveId, Bundle extras) {
17091            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17092
17093            final SomeArgs args = SomeArgs.obtain();
17094            args.argi1 = moveId;
17095            args.arg2 = extras;
17096            obtainMessage(MSG_CREATED, args).sendToTarget();
17097        }
17098
17099        private void notifyStatusChanged(int moveId, int status) {
17100            notifyStatusChanged(moveId, status, -1);
17101        }
17102
17103        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17104            Slog.v(TAG, "Move " + moveId + " status " + status);
17105
17106            final SomeArgs args = SomeArgs.obtain();
17107            args.argi1 = moveId;
17108            args.argi2 = status;
17109            args.arg3 = estMillis;
17110            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17111
17112            synchronized (mLastStatus) {
17113                mLastStatus.put(moveId, status);
17114            }
17115        }
17116    }
17117
17118    private final class OnPermissionChangeListeners extends Handler {
17119        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17120
17121        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17122                new RemoteCallbackList<>();
17123
17124        public OnPermissionChangeListeners(Looper looper) {
17125            super(looper);
17126        }
17127
17128        @Override
17129        public void handleMessage(Message msg) {
17130            switch (msg.what) {
17131                case MSG_ON_PERMISSIONS_CHANGED: {
17132                    final int uid = msg.arg1;
17133                    handleOnPermissionsChanged(uid);
17134                } break;
17135            }
17136        }
17137
17138        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17139            mPermissionListeners.register(listener);
17140
17141        }
17142
17143        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17144            mPermissionListeners.unregister(listener);
17145        }
17146
17147        public void onPermissionsChanged(int uid) {
17148            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17149                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17150            }
17151        }
17152
17153        private void handleOnPermissionsChanged(int uid) {
17154            final int count = mPermissionListeners.beginBroadcast();
17155            try {
17156                for (int i = 0; i < count; i++) {
17157                    IOnPermissionsChangeListener callback = mPermissionListeners
17158                            .getBroadcastItem(i);
17159                    try {
17160                        callback.onPermissionsChanged(uid);
17161                    } catch (RemoteException e) {
17162                        Log.e(TAG, "Permission listener is dead", e);
17163                    }
17164                }
17165            } finally {
17166                mPermissionListeners.finishBroadcast();
17167            }
17168        }
17169    }
17170
17171    private class PackageManagerInternalImpl extends PackageManagerInternal {
17172        @Override
17173        public void setLocationPackagesProvider(PackagesProvider provider) {
17174            synchronized (mPackages) {
17175                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17176            }
17177        }
17178
17179        @Override
17180        public void setImePackagesProvider(PackagesProvider provider) {
17181            synchronized (mPackages) {
17182                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17183            }
17184        }
17185
17186        @Override
17187        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17188            synchronized (mPackages) {
17189                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17190            }
17191        }
17192
17193        @Override
17194        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17195            synchronized (mPackages) {
17196                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17197            }
17198        }
17199
17200        @Override
17201        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17202            synchronized (mPackages) {
17203                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17204            }
17205        }
17206
17207        @Override
17208        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17209            synchronized (mPackages) {
17210                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17211            }
17212        }
17213
17214        @Override
17215        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17216            synchronized (mPackages) {
17217                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17218            }
17219        }
17220
17221        @Override
17222        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17223            synchronized (mPackages) {
17224                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17225                        packageName, userId);
17226            }
17227        }
17228
17229        @Override
17230        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17231            synchronized (mPackages) {
17232                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17233                        packageName, userId);
17234            }
17235        }
17236
17237        @Override
17238        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17239            synchronized (mPackages) {
17240                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17241                        packageName, userId);
17242            }
17243        }
17244
17245        @Override
17246        public void setKeepUninstalledPackages(final List<String> packageList) {
17247            Preconditions.checkNotNull(packageList);
17248            List<String> removedFromList = null;
17249            synchronized (mPackages) {
17250                if (mKeepUninstalledPackages != null) {
17251                    final int packagesCount = mKeepUninstalledPackages.size();
17252                    for (int i = 0; i < packagesCount; i++) {
17253                        String oldPackage = mKeepUninstalledPackages.get(i);
17254                        if (packageList != null && packageList.contains(oldPackage)) {
17255                            continue;
17256                        }
17257                        if (removedFromList == null) {
17258                            removedFromList = new ArrayList<>();
17259                        }
17260                        removedFromList.add(oldPackage);
17261                    }
17262                }
17263                mKeepUninstalledPackages = new ArrayList<>(packageList);
17264                if (removedFromList != null) {
17265                    final int removedCount = removedFromList.size();
17266                    for (int i = 0; i < removedCount; i++) {
17267                        deletePackageIfUnusedLPr(removedFromList.get(i));
17268                    }
17269                }
17270            }
17271        }
17272
17273        @Override
17274        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17275            synchronized (mPackages) {
17276                // If we do not support permission review, done.
17277                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17278                    return false;
17279                }
17280
17281                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17282                if (packageSetting == null) {
17283                    return false;
17284                }
17285
17286                // Permission review applies only to apps not supporting the new permission model.
17287                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17288                    return false;
17289                }
17290
17291                // Legacy apps have the permission and get user consent on launch.
17292                PermissionsState permissionsState = packageSetting.getPermissionsState();
17293                return permissionsState.isPermissionReviewRequired(userId);
17294            }
17295        }
17296    }
17297
17298    @Override
17299    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17300        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17301        synchronized (mPackages) {
17302            final long identity = Binder.clearCallingIdentity();
17303            try {
17304                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17305                        packageNames, userId);
17306            } finally {
17307                Binder.restoreCallingIdentity(identity);
17308            }
17309        }
17310    }
17311
17312    private static void enforceSystemOrPhoneCaller(String tag) {
17313        int callingUid = Binder.getCallingUid();
17314        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17315            throw new SecurityException(
17316                    "Cannot call " + tag + " from UID " + callingUid);
17317        }
17318    }
17319}
17320