PackageManagerService.java revision 2658cb002abae9341c9a82bfeaed764ba5bf97c8
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_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.system.OsConstants.O_CREAT;
71import static android.system.OsConstants.O_RDWR;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
76import static com.android.internal.util.ArrayUtils.appendInt;
77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
85
86import android.Manifest;
87import android.app.ActivityManager;
88import android.app.ActivityManagerNative;
89import android.app.AppGlobals;
90import android.app.IActivityManager;
91import android.app.admin.IDevicePolicyManager;
92import android.app.backup.IBackupManager;
93import android.app.usage.UsageStats;
94import android.app.usage.UsageStatsManager;
95import android.content.BroadcastReceiver;
96import android.content.ComponentName;
97import android.content.Context;
98import android.content.IIntentReceiver;
99import android.content.Intent;
100import android.content.IntentFilter;
101import android.content.IntentSender;
102import android.content.IntentSender.SendIntentException;
103import android.content.ServiceConnection;
104import android.content.pm.ActivityInfo;
105import android.content.pm.ApplicationInfo;
106import android.content.pm.FeatureInfo;
107import android.content.pm.IOnPermissionsChangeListener;
108import android.content.pm.IPackageDataObserver;
109import android.content.pm.IPackageDeleteObserver;
110import android.content.pm.IPackageDeleteObserver2;
111import android.content.pm.IPackageInstallObserver2;
112import android.content.pm.IPackageInstaller;
113import android.content.pm.IPackageManager;
114import android.content.pm.IPackageMoveObserver;
115import android.content.pm.IPackageStatsObserver;
116import android.content.pm.InstrumentationInfo;
117import android.content.pm.IntentFilterVerificationInfo;
118import android.content.pm.KeySet;
119import android.content.pm.ManifestDigest;
120import android.content.pm.PackageCleanItem;
121import android.content.pm.PackageInfo;
122import android.content.pm.PackageInfoLite;
123import android.content.pm.PackageInstaller;
124import android.content.pm.PackageManager;
125import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
126import android.content.pm.PackageManagerInternal;
127import android.content.pm.PackageParser;
128import android.content.pm.PackageParser.ActivityIntentInfo;
129import android.content.pm.PackageParser.PackageLite;
130import android.content.pm.PackageParser.PackageParserException;
131import android.content.pm.PackageStats;
132import android.content.pm.PackageUserState;
133import android.content.pm.ParceledListSlice;
134import android.content.pm.PermissionGroupInfo;
135import android.content.pm.PermissionInfo;
136import android.content.pm.ProviderInfo;
137import android.content.pm.ResolveInfo;
138import android.content.pm.ServiceInfo;
139import android.content.pm.Signature;
140import android.content.pm.UserInfo;
141import android.content.pm.VerificationParams;
142import android.content.pm.VerifierDeviceIdentity;
143import android.content.pm.VerifierInfo;
144import android.content.res.Resources;
145import android.hardware.display.DisplayManager;
146import android.net.Uri;
147import android.os.Debug;
148import android.os.Binder;
149import android.os.Build;
150import android.os.Bundle;
151import android.os.Environment;
152import android.os.Environment.UserEnvironment;
153import android.os.FileUtils;
154import android.os.Handler;
155import android.os.IBinder;
156import android.os.Looper;
157import android.os.Message;
158import android.os.Parcel;
159import android.os.ParcelFileDescriptor;
160import android.os.Process;
161import android.os.RemoteCallbackList;
162import android.os.RemoteException;
163import android.os.SELinux;
164import android.os.ServiceManager;
165import android.os.SystemClock;
166import android.os.SystemProperties;
167import android.os.UserHandle;
168import android.os.UserManager;
169import android.os.storage.IMountService;
170import android.os.storage.MountServiceInternal;
171import android.os.storage.StorageEventListener;
172import android.os.storage.StorageManager;
173import android.os.storage.VolumeInfo;
174import android.os.storage.VolumeRecord;
175import android.security.KeyStore;
176import android.security.SystemKeyStore;
177import android.system.ErrnoException;
178import android.system.Os;
179import android.system.StructStat;
180import android.text.TextUtils;
181import android.text.format.DateUtils;
182import android.util.ArrayMap;
183import android.util.ArraySet;
184import android.util.AtomicFile;
185import android.util.DisplayMetrics;
186import android.util.EventLog;
187import android.util.ExceptionUtils;
188import android.util.Log;
189import android.util.LogPrinter;
190import android.util.MathUtils;
191import android.util.PrintStreamPrinter;
192import android.util.Slog;
193import android.util.SparseArray;
194import android.util.SparseBooleanArray;
195import android.util.SparseIntArray;
196import android.util.Xml;
197import android.view.Display;
198
199import dalvik.system.DexFile;
200import dalvik.system.VMRuntime;
201
202import libcore.io.IoUtils;
203import libcore.util.EmptyArray;
204
205import com.android.internal.R;
206import com.android.internal.annotations.GuardedBy;
207import com.android.internal.app.IMediaContainerService;
208import com.android.internal.app.ResolverActivity;
209import com.android.internal.content.NativeLibraryHelper;
210import com.android.internal.content.PackageHelper;
211import com.android.internal.os.IParcelFileDescriptorFactory;
212import com.android.internal.os.SomeArgs;
213import com.android.internal.os.Zygote;
214import com.android.internal.util.ArrayUtils;
215import com.android.internal.util.FastPrintWriter;
216import com.android.internal.util.FastXmlSerializer;
217import com.android.internal.util.IndentingPrintWriter;
218import com.android.internal.util.Preconditions;
219import com.android.server.EventLogTags;
220import com.android.server.FgThread;
221import com.android.server.IntentResolver;
222import com.android.server.LocalServices;
223import com.android.server.ServiceThread;
224import com.android.server.SystemConfig;
225import com.android.server.Watchdog;
226import com.android.server.pm.PermissionsState.PermissionState;
227import com.android.server.pm.Settings.DatabaseVersion;
228import com.android.server.pm.Settings.VersionInfo;
229import com.android.server.storage.DeviceStorageMonitorInternal;
230
231import org.xmlpull.v1.XmlPullParser;
232import org.xmlpull.v1.XmlPullParserException;
233import org.xmlpull.v1.XmlSerializer;
234
235import java.io.BufferedInputStream;
236import java.io.BufferedOutputStream;
237import java.io.BufferedReader;
238import java.io.ByteArrayInputStream;
239import java.io.ByteArrayOutputStream;
240import java.io.File;
241import java.io.FileDescriptor;
242import java.io.FileNotFoundException;
243import java.io.FileOutputStream;
244import java.io.FileReader;
245import java.io.FilenameFilter;
246import java.io.IOException;
247import java.io.InputStream;
248import java.io.PrintWriter;
249import java.nio.charset.StandardCharsets;
250import java.security.NoSuchAlgorithmException;
251import java.security.PublicKey;
252import java.security.cert.CertificateEncodingException;
253import java.security.cert.CertificateException;
254import java.text.SimpleDateFormat;
255import java.util.ArrayList;
256import java.util.Arrays;
257import java.util.Collection;
258import java.util.Collections;
259import java.util.Comparator;
260import java.util.Date;
261import java.util.Iterator;
262import java.util.List;
263import java.util.Map;
264import java.util.Objects;
265import java.util.Set;
266import java.util.concurrent.CountDownLatch;
267import java.util.concurrent.TimeUnit;
268import java.util.concurrent.atomic.AtomicBoolean;
269import java.util.concurrent.atomic.AtomicInteger;
270import java.util.concurrent.atomic.AtomicLong;
271
272/**
273 * Keep track of all those .apks everywhere.
274 *
275 * This is very central to the platform's security; please run the unit
276 * tests whenever making modifications here:
277 *
278mmm frameworks/base/tests/AndroidTests
279adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
280adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
281 *
282 * {@hide}
283 */
284public class PackageManagerService extends IPackageManager.Stub {
285    static final String TAG = "PackageManager";
286    static final boolean DEBUG_SETTINGS = false;
287    static final boolean DEBUG_PREFERRED = false;
288    static final boolean DEBUG_UPGRADE = false;
289    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
290    private static final boolean DEBUG_BACKUP = false;
291    private static final boolean DEBUG_INSTALL = false;
292    private static final boolean DEBUG_REMOVE = false;
293    private static final boolean DEBUG_BROADCASTS = false;
294    private static final boolean DEBUG_SHOW_INFO = false;
295    private static final boolean DEBUG_PACKAGE_INFO = false;
296    private static final boolean DEBUG_INTENT_MATCHING = false;
297    private static final boolean DEBUG_PACKAGE_SCANNING = false;
298    private static final boolean DEBUG_VERIFY = false;
299    private static final boolean DEBUG_DEXOPT = false;
300    private static final boolean DEBUG_ABI_SELECTION = false;
301
302    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
303
304    private static final int RADIO_UID = Process.PHONE_UID;
305    private static final int LOG_UID = Process.LOG_UID;
306    private static final int NFC_UID = Process.NFC_UID;
307    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
308    private static final int SHELL_UID = Process.SHELL_UID;
309
310    // Cap the size of permission trees that 3rd party apps can define
311    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
312
313    // Suffix used during package installation when copying/moving
314    // package apks to install directory.
315    private static final String INSTALL_PACKAGE_SUFFIX = "-";
316
317    static final int SCAN_NO_DEX = 1<<1;
318    static final int SCAN_FORCE_DEX = 1<<2;
319    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
320    static final int SCAN_NEW_INSTALL = 1<<4;
321    static final int SCAN_NO_PATHS = 1<<5;
322    static final int SCAN_UPDATE_TIME = 1<<6;
323    static final int SCAN_DEFER_DEX = 1<<7;
324    static final int SCAN_BOOTING = 1<<8;
325    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
326    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
327    static final int SCAN_REPLACING = 1<<11;
328    static final int SCAN_REQUIRE_KNOWN = 1<<12;
329    static final int SCAN_MOVE = 1<<13;
330    static final int SCAN_INITIAL = 1<<14;
331
332    static final int REMOVE_CHATTY = 1<<16;
333
334    private static final int[] EMPTY_INT_ARRAY = new int[0];
335
336    /**
337     * Timeout (in milliseconds) after which the watchdog should declare that
338     * our handler thread is wedged.  The usual default for such things is one
339     * minute but we sometimes do very lengthy I/O operations on this thread,
340     * such as installing multi-gigabyte applications, so ours needs to be longer.
341     */
342    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
343
344    /**
345     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
346     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
347     * settings entry if available, otherwise we use the hardcoded default.  If it's been
348     * more than this long since the last fstrim, we force one during the boot sequence.
349     *
350     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
351     * one gets run at the next available charging+idle time.  This final mandatory
352     * no-fstrim check kicks in only of the other scheduling criteria is never met.
353     */
354    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
355
356    /**
357     * Whether verification is enabled by default.
358     */
359    private static final boolean DEFAULT_VERIFY_ENABLE = true;
360
361    /**
362     * The default maximum time to wait for the verification agent to return in
363     * milliseconds.
364     */
365    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
366
367    /**
368     * The default response for package verification timeout.
369     *
370     * This can be either PackageManager.VERIFICATION_ALLOW or
371     * PackageManager.VERIFICATION_REJECT.
372     */
373    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
374
375    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
376
377    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
378            DEFAULT_CONTAINER_PACKAGE,
379            "com.android.defcontainer.DefaultContainerService");
380
381    private static final String KILL_APP_REASON_GIDS_CHANGED =
382            "permission grant or revoke changed gids";
383
384    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
385            "permissions revoked";
386
387    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
388
389    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
390
391    /** Permission grant: not grant the permission. */
392    private static final int GRANT_DENIED = 1;
393
394    /** Permission grant: grant the permission as an install permission. */
395    private static final int GRANT_INSTALL = 2;
396
397    /** Permission grant: grant the permission as an install permission for a legacy app. */
398    private static final int GRANT_INSTALL_LEGACY = 3;
399
400    /** Permission grant: grant the permission as a runtime one. */
401    private static final int GRANT_RUNTIME = 4;
402
403    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
404    private static final int GRANT_UPGRADE = 5;
405
406    /** Canonical intent used to identify what counts as a "web browser" app */
407    private static final Intent sBrowserIntent;
408    static {
409        sBrowserIntent = new Intent();
410        sBrowserIntent.setAction(Intent.ACTION_VIEW);
411        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
412        sBrowserIntent.setData(Uri.parse("http:"));
413    }
414
415    final ServiceThread mHandlerThread;
416
417    final PackageHandler mHandler;
418
419    /**
420     * Messages for {@link #mHandler} that need to wait for system ready before
421     * being dispatched.
422     */
423    private ArrayList<Message> mPostSystemReadyMessages;
424
425    final int mSdkVersion = Build.VERSION.SDK_INT;
426
427    final Context mContext;
428    final boolean mFactoryTest;
429    final boolean mOnlyCore;
430    final boolean mLazyDexOpt;
431    final long mDexOptLRUThresholdInMills;
432    final DisplayMetrics mMetrics;
433    final int mDefParseFlags;
434    final String[] mSeparateProcesses;
435    final boolean mIsUpgrade;
436
437    // This is where all application persistent data goes.
438    final File mAppDataDir;
439
440    // This is where all application persistent data goes for secondary users.
441    final File mUserAppDataDir;
442
443    /** The location for ASEC container files on internal storage. */
444    final String mAsecInternalPath;
445
446    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
447    // LOCK HELD.  Can be called with mInstallLock held.
448    @GuardedBy("mInstallLock")
449    final Installer mInstaller;
450
451    /** Directory where installed third-party apps stored */
452    final File mAppInstallDir;
453
454    /**
455     * Directory to which applications installed internally have their
456     * 32 bit native libraries copied.
457     */
458    private File mAppLib32InstallDir;
459
460    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
461    // apps.
462    final File mDrmAppPrivateInstallDir;
463
464    // ----------------------------------------------------------------
465
466    // Lock for state used when installing and doing other long running
467    // operations.  Methods that must be called with this lock held have
468    // the suffix "LI".
469    final Object mInstallLock = new Object();
470
471    // ----------------------------------------------------------------
472
473    // Keys are String (package name), values are Package.  This also serves
474    // as the lock for the global state.  Methods that must be called with
475    // this lock held have the prefix "LP".
476    @GuardedBy("mPackages")
477    final ArrayMap<String, PackageParser.Package> mPackages =
478            new ArrayMap<String, PackageParser.Package>();
479
480    // Tracks available target package names -> overlay package paths.
481    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
482        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
483
484    /**
485     * Tracks new system packages [received in an OTA] that we expect to
486     * find updated user-installed versions. Keys are package name, values
487     * are package location.
488     */
489    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
490
491    /**
492     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
493     */
494    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
495    /**
496     * Whether or not system app permissions should be promoted from install to runtime.
497     */
498    boolean mPromoteSystemApps;
499
500    final Settings mSettings;
501    boolean mRestoredSettings;
502
503    // System configuration read by SystemConfig.
504    final int[] mGlobalGids;
505    final SparseArray<ArraySet<String>> mSystemPermissions;
506    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
507
508    // If mac_permissions.xml was found for seinfo labeling.
509    boolean mFoundPolicyFile;
510
511    // If a recursive restorecon of /data/data/<pkg> is needed.
512    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
513
514    public static final class SharedLibraryEntry {
515        public final String path;
516        public final String apk;
517
518        SharedLibraryEntry(String _path, String _apk) {
519            path = _path;
520            apk = _apk;
521        }
522    }
523
524    // Currently known shared libraries.
525    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
526            new ArrayMap<String, SharedLibraryEntry>();
527
528    // All available activities, for your resolving pleasure.
529    final ActivityIntentResolver mActivities =
530            new ActivityIntentResolver();
531
532    // All available receivers, for your resolving pleasure.
533    final ActivityIntentResolver mReceivers =
534            new ActivityIntentResolver();
535
536    // All available services, for your resolving pleasure.
537    final ServiceIntentResolver mServices = new ServiceIntentResolver();
538
539    // All available providers, for your resolving pleasure.
540    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
541
542    // Mapping from provider base names (first directory in content URI codePath)
543    // to the provider information.
544    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
545            new ArrayMap<String, PackageParser.Provider>();
546
547    // Mapping from instrumentation class names to info about them.
548    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
549            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
550
551    // Mapping from permission names to info about them.
552    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
553            new ArrayMap<String, PackageParser.PermissionGroup>();
554
555    // Packages whose data we have transfered into another package, thus
556    // should no longer exist.
557    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
558
559    // Broadcast actions that are only available to the system.
560    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
561
562    /** List of packages waiting for verification. */
563    final SparseArray<PackageVerificationState> mPendingVerification
564            = new SparseArray<PackageVerificationState>();
565
566    /** Set of packages associated with each app op permission. */
567    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
568
569    final PackageInstallerService mInstallerService;
570
571    private final PackageDexOptimizer mPackageDexOptimizer;
572
573    private AtomicInteger mNextMoveId = new AtomicInteger();
574    private final MoveCallbacks mMoveCallbacks;
575
576    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
577
578    // Cache of users who need badging.
579    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
580
581    /** Token for keys in mPendingVerification. */
582    private int mPendingVerificationToken = 0;
583
584    volatile boolean mSystemReady;
585    volatile boolean mSafeMode;
586    volatile boolean mHasSystemUidErrors;
587
588    ApplicationInfo mAndroidApplication;
589    final ActivityInfo mResolveActivity = new ActivityInfo();
590    final ResolveInfo mResolveInfo = new ResolveInfo();
591    ComponentName mResolveComponentName;
592    PackageParser.Package mPlatformPackage;
593    ComponentName mCustomResolverComponentName;
594
595    boolean mResolverReplaced = false;
596
597    private final ComponentName mIntentFilterVerifierComponent;
598    private int mIntentFilterVerificationToken = 0;
599
600    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
601            = new SparseArray<IntentFilterVerificationState>();
602
603    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
604            new DefaultPermissionGrantPolicy(this);
605
606    private static class IFVerificationParams {
607        PackageParser.Package pkg;
608        boolean replacing;
609        int userId;
610        int verifierUid;
611
612        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
613                int _userId, int _verifierUid) {
614            pkg = _pkg;
615            replacing = _replacing;
616            userId = _userId;
617            replacing = _replacing;
618            verifierUid = _verifierUid;
619        }
620    }
621
622    private interface IntentFilterVerifier<T extends IntentFilter> {
623        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
624                                               T filter, String packageName);
625        void startVerifications(int userId);
626        void receiveVerificationResponse(int verificationId);
627    }
628
629    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
630        private Context mContext;
631        private ComponentName mIntentFilterVerifierComponent;
632        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
633
634        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
635            mContext = context;
636            mIntentFilterVerifierComponent = verifierComponent;
637        }
638
639        private String getDefaultScheme() {
640            return IntentFilter.SCHEME_HTTPS;
641        }
642
643        @Override
644        public void startVerifications(int userId) {
645            // Launch verifications requests
646            int count = mCurrentIntentFilterVerifications.size();
647            for (int n=0; n<count; n++) {
648                int verificationId = mCurrentIntentFilterVerifications.get(n);
649                final IntentFilterVerificationState ivs =
650                        mIntentFilterVerificationStates.get(verificationId);
651
652                String packageName = ivs.getPackageName();
653
654                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
655                final int filterCount = filters.size();
656                ArraySet<String> domainsSet = new ArraySet<>();
657                for (int m=0; m<filterCount; m++) {
658                    PackageParser.ActivityIntentInfo filter = filters.get(m);
659                    domainsSet.addAll(filter.getHostsList());
660                }
661                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
662                synchronized (mPackages) {
663                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
664                            packageName, domainsList) != null) {
665                        scheduleWriteSettingsLocked();
666                    }
667                }
668                sendVerificationRequest(userId, verificationId, ivs);
669            }
670            mCurrentIntentFilterVerifications.clear();
671        }
672
673        private void sendVerificationRequest(int userId, int verificationId,
674                IntentFilterVerificationState ivs) {
675
676            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
677            verificationIntent.putExtra(
678                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
679                    verificationId);
680            verificationIntent.putExtra(
681                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
682                    getDefaultScheme());
683            verificationIntent.putExtra(
684                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
685                    ivs.getHostsString());
686            verificationIntent.putExtra(
687                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
688                    ivs.getPackageName());
689            verificationIntent.setComponent(mIntentFilterVerifierComponent);
690            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
691
692            UserHandle user = new UserHandle(userId);
693            mContext.sendBroadcastAsUser(verificationIntent, user);
694            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
695                    "Sending IntentFilter verification broadcast");
696        }
697
698        public void receiveVerificationResponse(int verificationId) {
699            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
700
701            final boolean verified = ivs.isVerified();
702
703            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
704            final int count = filters.size();
705            if (DEBUG_DOMAIN_VERIFICATION) {
706                Slog.i(TAG, "Received verification response " + verificationId
707                        + " for " + count + " filters, verified=" + verified);
708            }
709            for (int n=0; n<count; n++) {
710                PackageParser.ActivityIntentInfo filter = filters.get(n);
711                filter.setVerified(verified);
712
713                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
714                        + " verified with result:" + verified + " and hosts:"
715                        + ivs.getHostsString());
716            }
717
718            mIntentFilterVerificationStates.remove(verificationId);
719
720            final String packageName = ivs.getPackageName();
721            IntentFilterVerificationInfo ivi = null;
722
723            synchronized (mPackages) {
724                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
725            }
726            if (ivi == null) {
727                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
728                        + verificationId + " packageName:" + packageName);
729                return;
730            }
731            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
732                    "Updating IntentFilterVerificationInfo for package " + packageName
733                            +" verificationId:" + verificationId);
734
735            synchronized (mPackages) {
736                if (verified) {
737                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
738                } else {
739                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
740                }
741                scheduleWriteSettingsLocked();
742
743                final int userId = ivs.getUserId();
744                if (userId != UserHandle.USER_ALL) {
745                    final int userStatus =
746                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
747
748                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
749                    boolean needUpdate = false;
750
751                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
752                    // already been set by the User thru the Disambiguation dialog
753                    switch (userStatus) {
754                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
755                            if (verified) {
756                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
757                            } else {
758                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
759                            }
760                            needUpdate = true;
761                            break;
762
763                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
764                            if (verified) {
765                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
766                                needUpdate = true;
767                            }
768                            break;
769
770                        default:
771                            // Nothing to do
772                    }
773
774                    if (needUpdate) {
775                        mSettings.updateIntentFilterVerificationStatusLPw(
776                                packageName, updatedStatus, userId);
777                        scheduleWritePackageRestrictionsLocked(userId);
778                    }
779                }
780            }
781        }
782
783        @Override
784        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
785                    ActivityIntentInfo filter, String packageName) {
786            if (!hasValidDomains(filter)) {
787                return false;
788            }
789            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
790            if (ivs == null) {
791                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
792                        packageName);
793            }
794            if (DEBUG_DOMAIN_VERIFICATION) {
795                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
796            }
797            ivs.addFilter(filter);
798            return true;
799        }
800
801        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
802                int userId, int verificationId, String packageName) {
803            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
804                    verifierUid, userId, packageName);
805            ivs.setPendingState();
806            synchronized (mPackages) {
807                mIntentFilterVerificationStates.append(verificationId, ivs);
808                mCurrentIntentFilterVerifications.add(verificationId);
809            }
810            return ivs;
811        }
812    }
813
814    private static boolean hasValidDomains(ActivityIntentInfo filter) {
815        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
816                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
817                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
818    }
819
820    private IntentFilterVerifier mIntentFilterVerifier;
821
822    // Set of pending broadcasts for aggregating enable/disable of components.
823    static class PendingPackageBroadcasts {
824        // for each user id, a map of <package name -> components within that package>
825        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
826
827        public PendingPackageBroadcasts() {
828            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
829        }
830
831        public ArrayList<String> get(int userId, String packageName) {
832            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
833            return packages.get(packageName);
834        }
835
836        public void put(int userId, String packageName, ArrayList<String> components) {
837            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
838            packages.put(packageName, components);
839        }
840
841        public void remove(int userId, String packageName) {
842            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
843            if (packages != null) {
844                packages.remove(packageName);
845            }
846        }
847
848        public void remove(int userId) {
849            mUidMap.remove(userId);
850        }
851
852        public int userIdCount() {
853            return mUidMap.size();
854        }
855
856        public int userIdAt(int n) {
857            return mUidMap.keyAt(n);
858        }
859
860        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
861            return mUidMap.get(userId);
862        }
863
864        public int size() {
865            // total number of pending broadcast entries across all userIds
866            int num = 0;
867            for (int i = 0; i< mUidMap.size(); i++) {
868                num += mUidMap.valueAt(i).size();
869            }
870            return num;
871        }
872
873        public void clear() {
874            mUidMap.clear();
875        }
876
877        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
878            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
879            if (map == null) {
880                map = new ArrayMap<String, ArrayList<String>>();
881                mUidMap.put(userId, map);
882            }
883            return map;
884        }
885    }
886    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
887
888    // Service Connection to remote media container service to copy
889    // package uri's from external media onto secure containers
890    // or internal storage.
891    private IMediaContainerService mContainerService = null;
892
893    static final int SEND_PENDING_BROADCAST = 1;
894    static final int MCS_BOUND = 3;
895    static final int END_COPY = 4;
896    static final int INIT_COPY = 5;
897    static final int MCS_UNBIND = 6;
898    static final int START_CLEANING_PACKAGE = 7;
899    static final int FIND_INSTALL_LOC = 8;
900    static final int POST_INSTALL = 9;
901    static final int MCS_RECONNECT = 10;
902    static final int MCS_GIVE_UP = 11;
903    static final int UPDATED_MEDIA_STATUS = 12;
904    static final int WRITE_SETTINGS = 13;
905    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
906    static final int PACKAGE_VERIFIED = 15;
907    static final int CHECK_PENDING_VERIFICATION = 16;
908    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
909    static final int INTENT_FILTER_VERIFIED = 18;
910
911    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
912
913    // Delay time in millisecs
914    static final int BROADCAST_DELAY = 10 * 1000;
915
916    static UserManagerService sUserManager;
917
918    // Stores a list of users whose package restrictions file needs to be updated
919    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
920
921    final private DefaultContainerConnection mDefContainerConn =
922            new DefaultContainerConnection();
923    class DefaultContainerConnection implements ServiceConnection {
924        public void onServiceConnected(ComponentName name, IBinder service) {
925            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
926            IMediaContainerService imcs =
927                IMediaContainerService.Stub.asInterface(service);
928            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
929        }
930
931        public void onServiceDisconnected(ComponentName name) {
932            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
933        }
934    }
935
936    // Recordkeeping of restore-after-install operations that are currently in flight
937    // between the Package Manager and the Backup Manager
938    class PostInstallData {
939        public InstallArgs args;
940        public PackageInstalledInfo res;
941
942        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
943            args = _a;
944            res = _r;
945        }
946    }
947
948    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
949    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
950
951    // XML tags for backup/restore of various bits of state
952    private static final String TAG_PREFERRED_BACKUP = "pa";
953    private static final String TAG_DEFAULT_APPS = "da";
954    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
955
956    final String mRequiredVerifierPackage;
957    final String mRequiredInstallerPackage;
958
959    private final PackageUsage mPackageUsage = new PackageUsage();
960
961    private class PackageUsage {
962        private static final int WRITE_INTERVAL
963            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
964
965        private final Object mFileLock = new Object();
966        private final AtomicLong mLastWritten = new AtomicLong(0);
967        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
968
969        private boolean mIsHistoricalPackageUsageAvailable = true;
970
971        boolean isHistoricalPackageUsageAvailable() {
972            return mIsHistoricalPackageUsageAvailable;
973        }
974
975        void write(boolean force) {
976            if (force) {
977                writeInternal();
978                return;
979            }
980            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
981                && !DEBUG_DEXOPT) {
982                return;
983            }
984            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
985                new Thread("PackageUsage_DiskWriter") {
986                    @Override
987                    public void run() {
988                        try {
989                            writeInternal();
990                        } finally {
991                            mBackgroundWriteRunning.set(false);
992                        }
993                    }
994                }.start();
995            }
996        }
997
998        private void writeInternal() {
999            synchronized (mPackages) {
1000                synchronized (mFileLock) {
1001                    AtomicFile file = getFile();
1002                    FileOutputStream f = null;
1003                    try {
1004                        f = file.startWrite();
1005                        BufferedOutputStream out = new BufferedOutputStream(f);
1006                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1007                        StringBuilder sb = new StringBuilder();
1008                        for (PackageParser.Package pkg : mPackages.values()) {
1009                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1010                                continue;
1011                            }
1012                            sb.setLength(0);
1013                            sb.append(pkg.packageName);
1014                            sb.append(' ');
1015                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1016                            sb.append('\n');
1017                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1018                        }
1019                        out.flush();
1020                        file.finishWrite(f);
1021                    } catch (IOException e) {
1022                        if (f != null) {
1023                            file.failWrite(f);
1024                        }
1025                        Log.e(TAG, "Failed to write package usage times", e);
1026                    }
1027                }
1028            }
1029            mLastWritten.set(SystemClock.elapsedRealtime());
1030        }
1031
1032        void readLP() {
1033            synchronized (mFileLock) {
1034                AtomicFile file = getFile();
1035                BufferedInputStream in = null;
1036                try {
1037                    in = new BufferedInputStream(file.openRead());
1038                    StringBuffer sb = new StringBuffer();
1039                    while (true) {
1040                        String packageName = readToken(in, sb, ' ');
1041                        if (packageName == null) {
1042                            break;
1043                        }
1044                        String timeInMillisString = readToken(in, sb, '\n');
1045                        if (timeInMillisString == null) {
1046                            throw new IOException("Failed to find last usage time for package "
1047                                                  + packageName);
1048                        }
1049                        PackageParser.Package pkg = mPackages.get(packageName);
1050                        if (pkg == null) {
1051                            continue;
1052                        }
1053                        long timeInMillis;
1054                        try {
1055                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1056                        } catch (NumberFormatException e) {
1057                            throw new IOException("Failed to parse " + timeInMillisString
1058                                                  + " as a long.", e);
1059                        }
1060                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1061                    }
1062                } catch (FileNotFoundException expected) {
1063                    mIsHistoricalPackageUsageAvailable = false;
1064                } catch (IOException e) {
1065                    Log.w(TAG, "Failed to read package usage times", e);
1066                } finally {
1067                    IoUtils.closeQuietly(in);
1068                }
1069            }
1070            mLastWritten.set(SystemClock.elapsedRealtime());
1071        }
1072
1073        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1074                throws IOException {
1075            sb.setLength(0);
1076            while (true) {
1077                int ch = in.read();
1078                if (ch == -1) {
1079                    if (sb.length() == 0) {
1080                        return null;
1081                    }
1082                    throw new IOException("Unexpected EOF");
1083                }
1084                if (ch == endOfToken) {
1085                    return sb.toString();
1086                }
1087                sb.append((char)ch);
1088            }
1089        }
1090
1091        private AtomicFile getFile() {
1092            File dataDir = Environment.getDataDirectory();
1093            File systemDir = new File(dataDir, "system");
1094            File fname = new File(systemDir, "package-usage.list");
1095            return new AtomicFile(fname);
1096        }
1097    }
1098
1099    class PackageHandler extends Handler {
1100        private boolean mBound = false;
1101        final ArrayList<HandlerParams> mPendingInstalls =
1102            new ArrayList<HandlerParams>();
1103
1104        private boolean connectToService() {
1105            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1106                    " DefaultContainerService");
1107            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1108            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1109            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1110                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1111                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112                mBound = true;
1113                return true;
1114            }
1115            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1116            return false;
1117        }
1118
1119        private void disconnectService() {
1120            mContainerService = null;
1121            mBound = false;
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            mContext.unbindService(mDefContainerConn);
1124            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125        }
1126
1127        PackageHandler(Looper looper) {
1128            super(looper);
1129        }
1130
1131        public void handleMessage(Message msg) {
1132            try {
1133                doHandleMessage(msg);
1134            } finally {
1135                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1136            }
1137        }
1138
1139        void doHandleMessage(Message msg) {
1140            switch (msg.what) {
1141                case INIT_COPY: {
1142                    HandlerParams params = (HandlerParams) msg.obj;
1143                    int idx = mPendingInstalls.size();
1144                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1145                    // If a bind was already initiated we dont really
1146                    // need to do anything. The pending install
1147                    // will be processed later on.
1148                    if (!mBound) {
1149                        // If this is the only one pending we might
1150                        // have to bind to the service again.
1151                        if (!connectToService()) {
1152                            Slog.e(TAG, "Failed to bind to media container service");
1153                            params.serviceError();
1154                            return;
1155                        } else {
1156                            // Once we bind to the service, the first
1157                            // pending request will be processed.
1158                            mPendingInstalls.add(idx, params);
1159                        }
1160                    } else {
1161                        mPendingInstalls.add(idx, params);
1162                        // Already bound to the service. Just make
1163                        // sure we trigger off processing the first request.
1164                        if (idx == 0) {
1165                            mHandler.sendEmptyMessage(MCS_BOUND);
1166                        }
1167                    }
1168                    break;
1169                }
1170                case MCS_BOUND: {
1171                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1172                    if (msg.obj != null) {
1173                        mContainerService = (IMediaContainerService) msg.obj;
1174                    }
1175                    if (mContainerService == null) {
1176                        if (!mBound) {
1177                            // Something seriously wrong since we are not bound and we are not
1178                            // waiting for connection. Bail out.
1179                            Slog.e(TAG, "Cannot bind to media container service");
1180                            for (HandlerParams params : mPendingInstalls) {
1181                                // Indicate service bind error
1182                                params.serviceError();
1183                            }
1184                            mPendingInstalls.clear();
1185                        } else {
1186                            Slog.w(TAG, "Waiting to connect to media container service");
1187                        }
1188                    } else if (mPendingInstalls.size() > 0) {
1189                        HandlerParams params = mPendingInstalls.get(0);
1190                        if (params != null) {
1191                            if (params.startCopy()) {
1192                                // We are done...  look for more work or to
1193                                // go idle.
1194                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1195                                        "Checking for more work or unbind...");
1196                                // Delete pending install
1197                                if (mPendingInstalls.size() > 0) {
1198                                    mPendingInstalls.remove(0);
1199                                }
1200                                if (mPendingInstalls.size() == 0) {
1201                                    if (mBound) {
1202                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1203                                                "Posting delayed MCS_UNBIND");
1204                                        removeMessages(MCS_UNBIND);
1205                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1206                                        // Unbind after a little delay, to avoid
1207                                        // continual thrashing.
1208                                        sendMessageDelayed(ubmsg, 10000);
1209                                    }
1210                                } else {
1211                                    // There are more pending requests in queue.
1212                                    // Just post MCS_BOUND message to trigger processing
1213                                    // of next pending install.
1214                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1215                                            "Posting MCS_BOUND for next work");
1216                                    mHandler.sendEmptyMessage(MCS_BOUND);
1217                                }
1218                            }
1219                        }
1220                    } else {
1221                        // Should never happen ideally.
1222                        Slog.w(TAG, "Empty queue");
1223                    }
1224                    break;
1225                }
1226                case MCS_RECONNECT: {
1227                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1228                    if (mPendingInstalls.size() > 0) {
1229                        if (mBound) {
1230                            disconnectService();
1231                        }
1232                        if (!connectToService()) {
1233                            Slog.e(TAG, "Failed to bind to media container service");
1234                            for (HandlerParams params : mPendingInstalls) {
1235                                // Indicate service bind error
1236                                params.serviceError();
1237                            }
1238                            mPendingInstalls.clear();
1239                        }
1240                    }
1241                    break;
1242                }
1243                case MCS_UNBIND: {
1244                    // If there is no actual work left, then time to unbind.
1245                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1246
1247                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1248                        if (mBound) {
1249                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1250
1251                            disconnectService();
1252                        }
1253                    } else if (mPendingInstalls.size() > 0) {
1254                        // There are more pending requests in queue.
1255                        // Just post MCS_BOUND message to trigger processing
1256                        // of next pending install.
1257                        mHandler.sendEmptyMessage(MCS_BOUND);
1258                    }
1259
1260                    break;
1261                }
1262                case MCS_GIVE_UP: {
1263                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1264                    mPendingInstalls.remove(0);
1265                    break;
1266                }
1267                case SEND_PENDING_BROADCAST: {
1268                    String packages[];
1269                    ArrayList<String> components[];
1270                    int size = 0;
1271                    int uids[];
1272                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1273                    synchronized (mPackages) {
1274                        if (mPendingBroadcasts == null) {
1275                            return;
1276                        }
1277                        size = mPendingBroadcasts.size();
1278                        if (size <= 0) {
1279                            // Nothing to be done. Just return
1280                            return;
1281                        }
1282                        packages = new String[size];
1283                        components = new ArrayList[size];
1284                        uids = new int[size];
1285                        int i = 0;  // filling out the above arrays
1286
1287                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1288                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1289                            Iterator<Map.Entry<String, ArrayList<String>>> it
1290                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1291                                            .entrySet().iterator();
1292                            while (it.hasNext() && i < size) {
1293                                Map.Entry<String, ArrayList<String>> ent = it.next();
1294                                packages[i] = ent.getKey();
1295                                components[i] = ent.getValue();
1296                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1297                                uids[i] = (ps != null)
1298                                        ? UserHandle.getUid(packageUserId, ps.appId)
1299                                        : -1;
1300                                i++;
1301                            }
1302                        }
1303                        size = i;
1304                        mPendingBroadcasts.clear();
1305                    }
1306                    // Send broadcasts
1307                    for (int i = 0; i < size; i++) {
1308                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1309                    }
1310                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1311                    break;
1312                }
1313                case START_CLEANING_PACKAGE: {
1314                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1315                    final String packageName = (String)msg.obj;
1316                    final int userId = msg.arg1;
1317                    final boolean andCode = msg.arg2 != 0;
1318                    synchronized (mPackages) {
1319                        if (userId == UserHandle.USER_ALL) {
1320                            int[] users = sUserManager.getUserIds();
1321                            for (int user : users) {
1322                                mSettings.addPackageToCleanLPw(
1323                                        new PackageCleanItem(user, packageName, andCode));
1324                            }
1325                        } else {
1326                            mSettings.addPackageToCleanLPw(
1327                                    new PackageCleanItem(userId, packageName, andCode));
1328                        }
1329                    }
1330                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1331                    startCleaningPackages();
1332                } break;
1333                case POST_INSTALL: {
1334                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1335                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1336                    mRunningInstalls.delete(msg.arg1);
1337                    boolean deleteOld = false;
1338
1339                    if (data != null) {
1340                        InstallArgs args = data.args;
1341                        PackageInstalledInfo res = data.res;
1342
1343                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1344                            final String packageName = res.pkg.applicationInfo.packageName;
1345                            res.removedInfo.sendBroadcast(false, true, false);
1346                            Bundle extras = new Bundle(1);
1347                            extras.putInt(Intent.EXTRA_UID, res.uid);
1348
1349                            // Now that we successfully installed the package, grant runtime
1350                            // permissions if requested before broadcasting the install.
1351                            if ((args.installFlags
1352                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1353                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1354                                        args.installGrantPermissions);
1355                            }
1356
1357                            // Determine the set of users who are adding this
1358                            // package for the first time vs. those who are seeing
1359                            // an update.
1360                            int[] firstUsers;
1361                            int[] updateUsers = new int[0];
1362                            if (res.origUsers == null || res.origUsers.length == 0) {
1363                                firstUsers = res.newUsers;
1364                            } else {
1365                                firstUsers = new int[0];
1366                                for (int i=0; i<res.newUsers.length; i++) {
1367                                    int user = res.newUsers[i];
1368                                    boolean isNew = true;
1369                                    for (int j=0; j<res.origUsers.length; j++) {
1370                                        if (res.origUsers[j] == user) {
1371                                            isNew = false;
1372                                            break;
1373                                        }
1374                                    }
1375                                    if (isNew) {
1376                                        int[] newFirst = new int[firstUsers.length+1];
1377                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1378                                                firstUsers.length);
1379                                        newFirst[firstUsers.length] = user;
1380                                        firstUsers = newFirst;
1381                                    } else {
1382                                        int[] newUpdate = new int[updateUsers.length+1];
1383                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1384                                                updateUsers.length);
1385                                        newUpdate[updateUsers.length] = user;
1386                                        updateUsers = newUpdate;
1387                                    }
1388                                }
1389                            }
1390                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1391                                    packageName, extras, null, null, firstUsers);
1392                            final boolean update = res.removedInfo.removedPackage != null;
1393                            if (update) {
1394                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1395                            }
1396                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1397                                    packageName, extras, null, null, updateUsers);
1398                            if (update) {
1399                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1400                                        packageName, extras, null, null, updateUsers);
1401                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1402                                        null, null, packageName, null, updateUsers);
1403
1404                                // treat asec-hosted packages like removable media on upgrade
1405                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1406                                    if (DEBUG_INSTALL) {
1407                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1408                                                + " is ASEC-hosted -> AVAILABLE");
1409                                    }
1410                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1411                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1412                                    pkgList.add(packageName);
1413                                    sendResourcesChangedBroadcast(true, true,
1414                                            pkgList,uidArray, null);
1415                                }
1416                            }
1417                            if (res.removedInfo.args != null) {
1418                                // Remove the replaced package's older resources safely now
1419                                deleteOld = true;
1420                            }
1421
1422                            // If this app is a browser and it's newly-installed for some
1423                            // users, clear any default-browser state in those users
1424                            if (firstUsers.length > 0) {
1425                                // the app's nature doesn't depend on the user, so we can just
1426                                // check its browser nature in any user and generalize.
1427                                if (packageIsBrowser(packageName, firstUsers[0])) {
1428                                    synchronized (mPackages) {
1429                                        for (int userId : firstUsers) {
1430                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1431                                        }
1432                                    }
1433                                }
1434                            }
1435                            // Log current value of "unknown sources" setting
1436                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1437                                getUnknownSourcesSettings());
1438                        }
1439                        // Force a gc to clear up things
1440                        Runtime.getRuntime().gc();
1441                        // We delete after a gc for applications  on sdcard.
1442                        if (deleteOld) {
1443                            synchronized (mInstallLock) {
1444                                res.removedInfo.args.doPostDeleteLI(true);
1445                            }
1446                        }
1447                        if (args.observer != null) {
1448                            try {
1449                                Bundle extras = extrasForInstallResult(res);
1450                                args.observer.onPackageInstalled(res.name, res.returnCode,
1451                                        res.returnMsg, extras);
1452                            } catch (RemoteException e) {
1453                                Slog.i(TAG, "Observer no longer exists.");
1454                            }
1455                        }
1456                    } else {
1457                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1458                    }
1459                } break;
1460                case UPDATED_MEDIA_STATUS: {
1461                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1462                    boolean reportStatus = msg.arg1 == 1;
1463                    boolean doGc = msg.arg2 == 1;
1464                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1465                    if (doGc) {
1466                        // Force a gc to clear up stale containers.
1467                        Runtime.getRuntime().gc();
1468                    }
1469                    if (msg.obj != null) {
1470                        @SuppressWarnings("unchecked")
1471                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1472                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1473                        // Unload containers
1474                        unloadAllContainers(args);
1475                    }
1476                    if (reportStatus) {
1477                        try {
1478                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1479                            PackageHelper.getMountService().finishMediaUpdate();
1480                        } catch (RemoteException e) {
1481                            Log.e(TAG, "MountService not running?");
1482                        }
1483                    }
1484                } break;
1485                case WRITE_SETTINGS: {
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1487                    synchronized (mPackages) {
1488                        removeMessages(WRITE_SETTINGS);
1489                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1490                        mSettings.writeLPr();
1491                        mDirtyUsers.clear();
1492                    }
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                } break;
1495                case WRITE_PACKAGE_RESTRICTIONS: {
1496                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1497                    synchronized (mPackages) {
1498                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1499                        for (int userId : mDirtyUsers) {
1500                            mSettings.writePackageRestrictionsLPr(userId);
1501                        }
1502                        mDirtyUsers.clear();
1503                    }
1504                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1505                } break;
1506                case CHECK_PENDING_VERIFICATION: {
1507                    final int verificationId = msg.arg1;
1508                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1509
1510                    if ((state != null) && !state.timeoutExtended()) {
1511                        final InstallArgs args = state.getInstallArgs();
1512                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1513
1514                        Slog.i(TAG, "Verification timed out for " + originUri);
1515                        mPendingVerification.remove(verificationId);
1516
1517                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1518
1519                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1520                            Slog.i(TAG, "Continuing with installation of " + originUri);
1521                            state.setVerifierResponse(Binder.getCallingUid(),
1522                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1523                            broadcastPackageVerified(verificationId, originUri,
1524                                    PackageManager.VERIFICATION_ALLOW,
1525                                    state.getInstallArgs().getUser());
1526                            try {
1527                                ret = args.copyApk(mContainerService, true);
1528                            } catch (RemoteException e) {
1529                                Slog.e(TAG, "Could not contact the ContainerService");
1530                            }
1531                        } else {
1532                            broadcastPackageVerified(verificationId, originUri,
1533                                    PackageManager.VERIFICATION_REJECT,
1534                                    state.getInstallArgs().getUser());
1535                        }
1536
1537                        processPendingInstall(args, ret);
1538                        mHandler.sendEmptyMessage(MCS_UNBIND);
1539                    }
1540                    break;
1541                }
1542                case PACKAGE_VERIFIED: {
1543                    final int verificationId = msg.arg1;
1544
1545                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1546                    if (state == null) {
1547                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1548                        break;
1549                    }
1550
1551                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1552
1553                    state.setVerifierResponse(response.callerUid, response.code);
1554
1555                    if (state.isVerificationComplete()) {
1556                        mPendingVerification.remove(verificationId);
1557
1558                        final InstallArgs args = state.getInstallArgs();
1559                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1560
1561                        int ret;
1562                        if (state.isInstallAllowed()) {
1563                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1564                            broadcastPackageVerified(verificationId, originUri,
1565                                    response.code, state.getInstallArgs().getUser());
1566                            try {
1567                                ret = args.copyApk(mContainerService, true);
1568                            } catch (RemoteException e) {
1569                                Slog.e(TAG, "Could not contact the ContainerService");
1570                            }
1571                        } else {
1572                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1573                        }
1574
1575                        processPendingInstall(args, ret);
1576
1577                        mHandler.sendEmptyMessage(MCS_UNBIND);
1578                    }
1579
1580                    break;
1581                }
1582                case START_INTENT_FILTER_VERIFICATIONS: {
1583                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1584                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1585                            params.replacing, params.pkg);
1586                    break;
1587                }
1588                case INTENT_FILTER_VERIFIED: {
1589                    final int verificationId = msg.arg1;
1590
1591                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1592                            verificationId);
1593                    if (state == null) {
1594                        Slog.w(TAG, "Invalid IntentFilter verification token "
1595                                + verificationId + " received");
1596                        break;
1597                    }
1598
1599                    final int userId = state.getUserId();
1600
1601                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1602                            "Processing IntentFilter verification with token:"
1603                            + verificationId + " and userId:" + userId);
1604
1605                    final IntentFilterVerificationResponse response =
1606                            (IntentFilterVerificationResponse) msg.obj;
1607
1608                    state.setVerifierResponse(response.callerUid, response.code);
1609
1610                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1611                            "IntentFilter verification with token:" + verificationId
1612                            + " and userId:" + userId
1613                            + " is settings verifier response with response code:"
1614                            + response.code);
1615
1616                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1617                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1618                                + response.getFailedDomainsString());
1619                    }
1620
1621                    if (state.isVerificationComplete()) {
1622                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1623                    } else {
1624                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1625                                "IntentFilter verification with token:" + verificationId
1626                                + " was not said to be complete");
1627                    }
1628
1629                    break;
1630                }
1631            }
1632        }
1633    }
1634
1635    private StorageEventListener mStorageListener = new StorageEventListener() {
1636        @Override
1637        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1638            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1639                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1640                    final String volumeUuid = vol.getFsUuid();
1641
1642                    // Clean up any users or apps that were removed or recreated
1643                    // while this volume was missing
1644                    reconcileUsers(volumeUuid);
1645                    reconcileApps(volumeUuid);
1646
1647                    // Clean up any install sessions that expired or were
1648                    // cancelled while this volume was missing
1649                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1650
1651                    loadPrivatePackages(vol);
1652
1653                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1654                    unloadPrivatePackages(vol);
1655                }
1656            }
1657
1658            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1659                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1660                    updateExternalMediaStatus(true, false);
1661                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1662                    updateExternalMediaStatus(false, false);
1663                }
1664            }
1665        }
1666
1667        @Override
1668        public void onVolumeForgotten(String fsUuid) {
1669            if (TextUtils.isEmpty(fsUuid)) {
1670                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1671                return;
1672            }
1673
1674            // Remove any apps installed on the forgotten volume
1675            synchronized (mPackages) {
1676                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1677                for (PackageSetting ps : packages) {
1678                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1679                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1680                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1681                }
1682
1683                mSettings.onVolumeForgotten(fsUuid);
1684                mSettings.writeLPr();
1685            }
1686        }
1687    };
1688
1689    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1690            String[] grantedPermissions) {
1691        if (userId >= UserHandle.USER_OWNER) {
1692            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1693        } else if (userId == UserHandle.USER_ALL) {
1694            final int[] userIds;
1695            synchronized (mPackages) {
1696                userIds = UserManagerService.getInstance().getUserIds();
1697            }
1698            for (int someUserId : userIds) {
1699                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1700            }
1701        }
1702
1703        // We could have touched GID membership, so flush out packages.list
1704        synchronized (mPackages) {
1705            mSettings.writePackageListLPr();
1706        }
1707    }
1708
1709    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1710            String[] grantedPermissions) {
1711        SettingBase sb = (SettingBase) pkg.mExtras;
1712        if (sb == null) {
1713            return;
1714        }
1715
1716        synchronized (mPackages) {
1717            for (String permission : pkg.requestedPermissions) {
1718                BasePermission bp = mSettings.mPermissions.get(permission);
1719                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1720                        && (grantedPermissions == null
1721                               || ArrayUtils.contains(grantedPermissions, permission))) {
1722                    grantRuntimePermission(pkg.packageName, permission, userId);
1723                }
1724            }
1725        }
1726    }
1727
1728    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1729        Bundle extras = null;
1730        switch (res.returnCode) {
1731            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1732                extras = new Bundle();
1733                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1734                        res.origPermission);
1735                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1736                        res.origPackage);
1737                break;
1738            }
1739            case PackageManager.INSTALL_SUCCEEDED: {
1740                extras = new Bundle();
1741                extras.putBoolean(Intent.EXTRA_REPLACING,
1742                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1743                break;
1744            }
1745        }
1746        return extras;
1747    }
1748
1749    void scheduleWriteSettingsLocked() {
1750        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1751            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1752        }
1753    }
1754
1755    void scheduleWritePackageRestrictionsLocked(int userId) {
1756        if (!sUserManager.exists(userId)) return;
1757        mDirtyUsers.add(userId);
1758        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1759            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1760        }
1761    }
1762
1763    public static PackageManagerService main(Context context, Installer installer,
1764            boolean factoryTest, boolean onlyCore) {
1765        PackageManagerService m = new PackageManagerService(context, installer,
1766                factoryTest, onlyCore);
1767        ServiceManager.addService("package", m);
1768        return m;
1769    }
1770
1771    static String[] splitString(String str, char sep) {
1772        int count = 1;
1773        int i = 0;
1774        while ((i=str.indexOf(sep, i)) >= 0) {
1775            count++;
1776            i++;
1777        }
1778
1779        String[] res = new String[count];
1780        i=0;
1781        count = 0;
1782        int lastI=0;
1783        while ((i=str.indexOf(sep, i)) >= 0) {
1784            res[count] = str.substring(lastI, i);
1785            count++;
1786            i++;
1787            lastI = i;
1788        }
1789        res[count] = str.substring(lastI, str.length());
1790        return res;
1791    }
1792
1793    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1794        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1795                Context.DISPLAY_SERVICE);
1796        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1797    }
1798
1799    public PackageManagerService(Context context, Installer installer,
1800            boolean factoryTest, boolean onlyCore) {
1801        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1802                SystemClock.uptimeMillis());
1803
1804        if (mSdkVersion <= 0) {
1805            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1806        }
1807
1808        mContext = context;
1809        mFactoryTest = factoryTest;
1810        mOnlyCore = onlyCore;
1811        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1812        mMetrics = new DisplayMetrics();
1813        mSettings = new Settings(mPackages);
1814        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1815                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1816        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1817                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1818        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1819                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1820        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1821                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1822        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1823                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1824        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1825                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1826
1827        // TODO: add a property to control this?
1828        long dexOptLRUThresholdInMinutes;
1829        if (mLazyDexOpt) {
1830            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1831        } else {
1832            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1833        }
1834        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1835
1836        String separateProcesses = SystemProperties.get("debug.separate_processes");
1837        if (separateProcesses != null && separateProcesses.length() > 0) {
1838            if ("*".equals(separateProcesses)) {
1839                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1840                mSeparateProcesses = null;
1841                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1842            } else {
1843                mDefParseFlags = 0;
1844                mSeparateProcesses = separateProcesses.split(",");
1845                Slog.w(TAG, "Running with debug.separate_processes: "
1846                        + separateProcesses);
1847            }
1848        } else {
1849            mDefParseFlags = 0;
1850            mSeparateProcesses = null;
1851        }
1852
1853        mInstaller = installer;
1854        mPackageDexOptimizer = new PackageDexOptimizer(this);
1855        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1856
1857        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1858                FgThread.get().getLooper());
1859
1860        getDefaultDisplayMetrics(context, mMetrics);
1861
1862        SystemConfig systemConfig = SystemConfig.getInstance();
1863        mGlobalGids = systemConfig.getGlobalGids();
1864        mSystemPermissions = systemConfig.getSystemPermissions();
1865        mAvailableFeatures = systemConfig.getAvailableFeatures();
1866
1867        synchronized (mInstallLock) {
1868        // writer
1869        synchronized (mPackages) {
1870            mHandlerThread = new ServiceThread(TAG,
1871                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1872            mHandlerThread.start();
1873            mHandler = new PackageHandler(mHandlerThread.getLooper());
1874            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1875
1876            File dataDir = Environment.getDataDirectory();
1877            mAppDataDir = new File(dataDir, "data");
1878            mAppInstallDir = new File(dataDir, "app");
1879            mAppLib32InstallDir = new File(dataDir, "app-lib");
1880            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1881            mUserAppDataDir = new File(dataDir, "user");
1882            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1883
1884            sUserManager = new UserManagerService(context, this,
1885                    mInstallLock, mPackages);
1886
1887            // Propagate permission configuration in to package manager.
1888            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1889                    = systemConfig.getPermissions();
1890            for (int i=0; i<permConfig.size(); i++) {
1891                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1892                BasePermission bp = mSettings.mPermissions.get(perm.name);
1893                if (bp == null) {
1894                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1895                    mSettings.mPermissions.put(perm.name, bp);
1896                }
1897                if (perm.gids != null) {
1898                    bp.setGids(perm.gids, perm.perUser);
1899                }
1900            }
1901
1902            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1903            for (int i=0; i<libConfig.size(); i++) {
1904                mSharedLibraries.put(libConfig.keyAt(i),
1905                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1906            }
1907
1908            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1909
1910            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1911                    mSdkVersion, mOnlyCore);
1912
1913            String customResolverActivity = Resources.getSystem().getString(
1914                    R.string.config_customResolverActivity);
1915            if (TextUtils.isEmpty(customResolverActivity)) {
1916                customResolverActivity = null;
1917            } else {
1918                mCustomResolverComponentName = ComponentName.unflattenFromString(
1919                        customResolverActivity);
1920            }
1921
1922            long startTime = SystemClock.uptimeMillis();
1923
1924            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1925                    startTime);
1926
1927            // Set flag to monitor and not change apk file paths when
1928            // scanning install directories.
1929            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1930
1931            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1932
1933            /**
1934             * Add everything in the in the boot class path to the
1935             * list of process files because dexopt will have been run
1936             * if necessary during zygote startup.
1937             */
1938            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1939            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1940
1941            if (bootClassPath != null) {
1942                String[] bootClassPathElements = splitString(bootClassPath, ':');
1943                for (String element : bootClassPathElements) {
1944                    alreadyDexOpted.add(element);
1945                }
1946            } else {
1947                Slog.w(TAG, "No BOOTCLASSPATH found!");
1948            }
1949
1950            if (systemServerClassPath != null) {
1951                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1952                for (String element : systemServerClassPathElements) {
1953                    alreadyDexOpted.add(element);
1954                }
1955            } else {
1956                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1957            }
1958
1959            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1960            final String[] dexCodeInstructionSets =
1961                    getDexCodeInstructionSets(
1962                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1963
1964            /**
1965             * Ensure all external libraries have had dexopt run on them.
1966             */
1967            if (mSharedLibraries.size() > 0) {
1968                // NOTE: For now, we're compiling these system "shared libraries"
1969                // (and framework jars) into all available architectures. It's possible
1970                // to compile them only when we come across an app that uses them (there's
1971                // already logic for that in scanPackageLI) but that adds some complexity.
1972                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1973                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1974                        final String lib = libEntry.path;
1975                        if (lib == null) {
1976                            continue;
1977                        }
1978
1979                        try {
1980                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1981                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1982                                alreadyDexOpted.add(lib);
1983                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded, false);
1984                            }
1985                        } catch (FileNotFoundException e) {
1986                            Slog.w(TAG, "Library not found: " + lib);
1987                        } catch (IOException e) {
1988                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1989                                    + e.getMessage());
1990                        }
1991                    }
1992                }
1993            }
1994
1995            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1996
1997            // Gross hack for now: we know this file doesn't contain any
1998            // code, so don't dexopt it to avoid the resulting log spew.
1999            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2000
2001            // Gross hack for now: we know this file is only part of
2002            // the boot class path for art, so don't dexopt it to
2003            // avoid the resulting log spew.
2004            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2005
2006            /**
2007             * There are a number of commands implemented in Java, which
2008             * we currently need to do the dexopt on so that they can be
2009             * run from a non-root shell.
2010             */
2011            String[] frameworkFiles = frameworkDir.list();
2012            if (frameworkFiles != null) {
2013                // TODO: We could compile these only for the most preferred ABI. We should
2014                // first double check that the dex files for these commands are not referenced
2015                // by other system apps.
2016                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2017                    for (int i=0; i<frameworkFiles.length; i++) {
2018                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2019                        String path = libPath.getPath();
2020                        // Skip the file if we already did it.
2021                        if (alreadyDexOpted.contains(path)) {
2022                            continue;
2023                        }
2024                        // Skip the file if it is not a type we want to dexopt.
2025                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2026                            continue;
2027                        }
2028                        try {
2029                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2030                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2031                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded, false);
2032                            }
2033                        } catch (FileNotFoundException e) {
2034                            Slog.w(TAG, "Jar not found: " + path);
2035                        } catch (IOException e) {
2036                            Slog.w(TAG, "Exception reading jar: " + path, e);
2037                        }
2038                    }
2039                }
2040            }
2041
2042            final VersionInfo ver = mSettings.getInternalVersion();
2043            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2044            // when upgrading from pre-M, promote system app permissions from install to runtime
2045            mPromoteSystemApps =
2046                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2047
2048            // save off the names of pre-existing system packages prior to scanning; we don't
2049            // want to automatically grant runtime permissions for new system apps
2050            if (mPromoteSystemApps) {
2051                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2052                while (pkgSettingIter.hasNext()) {
2053                    PackageSetting ps = pkgSettingIter.next();
2054                    if (isSystemApp(ps)) {
2055                        mExistingSystemPackages.add(ps.name);
2056                    }
2057                }
2058            }
2059
2060            // Collect vendor overlay packages.
2061            // (Do this before scanning any apps.)
2062            // For security and version matching reason, only consider
2063            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2064            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2065            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2066                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2067
2068            // Find base frameworks (resource packages without code).
2069            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2070                    | PackageParser.PARSE_IS_SYSTEM_DIR
2071                    | PackageParser.PARSE_IS_PRIVILEGED,
2072                    scanFlags | SCAN_NO_DEX, 0);
2073
2074            // Collected privileged system packages.
2075            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2076            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2077                    | PackageParser.PARSE_IS_SYSTEM_DIR
2078                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2079
2080            // Collect ordinary system packages.
2081            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2082            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2083                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2084
2085            // Collect all vendor packages.
2086            File vendorAppDir = new File("/vendor/app");
2087            try {
2088                vendorAppDir = vendorAppDir.getCanonicalFile();
2089            } catch (IOException e) {
2090                // failed to look up canonical path, continue with original one
2091            }
2092            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2093                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2094
2095            // Collect all OEM packages.
2096            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2097            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2098                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2099
2100            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2101            mInstaller.moveFiles();
2102
2103            // Prune any system packages that no longer exist.
2104            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2105            if (!mOnlyCore) {
2106                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2107                while (psit.hasNext()) {
2108                    PackageSetting ps = psit.next();
2109
2110                    /*
2111                     * If this is not a system app, it can't be a
2112                     * disable system app.
2113                     */
2114                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2115                        continue;
2116                    }
2117
2118                    /*
2119                     * If the package is scanned, it's not erased.
2120                     */
2121                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2122                    if (scannedPkg != null) {
2123                        /*
2124                         * If the system app is both scanned and in the
2125                         * disabled packages list, then it must have been
2126                         * added via OTA. Remove it from the currently
2127                         * scanned package so the previously user-installed
2128                         * application can be scanned.
2129                         */
2130                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2131                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2132                                    + ps.name + "; removing system app.  Last known codePath="
2133                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2134                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2135                                    + scannedPkg.mVersionCode);
2136                            removePackageLI(ps, true);
2137                            mExpectingBetter.put(ps.name, ps.codePath);
2138                        }
2139
2140                        continue;
2141                    }
2142
2143                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2144                        psit.remove();
2145                        logCriticalInfo(Log.WARN, "System package " + ps.name
2146                                + " no longer exists; wiping its data");
2147                        removeDataDirsLI(null, ps.name);
2148                    } else {
2149                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2150                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2151                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2152                        }
2153                    }
2154                }
2155            }
2156
2157            //look for any incomplete package installations
2158            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2159            //clean up list
2160            for(int i = 0; i < deletePkgsList.size(); i++) {
2161                //clean up here
2162                cleanupInstallFailedPackage(deletePkgsList.get(i));
2163            }
2164            //delete tmp files
2165            deleteTempPackageFiles();
2166
2167            // Remove any shared userIDs that have no associated packages
2168            mSettings.pruneSharedUsersLPw();
2169
2170            if (!mOnlyCore) {
2171                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2172                        SystemClock.uptimeMillis());
2173                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2174
2175                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2176                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2177
2178                /**
2179                 * Remove disable package settings for any updated system
2180                 * apps that were removed via an OTA. If they're not a
2181                 * previously-updated app, remove them completely.
2182                 * Otherwise, just revoke their system-level permissions.
2183                 */
2184                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2185                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2186                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2187
2188                    String msg;
2189                    if (deletedPkg == null) {
2190                        msg = "Updated system package " + deletedAppName
2191                                + " no longer exists; wiping its data";
2192                        removeDataDirsLI(null, deletedAppName);
2193                    } else {
2194                        msg = "Updated system app + " + deletedAppName
2195                                + " no longer present; removing system privileges for "
2196                                + deletedAppName;
2197
2198                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2199
2200                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2201                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2202                    }
2203                    logCriticalInfo(Log.WARN, msg);
2204                }
2205
2206                /**
2207                 * Make sure all system apps that we expected to appear on
2208                 * the userdata partition actually showed up. If they never
2209                 * appeared, crawl back and revive the system version.
2210                 */
2211                for (int i = 0; i < mExpectingBetter.size(); i++) {
2212                    final String packageName = mExpectingBetter.keyAt(i);
2213                    if (!mPackages.containsKey(packageName)) {
2214                        final File scanFile = mExpectingBetter.valueAt(i);
2215
2216                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2217                                + " but never showed up; reverting to system");
2218
2219                        final int reparseFlags;
2220                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2221                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2222                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2223                                    | PackageParser.PARSE_IS_PRIVILEGED;
2224                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2225                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2226                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2227                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2228                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2229                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2230                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2231                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2232                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2233                        } else {
2234                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2235                            continue;
2236                        }
2237
2238                        mSettings.enableSystemPackageLPw(packageName);
2239
2240                        try {
2241                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2242                        } catch (PackageManagerException e) {
2243                            Slog.e(TAG, "Failed to parse original system package: "
2244                                    + e.getMessage());
2245                        }
2246                    }
2247                }
2248            }
2249            mExpectingBetter.clear();
2250
2251            // Now that we know all of the shared libraries, update all clients to have
2252            // the correct library paths.
2253            updateAllSharedLibrariesLPw();
2254
2255            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2256                // NOTE: We ignore potential failures here during a system scan (like
2257                // the rest of the commands above) because there's precious little we
2258                // can do about it. A settings error is reported, though.
2259                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2260                        false /* force dexopt */, false /* defer dexopt */,
2261                        false /* boot complete */);
2262            }
2263
2264            // Now that we know all the packages we are keeping,
2265            // read and update their last usage times.
2266            mPackageUsage.readLP();
2267
2268            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2269                    SystemClock.uptimeMillis());
2270            Slog.i(TAG, "Time to scan packages: "
2271                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2272                    + " seconds");
2273
2274            // If the platform SDK has changed since the last time we booted,
2275            // we need to re-grant app permission to catch any new ones that
2276            // appear.  This is really a hack, and means that apps can in some
2277            // cases get permissions that the user didn't initially explicitly
2278            // allow...  it would be nice to have some better way to handle
2279            // this situation.
2280            int updateFlags = UPDATE_PERMISSIONS_ALL;
2281            if (ver.sdkVersion != mSdkVersion) {
2282                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2283                        + mSdkVersion + "; regranting permissions for internal storage");
2284                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2285            }
2286            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2287            ver.sdkVersion = mSdkVersion;
2288
2289            // If this is the first boot or an update from pre-M, and it is a normal
2290            // boot, then we need to initialize the default preferred apps across
2291            // all defined users.
2292            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2293                for (UserInfo user : sUserManager.getUsers(true)) {
2294                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2295                    applyFactoryDefaultBrowserLPw(user.id);
2296                    primeDomainVerificationsLPw(user.id);
2297                }
2298            }
2299
2300            // If this is first boot after an OTA, and a normal boot, then
2301            // we need to clear code cache directories.
2302            if (mIsUpgrade && !onlyCore) {
2303                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2304                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2305                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2306                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2307                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2308                    }
2309                }
2310                ver.fingerprint = Build.FINGERPRINT;
2311            }
2312
2313            checkDefaultBrowser();
2314
2315            // clear only after permissions and other defaults have been updated
2316            mExistingSystemPackages.clear();
2317            mPromoteSystemApps = false;
2318
2319            // All the changes are done during package scanning.
2320            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2321
2322            // can downgrade to reader
2323            mSettings.writeLPr();
2324
2325            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2326                    SystemClock.uptimeMillis());
2327
2328            mRequiredVerifierPackage = getRequiredVerifierLPr();
2329            mRequiredInstallerPackage = getRequiredInstallerLPr();
2330
2331            mInstallerService = new PackageInstallerService(context, this);
2332
2333            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2334            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2335                    mIntentFilterVerifierComponent);
2336
2337        } // synchronized (mPackages)
2338        } // synchronized (mInstallLock)
2339
2340        // Now after opening every single application zip, make sure they
2341        // are all flushed.  Not really needed, but keeps things nice and
2342        // tidy.
2343        Runtime.getRuntime().gc();
2344
2345        // Expose private service for system components to use.
2346        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2347    }
2348
2349    @Override
2350    public boolean isFirstBoot() {
2351        return !mRestoredSettings;
2352    }
2353
2354    @Override
2355    public boolean isOnlyCoreApps() {
2356        return mOnlyCore;
2357    }
2358
2359    @Override
2360    public boolean isUpgrade() {
2361        return mIsUpgrade;
2362    }
2363
2364    private String getRequiredVerifierLPr() {
2365        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2366        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2367                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2368
2369        String requiredVerifier = null;
2370
2371        final int N = receivers.size();
2372        for (int i = 0; i < N; i++) {
2373            final ResolveInfo info = receivers.get(i);
2374
2375            if (info.activityInfo == null) {
2376                continue;
2377            }
2378
2379            final String packageName = info.activityInfo.packageName;
2380
2381            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2382                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2383                continue;
2384            }
2385
2386            if (requiredVerifier != null) {
2387                throw new RuntimeException("There can be only one required verifier");
2388            }
2389
2390            requiredVerifier = packageName;
2391        }
2392
2393        return requiredVerifier;
2394    }
2395
2396    private String getRequiredInstallerLPr() {
2397        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2398        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2399        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2400
2401        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2402                PACKAGE_MIME_TYPE, 0, 0);
2403
2404        String requiredInstaller = null;
2405
2406        final int N = installers.size();
2407        for (int i = 0; i < N; i++) {
2408            final ResolveInfo info = installers.get(i);
2409            final String packageName = info.activityInfo.packageName;
2410
2411            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2412                continue;
2413            }
2414
2415            if (requiredInstaller != null) {
2416                throw new RuntimeException("There must be one required installer");
2417            }
2418
2419            requiredInstaller = packageName;
2420        }
2421
2422        if (requiredInstaller == null) {
2423            throw new RuntimeException("There must be one required installer");
2424        }
2425
2426        return requiredInstaller;
2427    }
2428
2429    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2430        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2431        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2432                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2433
2434        ComponentName verifierComponentName = null;
2435
2436        int priority = -1000;
2437        final int N = receivers.size();
2438        for (int i = 0; i < N; i++) {
2439            final ResolveInfo info = receivers.get(i);
2440
2441            if (info.activityInfo == null) {
2442                continue;
2443            }
2444
2445            final String packageName = info.activityInfo.packageName;
2446
2447            final PackageSetting ps = mSettings.mPackages.get(packageName);
2448            if (ps == null) {
2449                continue;
2450            }
2451
2452            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2453                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2454                continue;
2455            }
2456
2457            // Select the IntentFilterVerifier with the highest priority
2458            if (priority < info.priority) {
2459                priority = info.priority;
2460                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2461                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2462                        + verifierComponentName + " with priority: " + info.priority);
2463            }
2464        }
2465
2466        return verifierComponentName;
2467    }
2468
2469    private void primeDomainVerificationsLPw(int userId) {
2470        if (DEBUG_DOMAIN_VERIFICATION) {
2471            Slog.d(TAG, "Priming domain verifications in user " + userId);
2472        }
2473
2474        SystemConfig systemConfig = SystemConfig.getInstance();
2475        ArraySet<String> packages = systemConfig.getLinkedApps();
2476        ArraySet<String> domains = new ArraySet<String>();
2477
2478        for (String packageName : packages) {
2479            PackageParser.Package pkg = mPackages.get(packageName);
2480            if (pkg != null) {
2481                if (!pkg.isSystemApp()) {
2482                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2483                    continue;
2484                }
2485
2486                domains.clear();
2487                for (PackageParser.Activity a : pkg.activities) {
2488                    for (ActivityIntentInfo filter : a.intents) {
2489                        if (hasValidDomains(filter)) {
2490                            domains.addAll(filter.getHostsList());
2491                        }
2492                    }
2493                }
2494
2495                if (domains.size() > 0) {
2496                    if (DEBUG_DOMAIN_VERIFICATION) {
2497                        Slog.v(TAG, "      + " + packageName);
2498                    }
2499                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2500                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2501                    // and then 'always' in the per-user state actually used for intent resolution.
2502                    final IntentFilterVerificationInfo ivi;
2503                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2504                            new ArrayList<String>(domains));
2505                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2506                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2507                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2508                } else {
2509                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2510                            + "' does not handle web links");
2511                }
2512            } else {
2513                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2514            }
2515        }
2516
2517        scheduleWritePackageRestrictionsLocked(userId);
2518        scheduleWriteSettingsLocked();
2519    }
2520
2521    private void applyFactoryDefaultBrowserLPw(int userId) {
2522        // The default browser app's package name is stored in a string resource,
2523        // with a product-specific overlay used for vendor customization.
2524        String browserPkg = mContext.getResources().getString(
2525                com.android.internal.R.string.default_browser);
2526        if (!TextUtils.isEmpty(browserPkg)) {
2527            // non-empty string => required to be a known package
2528            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2529            if (ps == null) {
2530                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2531                browserPkg = null;
2532            } else {
2533                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2534            }
2535        }
2536
2537        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2538        // default.  If there's more than one, just leave everything alone.
2539        if (browserPkg == null) {
2540            calculateDefaultBrowserLPw(userId);
2541        }
2542    }
2543
2544    private void calculateDefaultBrowserLPw(int userId) {
2545        List<String> allBrowsers = resolveAllBrowserApps(userId);
2546        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2547        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2548    }
2549
2550    private List<String> resolveAllBrowserApps(int userId) {
2551        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2552        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2553                PackageManager.MATCH_ALL, userId);
2554
2555        final int count = list.size();
2556        List<String> result = new ArrayList<String>(count);
2557        for (int i=0; i<count; i++) {
2558            ResolveInfo info = list.get(i);
2559            if (info.activityInfo == null
2560                    || !info.handleAllWebDataURI
2561                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2562                    || result.contains(info.activityInfo.packageName)) {
2563                continue;
2564            }
2565            result.add(info.activityInfo.packageName);
2566        }
2567
2568        return result;
2569    }
2570
2571    private boolean packageIsBrowser(String packageName, int userId) {
2572        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2573                PackageManager.MATCH_ALL, userId);
2574        final int N = list.size();
2575        for (int i = 0; i < N; i++) {
2576            ResolveInfo info = list.get(i);
2577            if (packageName.equals(info.activityInfo.packageName)) {
2578                return true;
2579            }
2580        }
2581        return false;
2582    }
2583
2584    private void checkDefaultBrowser() {
2585        final int myUserId = UserHandle.myUserId();
2586        final String packageName = getDefaultBrowserPackageName(myUserId);
2587        if (packageName != null) {
2588            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2589            if (info == null) {
2590                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2591                synchronized (mPackages) {
2592                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2593                }
2594            }
2595        }
2596    }
2597
2598    @Override
2599    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2600            throws RemoteException {
2601        try {
2602            return super.onTransact(code, data, reply, flags);
2603        } catch (RuntimeException e) {
2604            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2605                Slog.wtf(TAG, "Package Manager Crash", e);
2606            }
2607            throw e;
2608        }
2609    }
2610
2611    void cleanupInstallFailedPackage(PackageSetting ps) {
2612        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2613
2614        removeDataDirsLI(ps.volumeUuid, ps.name);
2615        if (ps.codePath != null) {
2616            if (ps.codePath.isDirectory()) {
2617                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2618            } else {
2619                ps.codePath.delete();
2620            }
2621        }
2622        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2623            if (ps.resourcePath.isDirectory()) {
2624                FileUtils.deleteContents(ps.resourcePath);
2625            }
2626            ps.resourcePath.delete();
2627        }
2628        mSettings.removePackageLPw(ps.name);
2629    }
2630
2631    static int[] appendInts(int[] cur, int[] add) {
2632        if (add == null) return cur;
2633        if (cur == null) return add;
2634        final int N = add.length;
2635        for (int i=0; i<N; i++) {
2636            cur = appendInt(cur, add[i]);
2637        }
2638        return cur;
2639    }
2640
2641    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2642        if (!sUserManager.exists(userId)) return null;
2643        final PackageSetting ps = (PackageSetting) p.mExtras;
2644        if (ps == null) {
2645            return null;
2646        }
2647
2648        final PermissionsState permissionsState = ps.getPermissionsState();
2649
2650        final int[] gids = permissionsState.computeGids(userId);
2651        final Set<String> permissions = permissionsState.getPermissions(userId);
2652        final PackageUserState state = ps.readUserState(userId);
2653
2654        return PackageParser.generatePackageInfo(p, gids, flags,
2655                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2656    }
2657
2658    @Override
2659    public boolean isPackageFrozen(String packageName) {
2660        synchronized (mPackages) {
2661            final PackageSetting ps = mSettings.mPackages.get(packageName);
2662            if (ps != null) {
2663                return ps.frozen;
2664            }
2665        }
2666        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2667        return true;
2668    }
2669
2670    @Override
2671    public boolean isPackageAvailable(String packageName, int userId) {
2672        if (!sUserManager.exists(userId)) return false;
2673        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2674        synchronized (mPackages) {
2675            PackageParser.Package p = mPackages.get(packageName);
2676            if (p != null) {
2677                final PackageSetting ps = (PackageSetting) p.mExtras;
2678                if (ps != null) {
2679                    final PackageUserState state = ps.readUserState(userId);
2680                    if (state != null) {
2681                        return PackageParser.isAvailable(state);
2682                    }
2683                }
2684            }
2685        }
2686        return false;
2687    }
2688
2689    @Override
2690    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2691        if (!sUserManager.exists(userId)) return null;
2692        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2693        // reader
2694        synchronized (mPackages) {
2695            PackageParser.Package p = mPackages.get(packageName);
2696            if (DEBUG_PACKAGE_INFO)
2697                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2698            if (p != null) {
2699                return generatePackageInfo(p, flags, userId);
2700            }
2701            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2702                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2703            }
2704        }
2705        return null;
2706    }
2707
2708    @Override
2709    public String[] currentToCanonicalPackageNames(String[] names) {
2710        String[] out = new String[names.length];
2711        // reader
2712        synchronized (mPackages) {
2713            for (int i=names.length-1; i>=0; i--) {
2714                PackageSetting ps = mSettings.mPackages.get(names[i]);
2715                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2716            }
2717        }
2718        return out;
2719    }
2720
2721    @Override
2722    public String[] canonicalToCurrentPackageNames(String[] names) {
2723        String[] out = new String[names.length];
2724        // reader
2725        synchronized (mPackages) {
2726            for (int i=names.length-1; i>=0; i--) {
2727                String cur = mSettings.mRenamedPackages.get(names[i]);
2728                out[i] = cur != null ? cur : names[i];
2729            }
2730        }
2731        return out;
2732    }
2733
2734    @Override
2735    public int getPackageUid(String packageName, int userId) {
2736        if (!sUserManager.exists(userId)) return -1;
2737        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2738
2739        // reader
2740        synchronized (mPackages) {
2741            PackageParser.Package p = mPackages.get(packageName);
2742            if(p != null) {
2743                return UserHandle.getUid(userId, p.applicationInfo.uid);
2744            }
2745            PackageSetting ps = mSettings.mPackages.get(packageName);
2746            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2747                return -1;
2748            }
2749            p = ps.pkg;
2750            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2751        }
2752    }
2753
2754    @Override
2755    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2756        if (!sUserManager.exists(userId)) {
2757            return null;
2758        }
2759
2760        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2761                "getPackageGids");
2762
2763        // reader
2764        synchronized (mPackages) {
2765            PackageParser.Package p = mPackages.get(packageName);
2766            if (DEBUG_PACKAGE_INFO) {
2767                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2768            }
2769            if (p != null) {
2770                PackageSetting ps = (PackageSetting) p.mExtras;
2771                return ps.getPermissionsState().computeGids(userId);
2772            }
2773        }
2774
2775        return null;
2776    }
2777
2778    static PermissionInfo generatePermissionInfo(
2779            BasePermission bp, int flags) {
2780        if (bp.perm != null) {
2781            return PackageParser.generatePermissionInfo(bp.perm, flags);
2782        }
2783        PermissionInfo pi = new PermissionInfo();
2784        pi.name = bp.name;
2785        pi.packageName = bp.sourcePackage;
2786        pi.nonLocalizedLabel = bp.name;
2787        pi.protectionLevel = bp.protectionLevel;
2788        return pi;
2789    }
2790
2791    @Override
2792    public PermissionInfo getPermissionInfo(String name, int flags) {
2793        // reader
2794        synchronized (mPackages) {
2795            final BasePermission p = mSettings.mPermissions.get(name);
2796            if (p != null) {
2797                return generatePermissionInfo(p, flags);
2798            }
2799            return null;
2800        }
2801    }
2802
2803    @Override
2804    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2805        // reader
2806        synchronized (mPackages) {
2807            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2808            for (BasePermission p : mSettings.mPermissions.values()) {
2809                if (group == null) {
2810                    if (p.perm == null || p.perm.info.group == null) {
2811                        out.add(generatePermissionInfo(p, flags));
2812                    }
2813                } else {
2814                    if (p.perm != null && group.equals(p.perm.info.group)) {
2815                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2816                    }
2817                }
2818            }
2819
2820            if (out.size() > 0) {
2821                return out;
2822            }
2823            return mPermissionGroups.containsKey(group) ? out : null;
2824        }
2825    }
2826
2827    @Override
2828    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2829        // reader
2830        synchronized (mPackages) {
2831            return PackageParser.generatePermissionGroupInfo(
2832                    mPermissionGroups.get(name), flags);
2833        }
2834    }
2835
2836    @Override
2837    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2838        // reader
2839        synchronized (mPackages) {
2840            final int N = mPermissionGroups.size();
2841            ArrayList<PermissionGroupInfo> out
2842                    = new ArrayList<PermissionGroupInfo>(N);
2843            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2844                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2845            }
2846            return out;
2847        }
2848    }
2849
2850    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2851            int userId) {
2852        if (!sUserManager.exists(userId)) return null;
2853        PackageSetting ps = mSettings.mPackages.get(packageName);
2854        if (ps != null) {
2855            if (ps.pkg == null) {
2856                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2857                        flags, userId);
2858                if (pInfo != null) {
2859                    return pInfo.applicationInfo;
2860                }
2861                return null;
2862            }
2863            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2864                    ps.readUserState(userId), userId);
2865        }
2866        return null;
2867    }
2868
2869    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2870            int userId) {
2871        if (!sUserManager.exists(userId)) return null;
2872        PackageSetting ps = mSettings.mPackages.get(packageName);
2873        if (ps != null) {
2874            PackageParser.Package pkg = ps.pkg;
2875            if (pkg == null) {
2876                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2877                    return null;
2878                }
2879                // Only data remains, so we aren't worried about code paths
2880                pkg = new PackageParser.Package(packageName);
2881                pkg.applicationInfo.packageName = packageName;
2882                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2883                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2884                pkg.applicationInfo.dataDir = Environment
2885                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2886                        .getAbsolutePath();
2887                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2888                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2889            }
2890            return generatePackageInfo(pkg, flags, userId);
2891        }
2892        return null;
2893    }
2894
2895    @Override
2896    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2897        if (!sUserManager.exists(userId)) return null;
2898        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2899        // writer
2900        synchronized (mPackages) {
2901            PackageParser.Package p = mPackages.get(packageName);
2902            if (DEBUG_PACKAGE_INFO) Log.v(
2903                    TAG, "getApplicationInfo " + packageName
2904                    + ": " + p);
2905            if (p != null) {
2906                PackageSetting ps = mSettings.mPackages.get(packageName);
2907                if (ps == null) return null;
2908                // Note: isEnabledLP() does not apply here - always return info
2909                return PackageParser.generateApplicationInfo(
2910                        p, flags, ps.readUserState(userId), userId);
2911            }
2912            if ("android".equals(packageName)||"system".equals(packageName)) {
2913                return mAndroidApplication;
2914            }
2915            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2916                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2917            }
2918        }
2919        return null;
2920    }
2921
2922    @Override
2923    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2924            final IPackageDataObserver observer) {
2925        mContext.enforceCallingOrSelfPermission(
2926                android.Manifest.permission.CLEAR_APP_CACHE, null);
2927        // Queue up an async operation since clearing cache may take a little while.
2928        mHandler.post(new Runnable() {
2929            public void run() {
2930                mHandler.removeCallbacks(this);
2931                int retCode = -1;
2932                synchronized (mInstallLock) {
2933                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2934                    if (retCode < 0) {
2935                        Slog.w(TAG, "Couldn't clear application caches");
2936                    }
2937                }
2938                if (observer != null) {
2939                    try {
2940                        observer.onRemoveCompleted(null, (retCode >= 0));
2941                    } catch (RemoteException e) {
2942                        Slog.w(TAG, "RemoveException when invoking call back");
2943                    }
2944                }
2945            }
2946        });
2947    }
2948
2949    @Override
2950    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2951            final IntentSender pi) {
2952        mContext.enforceCallingOrSelfPermission(
2953                android.Manifest.permission.CLEAR_APP_CACHE, null);
2954        // Queue up an async operation since clearing cache may take a little while.
2955        mHandler.post(new Runnable() {
2956            public void run() {
2957                mHandler.removeCallbacks(this);
2958                int retCode = -1;
2959                synchronized (mInstallLock) {
2960                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2961                    if (retCode < 0) {
2962                        Slog.w(TAG, "Couldn't clear application caches");
2963                    }
2964                }
2965                if(pi != null) {
2966                    try {
2967                        // Callback via pending intent
2968                        int code = (retCode >= 0) ? 1 : 0;
2969                        pi.sendIntent(null, code, null,
2970                                null, null);
2971                    } catch (SendIntentException e1) {
2972                        Slog.i(TAG, "Failed to send pending intent");
2973                    }
2974                }
2975            }
2976        });
2977    }
2978
2979    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2980        synchronized (mInstallLock) {
2981            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2982                throw new IOException("Failed to free enough space");
2983            }
2984        }
2985    }
2986
2987    @Override
2988    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2989        if (!sUserManager.exists(userId)) return null;
2990        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2991        synchronized (mPackages) {
2992            PackageParser.Activity a = mActivities.mActivities.get(component);
2993
2994            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2995            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2996                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2997                if (ps == null) return null;
2998                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2999                        userId);
3000            }
3001            if (mResolveComponentName.equals(component)) {
3002                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3003                        new PackageUserState(), userId);
3004            }
3005        }
3006        return null;
3007    }
3008
3009    @Override
3010    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3011            String resolvedType) {
3012        synchronized (mPackages) {
3013            if (component.equals(mResolveComponentName)) {
3014                // The resolver supports EVERYTHING!
3015                return true;
3016            }
3017            PackageParser.Activity a = mActivities.mActivities.get(component);
3018            if (a == null) {
3019                return false;
3020            }
3021            for (int i=0; i<a.intents.size(); i++) {
3022                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3023                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3024                    return true;
3025                }
3026            }
3027            return false;
3028        }
3029    }
3030
3031    @Override
3032    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3033        if (!sUserManager.exists(userId)) return null;
3034        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3035        synchronized (mPackages) {
3036            PackageParser.Activity a = mReceivers.mActivities.get(component);
3037            if (DEBUG_PACKAGE_INFO) Log.v(
3038                TAG, "getReceiverInfo " + component + ": " + a);
3039            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3040                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3041                if (ps == null) return null;
3042                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3043                        userId);
3044            }
3045        }
3046        return null;
3047    }
3048
3049    @Override
3050    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3051        if (!sUserManager.exists(userId)) return null;
3052        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3053        synchronized (mPackages) {
3054            PackageParser.Service s = mServices.mServices.get(component);
3055            if (DEBUG_PACKAGE_INFO) Log.v(
3056                TAG, "getServiceInfo " + component + ": " + s);
3057            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3058                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3059                if (ps == null) return null;
3060                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3061                        userId);
3062            }
3063        }
3064        return null;
3065    }
3066
3067    @Override
3068    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3069        if (!sUserManager.exists(userId)) return null;
3070        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3071        synchronized (mPackages) {
3072            PackageParser.Provider p = mProviders.mProviders.get(component);
3073            if (DEBUG_PACKAGE_INFO) Log.v(
3074                TAG, "getProviderInfo " + component + ": " + p);
3075            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3076                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3077                if (ps == null) return null;
3078                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3079                        userId);
3080            }
3081        }
3082        return null;
3083    }
3084
3085    @Override
3086    public String[] getSystemSharedLibraryNames() {
3087        Set<String> libSet;
3088        synchronized (mPackages) {
3089            libSet = mSharedLibraries.keySet();
3090            int size = libSet.size();
3091            if (size > 0) {
3092                String[] libs = new String[size];
3093                libSet.toArray(libs);
3094                return libs;
3095            }
3096        }
3097        return null;
3098    }
3099
3100    /**
3101     * @hide
3102     */
3103    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3104        synchronized (mPackages) {
3105            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3106            if (lib != null && lib.apk != null) {
3107                return mPackages.get(lib.apk);
3108            }
3109        }
3110        return null;
3111    }
3112
3113    @Override
3114    public FeatureInfo[] getSystemAvailableFeatures() {
3115        Collection<FeatureInfo> featSet;
3116        synchronized (mPackages) {
3117            featSet = mAvailableFeatures.values();
3118            int size = featSet.size();
3119            if (size > 0) {
3120                FeatureInfo[] features = new FeatureInfo[size+1];
3121                featSet.toArray(features);
3122                FeatureInfo fi = new FeatureInfo();
3123                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3124                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3125                features[size] = fi;
3126                return features;
3127            }
3128        }
3129        return null;
3130    }
3131
3132    @Override
3133    public boolean hasSystemFeature(String name) {
3134        synchronized (mPackages) {
3135            return mAvailableFeatures.containsKey(name);
3136        }
3137    }
3138
3139    private void checkValidCaller(int uid, int userId) {
3140        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3141            return;
3142
3143        throw new SecurityException("Caller uid=" + uid
3144                + " is not privileged to communicate with user=" + userId);
3145    }
3146
3147    @Override
3148    public int checkPermission(String permName, String pkgName, int userId) {
3149        if (!sUserManager.exists(userId)) {
3150            return PackageManager.PERMISSION_DENIED;
3151        }
3152
3153        synchronized (mPackages) {
3154            final PackageParser.Package p = mPackages.get(pkgName);
3155            if (p != null && p.mExtras != null) {
3156                final PackageSetting ps = (PackageSetting) p.mExtras;
3157                final PermissionsState permissionsState = ps.getPermissionsState();
3158                if (permissionsState.hasPermission(permName, userId)) {
3159                    return PackageManager.PERMISSION_GRANTED;
3160                }
3161                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3162                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3163                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3164                    return PackageManager.PERMISSION_GRANTED;
3165                }
3166            }
3167        }
3168
3169        return PackageManager.PERMISSION_DENIED;
3170    }
3171
3172    @Override
3173    public int checkUidPermission(String permName, int uid) {
3174        final int userId = UserHandle.getUserId(uid);
3175
3176        if (!sUserManager.exists(userId)) {
3177            return PackageManager.PERMISSION_DENIED;
3178        }
3179
3180        synchronized (mPackages) {
3181            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3182            if (obj != null) {
3183                final SettingBase ps = (SettingBase) obj;
3184                final PermissionsState permissionsState = ps.getPermissionsState();
3185                if (permissionsState.hasPermission(permName, userId)) {
3186                    return PackageManager.PERMISSION_GRANTED;
3187                }
3188                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3189                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3190                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3191                    return PackageManager.PERMISSION_GRANTED;
3192                }
3193            } else {
3194                ArraySet<String> perms = mSystemPermissions.get(uid);
3195                if (perms != null) {
3196                    if (perms.contains(permName)) {
3197                        return PackageManager.PERMISSION_GRANTED;
3198                    }
3199                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3200                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3201                        return PackageManager.PERMISSION_GRANTED;
3202                    }
3203                }
3204            }
3205        }
3206
3207        return PackageManager.PERMISSION_DENIED;
3208    }
3209
3210    @Override
3211    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3212        if (UserHandle.getCallingUserId() != userId) {
3213            mContext.enforceCallingPermission(
3214                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3215                    "isPermissionRevokedByPolicy for user " + userId);
3216        }
3217
3218        if (checkPermission(permission, packageName, userId)
3219                == PackageManager.PERMISSION_GRANTED) {
3220            return false;
3221        }
3222
3223        final long identity = Binder.clearCallingIdentity();
3224        try {
3225            final int flags = getPermissionFlags(permission, packageName, userId);
3226            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3227        } finally {
3228            Binder.restoreCallingIdentity(identity);
3229        }
3230    }
3231
3232    @Override
3233    public String getPermissionControllerPackageName() {
3234        synchronized (mPackages) {
3235            return mRequiredInstallerPackage;
3236        }
3237    }
3238
3239    /**
3240     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3241     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3242     * @param checkShell TODO(yamasani):
3243     * @param message the message to log on security exception
3244     */
3245    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3246            boolean checkShell, String message) {
3247        if (userId < 0) {
3248            throw new IllegalArgumentException("Invalid userId " + userId);
3249        }
3250        if (checkShell) {
3251            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3252        }
3253        if (userId == UserHandle.getUserId(callingUid)) return;
3254        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3255            if (requireFullPermission) {
3256                mContext.enforceCallingOrSelfPermission(
3257                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3258            } else {
3259                try {
3260                    mContext.enforceCallingOrSelfPermission(
3261                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3262                } catch (SecurityException se) {
3263                    mContext.enforceCallingOrSelfPermission(
3264                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3265                }
3266            }
3267        }
3268    }
3269
3270    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3271        if (callingUid == Process.SHELL_UID) {
3272            if (userHandle >= 0
3273                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3274                throw new SecurityException("Shell does not have permission to access user "
3275                        + userHandle);
3276            } else if (userHandle < 0) {
3277                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3278                        + Debug.getCallers(3));
3279            }
3280        }
3281    }
3282
3283    private BasePermission findPermissionTreeLP(String permName) {
3284        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3285            if (permName.startsWith(bp.name) &&
3286                    permName.length() > bp.name.length() &&
3287                    permName.charAt(bp.name.length()) == '.') {
3288                return bp;
3289            }
3290        }
3291        return null;
3292    }
3293
3294    private BasePermission checkPermissionTreeLP(String permName) {
3295        if (permName != null) {
3296            BasePermission bp = findPermissionTreeLP(permName);
3297            if (bp != null) {
3298                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3299                    return bp;
3300                }
3301                throw new SecurityException("Calling uid "
3302                        + Binder.getCallingUid()
3303                        + " is not allowed to add to permission tree "
3304                        + bp.name + " owned by uid " + bp.uid);
3305            }
3306        }
3307        throw new SecurityException("No permission tree found for " + permName);
3308    }
3309
3310    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3311        if (s1 == null) {
3312            return s2 == null;
3313        }
3314        if (s2 == null) {
3315            return false;
3316        }
3317        if (s1.getClass() != s2.getClass()) {
3318            return false;
3319        }
3320        return s1.equals(s2);
3321    }
3322
3323    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3324        if (pi1.icon != pi2.icon) return false;
3325        if (pi1.logo != pi2.logo) return false;
3326        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3327        if (!compareStrings(pi1.name, pi2.name)) return false;
3328        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3329        // We'll take care of setting this one.
3330        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3331        // These are not currently stored in settings.
3332        //if (!compareStrings(pi1.group, pi2.group)) return false;
3333        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3334        //if (pi1.labelRes != pi2.labelRes) return false;
3335        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3336        return true;
3337    }
3338
3339    int permissionInfoFootprint(PermissionInfo info) {
3340        int size = info.name.length();
3341        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3342        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3343        return size;
3344    }
3345
3346    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3347        int size = 0;
3348        for (BasePermission perm : mSettings.mPermissions.values()) {
3349            if (perm.uid == tree.uid) {
3350                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3351            }
3352        }
3353        return size;
3354    }
3355
3356    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3357        // We calculate the max size of permissions defined by this uid and throw
3358        // if that plus the size of 'info' would exceed our stated maximum.
3359        if (tree.uid != Process.SYSTEM_UID) {
3360            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3361            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3362                throw new SecurityException("Permission tree size cap exceeded");
3363            }
3364        }
3365    }
3366
3367    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3368        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3369            throw new SecurityException("Label must be specified in permission");
3370        }
3371        BasePermission tree = checkPermissionTreeLP(info.name);
3372        BasePermission bp = mSettings.mPermissions.get(info.name);
3373        boolean added = bp == null;
3374        boolean changed = true;
3375        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3376        if (added) {
3377            enforcePermissionCapLocked(info, tree);
3378            bp = new BasePermission(info.name, tree.sourcePackage,
3379                    BasePermission.TYPE_DYNAMIC);
3380        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3381            throw new SecurityException(
3382                    "Not allowed to modify non-dynamic permission "
3383                    + info.name);
3384        } else {
3385            if (bp.protectionLevel == fixedLevel
3386                    && bp.perm.owner.equals(tree.perm.owner)
3387                    && bp.uid == tree.uid
3388                    && comparePermissionInfos(bp.perm.info, info)) {
3389                changed = false;
3390            }
3391        }
3392        bp.protectionLevel = fixedLevel;
3393        info = new PermissionInfo(info);
3394        info.protectionLevel = fixedLevel;
3395        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3396        bp.perm.info.packageName = tree.perm.info.packageName;
3397        bp.uid = tree.uid;
3398        if (added) {
3399            mSettings.mPermissions.put(info.name, bp);
3400        }
3401        if (changed) {
3402            if (!async) {
3403                mSettings.writeLPr();
3404            } else {
3405                scheduleWriteSettingsLocked();
3406            }
3407        }
3408        return added;
3409    }
3410
3411    @Override
3412    public boolean addPermission(PermissionInfo info) {
3413        synchronized (mPackages) {
3414            return addPermissionLocked(info, false);
3415        }
3416    }
3417
3418    @Override
3419    public boolean addPermissionAsync(PermissionInfo info) {
3420        synchronized (mPackages) {
3421            return addPermissionLocked(info, true);
3422        }
3423    }
3424
3425    @Override
3426    public void removePermission(String name) {
3427        synchronized (mPackages) {
3428            checkPermissionTreeLP(name);
3429            BasePermission bp = mSettings.mPermissions.get(name);
3430            if (bp != null) {
3431                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3432                    throw new SecurityException(
3433                            "Not allowed to modify non-dynamic permission "
3434                            + name);
3435                }
3436                mSettings.mPermissions.remove(name);
3437                mSettings.writeLPr();
3438            }
3439        }
3440    }
3441
3442    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3443            BasePermission bp) {
3444        int index = pkg.requestedPermissions.indexOf(bp.name);
3445        if (index == -1) {
3446            throw new SecurityException("Package " + pkg.packageName
3447                    + " has not requested permission " + bp.name);
3448        }
3449        if (!bp.isRuntime() && !bp.isDevelopment()) {
3450            throw new SecurityException("Permission " + bp.name
3451                    + " is not a changeable permission type");
3452        }
3453    }
3454
3455    @Override
3456    public void grantRuntimePermission(String packageName, String name, final int userId) {
3457        if (!sUserManager.exists(userId)) {
3458            Log.e(TAG, "No such user:" + userId);
3459            return;
3460        }
3461
3462        mContext.enforceCallingOrSelfPermission(
3463                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3464                "grantRuntimePermission");
3465
3466        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3467                "grantRuntimePermission");
3468
3469        final int uid;
3470        final SettingBase sb;
3471
3472        synchronized (mPackages) {
3473            final PackageParser.Package pkg = mPackages.get(packageName);
3474            if (pkg == null) {
3475                throw new IllegalArgumentException("Unknown package: " + packageName);
3476            }
3477
3478            final BasePermission bp = mSettings.mPermissions.get(name);
3479            if (bp == null) {
3480                throw new IllegalArgumentException("Unknown permission: " + name);
3481            }
3482
3483            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3484
3485            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3486            sb = (SettingBase) pkg.mExtras;
3487            if (sb == null) {
3488                throw new IllegalArgumentException("Unknown package: " + packageName);
3489            }
3490
3491            final PermissionsState permissionsState = sb.getPermissionsState();
3492
3493            final int flags = permissionsState.getPermissionFlags(name, userId);
3494            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3495                throw new SecurityException("Cannot grant system fixed permission: "
3496                        + name + " for package: " + packageName);
3497            }
3498
3499            if (bp.isDevelopment()) {
3500                // Development permissions must be handled specially, since they are not
3501                // normal runtime permissions.  For now they apply to all users.
3502                if (permissionsState.grantInstallPermission(bp) !=
3503                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3504                    scheduleWriteSettingsLocked();
3505                }
3506                return;
3507            }
3508
3509            final int result = permissionsState.grantRuntimePermission(bp, userId);
3510            switch (result) {
3511                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3512                    return;
3513                }
3514
3515                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3516                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3517                    mHandler.post(new Runnable() {
3518                        @Override
3519                        public void run() {
3520                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3521                        }
3522                    });
3523                }
3524                break;
3525            }
3526
3527            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3528
3529            // Not critical if that is lost - app has to request again.
3530            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3531        }
3532
3533        // Only need to do this if user is initialized. Otherwise it's a new user
3534        // and there are no processes running as the user yet and there's no need
3535        // to make an expensive call to remount processes for the changed permissions.
3536        if (READ_EXTERNAL_STORAGE.equals(name)
3537                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3538            final long token = Binder.clearCallingIdentity();
3539            try {
3540                if (sUserManager.isInitialized(userId)) {
3541                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3542                            MountServiceInternal.class);
3543                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3544                }
3545            } finally {
3546                Binder.restoreCallingIdentity(token);
3547            }
3548        }
3549    }
3550
3551    @Override
3552    public void revokeRuntimePermission(String packageName, String name, int userId) {
3553        if (!sUserManager.exists(userId)) {
3554            Log.e(TAG, "No such user:" + userId);
3555            return;
3556        }
3557
3558        mContext.enforceCallingOrSelfPermission(
3559                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3560                "revokeRuntimePermission");
3561
3562        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3563                "revokeRuntimePermission");
3564
3565        final int appId;
3566
3567        synchronized (mPackages) {
3568            final PackageParser.Package pkg = mPackages.get(packageName);
3569            if (pkg == null) {
3570                throw new IllegalArgumentException("Unknown package: " + packageName);
3571            }
3572
3573            final BasePermission bp = mSettings.mPermissions.get(name);
3574            if (bp == null) {
3575                throw new IllegalArgumentException("Unknown permission: " + name);
3576            }
3577
3578            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3579
3580            SettingBase sb = (SettingBase) pkg.mExtras;
3581            if (sb == null) {
3582                throw new IllegalArgumentException("Unknown package: " + packageName);
3583            }
3584
3585            final PermissionsState permissionsState = sb.getPermissionsState();
3586
3587            final int flags = permissionsState.getPermissionFlags(name, userId);
3588            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3589                throw new SecurityException("Cannot revoke system fixed permission: "
3590                        + name + " for package: " + packageName);
3591            }
3592
3593            if (bp.isDevelopment()) {
3594                // Development permissions must be handled specially, since they are not
3595                // normal runtime permissions.  For now they apply to all users.
3596                if (permissionsState.revokeInstallPermission(bp) !=
3597                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3598                    scheduleWriteSettingsLocked();
3599                }
3600                return;
3601            }
3602
3603            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3604                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3605                return;
3606            }
3607
3608            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3609
3610            // Critical, after this call app should never have the permission.
3611            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3612
3613            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3614        }
3615
3616        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3617    }
3618
3619    @Override
3620    public void resetRuntimePermissions() {
3621        mContext.enforceCallingOrSelfPermission(
3622                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3623                "revokeRuntimePermission");
3624
3625        int callingUid = Binder.getCallingUid();
3626        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3627            mContext.enforceCallingOrSelfPermission(
3628                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3629                    "resetRuntimePermissions");
3630        }
3631
3632        synchronized (mPackages) {
3633            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3634            for (int userId : UserManagerService.getInstance().getUserIds()) {
3635                final int packageCount = mPackages.size();
3636                for (int i = 0; i < packageCount; i++) {
3637                    PackageParser.Package pkg = mPackages.valueAt(i);
3638                    if (!(pkg.mExtras instanceof PackageSetting)) {
3639                        continue;
3640                    }
3641                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3642                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3643                }
3644            }
3645        }
3646    }
3647
3648    @Override
3649    public int getPermissionFlags(String name, String packageName, int userId) {
3650        if (!sUserManager.exists(userId)) {
3651            return 0;
3652        }
3653
3654        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3655
3656        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3657                "getPermissionFlags");
3658
3659        synchronized (mPackages) {
3660            final PackageParser.Package pkg = mPackages.get(packageName);
3661            if (pkg == null) {
3662                throw new IllegalArgumentException("Unknown package: " + packageName);
3663            }
3664
3665            final BasePermission bp = mSettings.mPermissions.get(name);
3666            if (bp == null) {
3667                throw new IllegalArgumentException("Unknown permission: " + name);
3668            }
3669
3670            SettingBase sb = (SettingBase) pkg.mExtras;
3671            if (sb == null) {
3672                throw new IllegalArgumentException("Unknown package: " + packageName);
3673            }
3674
3675            PermissionsState permissionsState = sb.getPermissionsState();
3676            return permissionsState.getPermissionFlags(name, userId);
3677        }
3678    }
3679
3680    @Override
3681    public void updatePermissionFlags(String name, String packageName, int flagMask,
3682            int flagValues, int userId) {
3683        if (!sUserManager.exists(userId)) {
3684            return;
3685        }
3686
3687        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3688
3689        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3690                "updatePermissionFlags");
3691
3692        // Only the system can change these flags and nothing else.
3693        if (getCallingUid() != Process.SYSTEM_UID) {
3694            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3695            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3696            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3697            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3698        }
3699
3700        synchronized (mPackages) {
3701            final PackageParser.Package pkg = mPackages.get(packageName);
3702            if (pkg == null) {
3703                throw new IllegalArgumentException("Unknown package: " + packageName);
3704            }
3705
3706            final BasePermission bp = mSettings.mPermissions.get(name);
3707            if (bp == null) {
3708                throw new IllegalArgumentException("Unknown permission: " + name);
3709            }
3710
3711            SettingBase sb = (SettingBase) pkg.mExtras;
3712            if (sb == null) {
3713                throw new IllegalArgumentException("Unknown package: " + packageName);
3714            }
3715
3716            PermissionsState permissionsState = sb.getPermissionsState();
3717
3718            // Only the package manager can change flags for system component permissions.
3719            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3720            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3721                return;
3722            }
3723
3724            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3725
3726            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3727                // Install and runtime permissions are stored in different places,
3728                // so figure out what permission changed and persist the change.
3729                if (permissionsState.getInstallPermissionState(name) != null) {
3730                    scheduleWriteSettingsLocked();
3731                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3732                        || hadState) {
3733                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3734                }
3735            }
3736        }
3737    }
3738
3739    /**
3740     * Update the permission flags for all packages and runtime permissions of a user in order
3741     * to allow device or profile owner to remove POLICY_FIXED.
3742     */
3743    @Override
3744    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3745        if (!sUserManager.exists(userId)) {
3746            return;
3747        }
3748
3749        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3750
3751        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3752                "updatePermissionFlagsForAllApps");
3753
3754        // Only the system can change system fixed flags.
3755        if (getCallingUid() != Process.SYSTEM_UID) {
3756            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3757            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3758        }
3759
3760        synchronized (mPackages) {
3761            boolean changed = false;
3762            final int packageCount = mPackages.size();
3763            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3764                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3765                SettingBase sb = (SettingBase) pkg.mExtras;
3766                if (sb == null) {
3767                    continue;
3768                }
3769                PermissionsState permissionsState = sb.getPermissionsState();
3770                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3771                        userId, flagMask, flagValues);
3772            }
3773            if (changed) {
3774                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3775            }
3776        }
3777    }
3778
3779    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3780        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3781                != PackageManager.PERMISSION_GRANTED
3782            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3783                != PackageManager.PERMISSION_GRANTED) {
3784            throw new SecurityException(message + " requires "
3785                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3786                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3787        }
3788    }
3789
3790    @Override
3791    public boolean shouldShowRequestPermissionRationale(String permissionName,
3792            String packageName, int userId) {
3793        if (UserHandle.getCallingUserId() != userId) {
3794            mContext.enforceCallingPermission(
3795                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3796                    "canShowRequestPermissionRationale for user " + userId);
3797        }
3798
3799        final int uid = getPackageUid(packageName, userId);
3800        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3801            return false;
3802        }
3803
3804        if (checkPermission(permissionName, packageName, userId)
3805                == PackageManager.PERMISSION_GRANTED) {
3806            return false;
3807        }
3808
3809        final int flags;
3810
3811        final long identity = Binder.clearCallingIdentity();
3812        try {
3813            flags = getPermissionFlags(permissionName,
3814                    packageName, userId);
3815        } finally {
3816            Binder.restoreCallingIdentity(identity);
3817        }
3818
3819        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3820                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3821                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3822
3823        if ((flags & fixedFlags) != 0) {
3824            return false;
3825        }
3826
3827        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3828    }
3829
3830    @Override
3831    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3832        mContext.enforceCallingOrSelfPermission(
3833                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3834                "addOnPermissionsChangeListener");
3835
3836        synchronized (mPackages) {
3837            mOnPermissionChangeListeners.addListenerLocked(listener);
3838        }
3839    }
3840
3841    @Override
3842    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3843        synchronized (mPackages) {
3844            mOnPermissionChangeListeners.removeListenerLocked(listener);
3845        }
3846    }
3847
3848    @Override
3849    public boolean isProtectedBroadcast(String actionName) {
3850        synchronized (mPackages) {
3851            return mProtectedBroadcasts.contains(actionName);
3852        }
3853    }
3854
3855    @Override
3856    public int checkSignatures(String pkg1, String pkg2) {
3857        synchronized (mPackages) {
3858            final PackageParser.Package p1 = mPackages.get(pkg1);
3859            final PackageParser.Package p2 = mPackages.get(pkg2);
3860            if (p1 == null || p1.mExtras == null
3861                    || p2 == null || p2.mExtras == null) {
3862                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3863            }
3864            return compareSignatures(p1.mSignatures, p2.mSignatures);
3865        }
3866    }
3867
3868    @Override
3869    public int checkUidSignatures(int uid1, int uid2) {
3870        // Map to base uids.
3871        uid1 = UserHandle.getAppId(uid1);
3872        uid2 = UserHandle.getAppId(uid2);
3873        // reader
3874        synchronized (mPackages) {
3875            Signature[] s1;
3876            Signature[] s2;
3877            Object obj = mSettings.getUserIdLPr(uid1);
3878            if (obj != null) {
3879                if (obj instanceof SharedUserSetting) {
3880                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3881                } else if (obj instanceof PackageSetting) {
3882                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3883                } else {
3884                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3885                }
3886            } else {
3887                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3888            }
3889            obj = mSettings.getUserIdLPr(uid2);
3890            if (obj != null) {
3891                if (obj instanceof SharedUserSetting) {
3892                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3893                } else if (obj instanceof PackageSetting) {
3894                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3895                } else {
3896                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3897                }
3898            } else {
3899                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3900            }
3901            return compareSignatures(s1, s2);
3902        }
3903    }
3904
3905    private void killUid(int appId, int userId, String reason) {
3906        final long identity = Binder.clearCallingIdentity();
3907        try {
3908            IActivityManager am = ActivityManagerNative.getDefault();
3909            if (am != null) {
3910                try {
3911                    am.killUid(appId, userId, reason);
3912                } catch (RemoteException e) {
3913                    /* ignore - same process */
3914                }
3915            }
3916        } finally {
3917            Binder.restoreCallingIdentity(identity);
3918        }
3919    }
3920
3921    /**
3922     * Compares two sets of signatures. Returns:
3923     * <br />
3924     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3925     * <br />
3926     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3927     * <br />
3928     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3929     * <br />
3930     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3931     * <br />
3932     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3933     */
3934    static int compareSignatures(Signature[] s1, Signature[] s2) {
3935        if (s1 == null) {
3936            return s2 == null
3937                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3938                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3939        }
3940
3941        if (s2 == null) {
3942            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3943        }
3944
3945        if (s1.length != s2.length) {
3946            return PackageManager.SIGNATURE_NO_MATCH;
3947        }
3948
3949        // Since both signature sets are of size 1, we can compare without HashSets.
3950        if (s1.length == 1) {
3951            return s1[0].equals(s2[0]) ?
3952                    PackageManager.SIGNATURE_MATCH :
3953                    PackageManager.SIGNATURE_NO_MATCH;
3954        }
3955
3956        ArraySet<Signature> set1 = new ArraySet<Signature>();
3957        for (Signature sig : s1) {
3958            set1.add(sig);
3959        }
3960        ArraySet<Signature> set2 = new ArraySet<Signature>();
3961        for (Signature sig : s2) {
3962            set2.add(sig);
3963        }
3964        // Make sure s2 contains all signatures in s1.
3965        if (set1.equals(set2)) {
3966            return PackageManager.SIGNATURE_MATCH;
3967        }
3968        return PackageManager.SIGNATURE_NO_MATCH;
3969    }
3970
3971    /**
3972     * If the database version for this type of package (internal storage or
3973     * external storage) is less than the version where package signatures
3974     * were updated, return true.
3975     */
3976    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3977        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3978        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3979    }
3980
3981    /**
3982     * Used for backward compatibility to make sure any packages with
3983     * certificate chains get upgraded to the new style. {@code existingSigs}
3984     * will be in the old format (since they were stored on disk from before the
3985     * system upgrade) and {@code scannedSigs} will be in the newer format.
3986     */
3987    private int compareSignaturesCompat(PackageSignatures existingSigs,
3988            PackageParser.Package scannedPkg) {
3989        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3990            return PackageManager.SIGNATURE_NO_MATCH;
3991        }
3992
3993        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3994        for (Signature sig : existingSigs.mSignatures) {
3995            existingSet.add(sig);
3996        }
3997        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3998        for (Signature sig : scannedPkg.mSignatures) {
3999            try {
4000                Signature[] chainSignatures = sig.getChainSignatures();
4001                for (Signature chainSig : chainSignatures) {
4002                    scannedCompatSet.add(chainSig);
4003                }
4004            } catch (CertificateEncodingException e) {
4005                scannedCompatSet.add(sig);
4006            }
4007        }
4008        /*
4009         * Make sure the expanded scanned set contains all signatures in the
4010         * existing one.
4011         */
4012        if (scannedCompatSet.equals(existingSet)) {
4013            // Migrate the old signatures to the new scheme.
4014            existingSigs.assignSignatures(scannedPkg.mSignatures);
4015            // The new KeySets will be re-added later in the scanning process.
4016            synchronized (mPackages) {
4017                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4018            }
4019            return PackageManager.SIGNATURE_MATCH;
4020        }
4021        return PackageManager.SIGNATURE_NO_MATCH;
4022    }
4023
4024    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4025        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4026        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4027    }
4028
4029    private int compareSignaturesRecover(PackageSignatures existingSigs,
4030            PackageParser.Package scannedPkg) {
4031        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4032            return PackageManager.SIGNATURE_NO_MATCH;
4033        }
4034
4035        String msg = null;
4036        try {
4037            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4038                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4039                        + scannedPkg.packageName);
4040                return PackageManager.SIGNATURE_MATCH;
4041            }
4042        } catch (CertificateException e) {
4043            msg = e.getMessage();
4044        }
4045
4046        logCriticalInfo(Log.INFO,
4047                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4048        return PackageManager.SIGNATURE_NO_MATCH;
4049    }
4050
4051    @Override
4052    public String[] getPackagesForUid(int uid) {
4053        uid = UserHandle.getAppId(uid);
4054        // reader
4055        synchronized (mPackages) {
4056            Object obj = mSettings.getUserIdLPr(uid);
4057            if (obj instanceof SharedUserSetting) {
4058                final SharedUserSetting sus = (SharedUserSetting) obj;
4059                final int N = sus.packages.size();
4060                final String[] res = new String[N];
4061                final Iterator<PackageSetting> it = sus.packages.iterator();
4062                int i = 0;
4063                while (it.hasNext()) {
4064                    res[i++] = it.next().name;
4065                }
4066                return res;
4067            } else if (obj instanceof PackageSetting) {
4068                final PackageSetting ps = (PackageSetting) obj;
4069                return new String[] { ps.name };
4070            }
4071        }
4072        return null;
4073    }
4074
4075    @Override
4076    public String getNameForUid(int uid) {
4077        // reader
4078        synchronized (mPackages) {
4079            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4080            if (obj instanceof SharedUserSetting) {
4081                final SharedUserSetting sus = (SharedUserSetting) obj;
4082                return sus.name + ":" + sus.userId;
4083            } else if (obj instanceof PackageSetting) {
4084                final PackageSetting ps = (PackageSetting) obj;
4085                return ps.name;
4086            }
4087        }
4088        return null;
4089    }
4090
4091    @Override
4092    public int getUidForSharedUser(String sharedUserName) {
4093        if(sharedUserName == null) {
4094            return -1;
4095        }
4096        // reader
4097        synchronized (mPackages) {
4098            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4099            if (suid == null) {
4100                return -1;
4101            }
4102            return suid.userId;
4103        }
4104    }
4105
4106    @Override
4107    public int getFlagsForUid(int uid) {
4108        synchronized (mPackages) {
4109            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4110            if (obj instanceof SharedUserSetting) {
4111                final SharedUserSetting sus = (SharedUserSetting) obj;
4112                return sus.pkgFlags;
4113            } else if (obj instanceof PackageSetting) {
4114                final PackageSetting ps = (PackageSetting) obj;
4115                return ps.pkgFlags;
4116            }
4117        }
4118        return 0;
4119    }
4120
4121    @Override
4122    public int getPrivateFlagsForUid(int uid) {
4123        synchronized (mPackages) {
4124            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4125            if (obj instanceof SharedUserSetting) {
4126                final SharedUserSetting sus = (SharedUserSetting) obj;
4127                return sus.pkgPrivateFlags;
4128            } else if (obj instanceof PackageSetting) {
4129                final PackageSetting ps = (PackageSetting) obj;
4130                return ps.pkgPrivateFlags;
4131            }
4132        }
4133        return 0;
4134    }
4135
4136    @Override
4137    public boolean isUidPrivileged(int uid) {
4138        uid = UserHandle.getAppId(uid);
4139        // reader
4140        synchronized (mPackages) {
4141            Object obj = mSettings.getUserIdLPr(uid);
4142            if (obj instanceof SharedUserSetting) {
4143                final SharedUserSetting sus = (SharedUserSetting) obj;
4144                final Iterator<PackageSetting> it = sus.packages.iterator();
4145                while (it.hasNext()) {
4146                    if (it.next().isPrivileged()) {
4147                        return true;
4148                    }
4149                }
4150            } else if (obj instanceof PackageSetting) {
4151                final PackageSetting ps = (PackageSetting) obj;
4152                return ps.isPrivileged();
4153            }
4154        }
4155        return false;
4156    }
4157
4158    @Override
4159    public String[] getAppOpPermissionPackages(String permissionName) {
4160        synchronized (mPackages) {
4161            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4162            if (pkgs == null) {
4163                return null;
4164            }
4165            return pkgs.toArray(new String[pkgs.size()]);
4166        }
4167    }
4168
4169    @Override
4170    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4171            int flags, int userId) {
4172        if (!sUserManager.exists(userId)) return null;
4173        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4174        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4175        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4176    }
4177
4178    @Override
4179    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4180            IntentFilter filter, int match, ComponentName activity) {
4181        final int userId = UserHandle.getCallingUserId();
4182        if (DEBUG_PREFERRED) {
4183            Log.v(TAG, "setLastChosenActivity intent=" + intent
4184                + " resolvedType=" + resolvedType
4185                + " flags=" + flags
4186                + " filter=" + filter
4187                + " match=" + match
4188                + " activity=" + activity);
4189            filter.dump(new PrintStreamPrinter(System.out), "    ");
4190        }
4191        intent.setComponent(null);
4192        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4193        // Find any earlier preferred or last chosen entries and nuke them
4194        findPreferredActivity(intent, resolvedType,
4195                flags, query, 0, false, true, false, userId);
4196        // Add the new activity as the last chosen for this filter
4197        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4198                "Setting last chosen");
4199    }
4200
4201    @Override
4202    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4203        final int userId = UserHandle.getCallingUserId();
4204        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4205        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4206        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4207                false, false, false, userId);
4208    }
4209
4210    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4211            int flags, List<ResolveInfo> query, int userId) {
4212        if (query != null) {
4213            final int N = query.size();
4214            if (N == 1) {
4215                return query.get(0);
4216            } else if (N > 1) {
4217                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4218                // If there is more than one activity with the same priority,
4219                // then let the user decide between them.
4220                ResolveInfo r0 = query.get(0);
4221                ResolveInfo r1 = query.get(1);
4222                if (DEBUG_INTENT_MATCHING || debug) {
4223                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4224                            + r1.activityInfo.name + "=" + r1.priority);
4225                }
4226                // If the first activity has a higher priority, or a different
4227                // default, then it is always desireable to pick it.
4228                if (r0.priority != r1.priority
4229                        || r0.preferredOrder != r1.preferredOrder
4230                        || r0.isDefault != r1.isDefault) {
4231                    return query.get(0);
4232                }
4233                // If we have saved a preference for a preferred activity for
4234                // this Intent, use that.
4235                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4236                        flags, query, r0.priority, true, false, debug, userId);
4237                if (ri != null) {
4238                    return ri;
4239                }
4240                ri = new ResolveInfo(mResolveInfo);
4241                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4242                ri.activityInfo.applicationInfo = new ApplicationInfo(
4243                        ri.activityInfo.applicationInfo);
4244                if (userId != 0) {
4245                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4246                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4247                }
4248                // Make sure that the resolver is displayable in car mode
4249                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4250                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4251                return ri;
4252            }
4253        }
4254        return null;
4255    }
4256
4257    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4258            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4259        final int N = query.size();
4260        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4261                .get(userId);
4262        // Get the list of persistent preferred activities that handle the intent
4263        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4264        List<PersistentPreferredActivity> pprefs = ppir != null
4265                ? ppir.queryIntent(intent, resolvedType,
4266                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4267                : null;
4268        if (pprefs != null && pprefs.size() > 0) {
4269            final int M = pprefs.size();
4270            for (int i=0; i<M; i++) {
4271                final PersistentPreferredActivity ppa = pprefs.get(i);
4272                if (DEBUG_PREFERRED || debug) {
4273                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4274                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4275                            + "\n  component=" + ppa.mComponent);
4276                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4277                }
4278                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4279                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4280                if (DEBUG_PREFERRED || debug) {
4281                    Slog.v(TAG, "Found persistent preferred activity:");
4282                    if (ai != null) {
4283                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4284                    } else {
4285                        Slog.v(TAG, "  null");
4286                    }
4287                }
4288                if (ai == null) {
4289                    // This previously registered persistent preferred activity
4290                    // component is no longer known. Ignore it and do NOT remove it.
4291                    continue;
4292                }
4293                for (int j=0; j<N; j++) {
4294                    final ResolveInfo ri = query.get(j);
4295                    if (!ri.activityInfo.applicationInfo.packageName
4296                            .equals(ai.applicationInfo.packageName)) {
4297                        continue;
4298                    }
4299                    if (!ri.activityInfo.name.equals(ai.name)) {
4300                        continue;
4301                    }
4302                    //  Found a persistent preference that can handle the intent.
4303                    if (DEBUG_PREFERRED || debug) {
4304                        Slog.v(TAG, "Returning persistent preferred activity: " +
4305                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4306                    }
4307                    return ri;
4308                }
4309            }
4310        }
4311        return null;
4312    }
4313
4314    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4315            List<ResolveInfo> query, int priority, boolean always,
4316            boolean removeMatches, boolean debug, int userId) {
4317        if (!sUserManager.exists(userId)) return null;
4318        // writer
4319        synchronized (mPackages) {
4320            if (intent.getSelector() != null) {
4321                intent = intent.getSelector();
4322            }
4323            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4324
4325            // Try to find a matching persistent preferred activity.
4326            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4327                    debug, userId);
4328
4329            // If a persistent preferred activity matched, use it.
4330            if (pri != null) {
4331                return pri;
4332            }
4333
4334            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4335            // Get the list of preferred activities that handle the intent
4336            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4337            List<PreferredActivity> prefs = pir != null
4338                    ? pir.queryIntent(intent, resolvedType,
4339                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4340                    : null;
4341            if (prefs != null && prefs.size() > 0) {
4342                boolean changed = false;
4343                try {
4344                    // First figure out how good the original match set is.
4345                    // We will only allow preferred activities that came
4346                    // from the same match quality.
4347                    int match = 0;
4348
4349                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4350
4351                    final int N = query.size();
4352                    for (int j=0; j<N; j++) {
4353                        final ResolveInfo ri = query.get(j);
4354                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4355                                + ": 0x" + Integer.toHexString(match));
4356                        if (ri.match > match) {
4357                            match = ri.match;
4358                        }
4359                    }
4360
4361                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4362                            + Integer.toHexString(match));
4363
4364                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4365                    final int M = prefs.size();
4366                    for (int i=0; i<M; i++) {
4367                        final PreferredActivity pa = prefs.get(i);
4368                        if (DEBUG_PREFERRED || debug) {
4369                            Slog.v(TAG, "Checking PreferredActivity ds="
4370                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4371                                    + "\n  component=" + pa.mPref.mComponent);
4372                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4373                        }
4374                        if (pa.mPref.mMatch != match) {
4375                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4376                                    + Integer.toHexString(pa.mPref.mMatch));
4377                            continue;
4378                        }
4379                        // If it's not an "always" type preferred activity and that's what we're
4380                        // looking for, skip it.
4381                        if (always && !pa.mPref.mAlways) {
4382                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4383                            continue;
4384                        }
4385                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4386                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4387                        if (DEBUG_PREFERRED || debug) {
4388                            Slog.v(TAG, "Found preferred activity:");
4389                            if (ai != null) {
4390                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4391                            } else {
4392                                Slog.v(TAG, "  null");
4393                            }
4394                        }
4395                        if (ai == null) {
4396                            // This previously registered preferred activity
4397                            // component is no longer known.  Most likely an update
4398                            // to the app was installed and in the new version this
4399                            // component no longer exists.  Clean it up by removing
4400                            // it from the preferred activities list, and skip it.
4401                            Slog.w(TAG, "Removing dangling preferred activity: "
4402                                    + pa.mPref.mComponent);
4403                            pir.removeFilter(pa);
4404                            changed = true;
4405                            continue;
4406                        }
4407                        for (int j=0; j<N; j++) {
4408                            final ResolveInfo ri = query.get(j);
4409                            if (!ri.activityInfo.applicationInfo.packageName
4410                                    .equals(ai.applicationInfo.packageName)) {
4411                                continue;
4412                            }
4413                            if (!ri.activityInfo.name.equals(ai.name)) {
4414                                continue;
4415                            }
4416
4417                            if (removeMatches) {
4418                                pir.removeFilter(pa);
4419                                changed = true;
4420                                if (DEBUG_PREFERRED) {
4421                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4422                                }
4423                                break;
4424                            }
4425
4426                            // Okay we found a previously set preferred or last chosen app.
4427                            // If the result set is different from when this
4428                            // was created, we need to clear it and re-ask the
4429                            // user their preference, if we're looking for an "always" type entry.
4430                            if (always && !pa.mPref.sameSet(query)) {
4431                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4432                                        + intent + " type " + resolvedType);
4433                                if (DEBUG_PREFERRED) {
4434                                    Slog.v(TAG, "Removing preferred activity since set changed "
4435                                            + pa.mPref.mComponent);
4436                                }
4437                                pir.removeFilter(pa);
4438                                // Re-add the filter as a "last chosen" entry (!always)
4439                                PreferredActivity lastChosen = new PreferredActivity(
4440                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4441                                pir.addFilter(lastChosen);
4442                                changed = true;
4443                                return null;
4444                            }
4445
4446                            // Yay! Either the set matched or we're looking for the last chosen
4447                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4448                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4449                            return ri;
4450                        }
4451                    }
4452                } finally {
4453                    if (changed) {
4454                        if (DEBUG_PREFERRED) {
4455                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4456                        }
4457                        scheduleWritePackageRestrictionsLocked(userId);
4458                    }
4459                }
4460            }
4461        }
4462        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4463        return null;
4464    }
4465
4466    /*
4467     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4468     */
4469    @Override
4470    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4471            int targetUserId) {
4472        mContext.enforceCallingOrSelfPermission(
4473                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4474        List<CrossProfileIntentFilter> matches =
4475                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4476        if (matches != null) {
4477            int size = matches.size();
4478            for (int i = 0; i < size; i++) {
4479                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4480            }
4481        }
4482        if (hasWebURI(intent)) {
4483            // cross-profile app linking works only towards the parent.
4484            final UserInfo parent = getProfileParent(sourceUserId);
4485            synchronized(mPackages) {
4486                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4487                        intent, resolvedType, 0, sourceUserId, parent.id);
4488                return xpDomainInfo != null;
4489            }
4490        }
4491        return false;
4492    }
4493
4494    private UserInfo getProfileParent(int userId) {
4495        final long identity = Binder.clearCallingIdentity();
4496        try {
4497            return sUserManager.getProfileParent(userId);
4498        } finally {
4499            Binder.restoreCallingIdentity(identity);
4500        }
4501    }
4502
4503    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4504            String resolvedType, int userId) {
4505        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4506        if (resolver != null) {
4507            return resolver.queryIntent(intent, resolvedType, false, userId);
4508        }
4509        return null;
4510    }
4511
4512    @Override
4513    public List<ResolveInfo> queryIntentActivities(Intent intent,
4514            String resolvedType, int flags, int userId) {
4515        if (!sUserManager.exists(userId)) return Collections.emptyList();
4516        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4517        ComponentName comp = intent.getComponent();
4518        if (comp == null) {
4519            if (intent.getSelector() != null) {
4520                intent = intent.getSelector();
4521                comp = intent.getComponent();
4522            }
4523        }
4524
4525        if (comp != null) {
4526            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4527            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4528            if (ai != null) {
4529                final ResolveInfo ri = new ResolveInfo();
4530                ri.activityInfo = ai;
4531                list.add(ri);
4532            }
4533            return list;
4534        }
4535
4536        // reader
4537        synchronized (mPackages) {
4538            final String pkgName = intent.getPackage();
4539            if (pkgName == null) {
4540                List<CrossProfileIntentFilter> matchingFilters =
4541                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4542                // Check for results that need to skip the current profile.
4543                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4544                        resolvedType, flags, userId);
4545                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4546                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4547                    result.add(xpResolveInfo);
4548                    return filterIfNotPrimaryUser(result, userId);
4549                }
4550
4551                // Check for results in the current profile.
4552                List<ResolveInfo> result = mActivities.queryIntent(
4553                        intent, resolvedType, flags, userId);
4554
4555                // Check for cross profile results.
4556                xpResolveInfo = queryCrossProfileIntents(
4557                        matchingFilters, intent, resolvedType, flags, userId);
4558                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4559                    result.add(xpResolveInfo);
4560                    Collections.sort(result, mResolvePrioritySorter);
4561                }
4562                result = filterIfNotPrimaryUser(result, userId);
4563                if (hasWebURI(intent)) {
4564                    CrossProfileDomainInfo xpDomainInfo = null;
4565                    final UserInfo parent = getProfileParent(userId);
4566                    if (parent != null) {
4567                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4568                                flags, userId, parent.id);
4569                    }
4570                    if (xpDomainInfo != null) {
4571                        if (xpResolveInfo != null) {
4572                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4573                            // in the result.
4574                            result.remove(xpResolveInfo);
4575                        }
4576                        if (result.size() == 0) {
4577                            result.add(xpDomainInfo.resolveInfo);
4578                            return result;
4579                        }
4580                    } else if (result.size() <= 1) {
4581                        return result;
4582                    }
4583                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4584                            xpDomainInfo, userId);
4585                    Collections.sort(result, mResolvePrioritySorter);
4586                }
4587                return result;
4588            }
4589            final PackageParser.Package pkg = mPackages.get(pkgName);
4590            if (pkg != null) {
4591                return filterIfNotPrimaryUser(
4592                        mActivities.queryIntentForPackage(
4593                                intent, resolvedType, flags, pkg.activities, userId),
4594                        userId);
4595            }
4596            return new ArrayList<ResolveInfo>();
4597        }
4598    }
4599
4600    private static class CrossProfileDomainInfo {
4601        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4602        ResolveInfo resolveInfo;
4603        /* Best domain verification status of the activities found in the other profile */
4604        int bestDomainVerificationStatus;
4605    }
4606
4607    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4608            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4609        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4610                sourceUserId)) {
4611            return null;
4612        }
4613        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4614                resolvedType, flags, parentUserId);
4615
4616        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4617            return null;
4618        }
4619        CrossProfileDomainInfo result = null;
4620        int size = resultTargetUser.size();
4621        for (int i = 0; i < size; i++) {
4622            ResolveInfo riTargetUser = resultTargetUser.get(i);
4623            // Intent filter verification is only for filters that specify a host. So don't return
4624            // those that handle all web uris.
4625            if (riTargetUser.handleAllWebDataURI) {
4626                continue;
4627            }
4628            String packageName = riTargetUser.activityInfo.packageName;
4629            PackageSetting ps = mSettings.mPackages.get(packageName);
4630            if (ps == null) {
4631                continue;
4632            }
4633            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4634            int status = (int)(verificationState >> 32);
4635            if (result == null) {
4636                result = new CrossProfileDomainInfo();
4637                result.resolveInfo =
4638                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4639                result.bestDomainVerificationStatus = status;
4640            } else {
4641                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4642                        result.bestDomainVerificationStatus);
4643            }
4644        }
4645        // Don't consider matches with status NEVER across profiles.
4646        if (result != null && result.bestDomainVerificationStatus
4647                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4648            return null;
4649        }
4650        return result;
4651    }
4652
4653    /**
4654     * Verification statuses are ordered from the worse to the best, except for
4655     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4656     */
4657    private int bestDomainVerificationStatus(int status1, int status2) {
4658        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4659            return status2;
4660        }
4661        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4662            return status1;
4663        }
4664        return (int) MathUtils.max(status1, status2);
4665    }
4666
4667    private boolean isUserEnabled(int userId) {
4668        long callingId = Binder.clearCallingIdentity();
4669        try {
4670            UserInfo userInfo = sUserManager.getUserInfo(userId);
4671            return userInfo != null && userInfo.isEnabled();
4672        } finally {
4673            Binder.restoreCallingIdentity(callingId);
4674        }
4675    }
4676
4677    /**
4678     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4679     *
4680     * @return filtered list
4681     */
4682    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4683        if (userId == UserHandle.USER_OWNER) {
4684            return resolveInfos;
4685        }
4686        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4687            ResolveInfo info = resolveInfos.get(i);
4688            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4689                resolveInfos.remove(i);
4690            }
4691        }
4692        return resolveInfos;
4693    }
4694
4695    private static boolean hasWebURI(Intent intent) {
4696        if (intent.getData() == null) {
4697            return false;
4698        }
4699        final String scheme = intent.getScheme();
4700        if (TextUtils.isEmpty(scheme)) {
4701            return false;
4702        }
4703        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4704    }
4705
4706    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4707            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4708            int userId) {
4709        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4710
4711        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4712            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4713                    candidates.size());
4714        }
4715
4716        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4717        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4718        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4719        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4720        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4721        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4722
4723        synchronized (mPackages) {
4724            final int count = candidates.size();
4725            // First, try to use linked apps. Partition the candidates into four lists:
4726            // one for the final results, one for the "do not use ever", one for "undefined status"
4727            // and finally one for "browser app type".
4728            for (int n=0; n<count; n++) {
4729                ResolveInfo info = candidates.get(n);
4730                String packageName = info.activityInfo.packageName;
4731                PackageSetting ps = mSettings.mPackages.get(packageName);
4732                if (ps != null) {
4733                    // Add to the special match all list (Browser use case)
4734                    if (info.handleAllWebDataURI) {
4735                        matchAllList.add(info);
4736                        continue;
4737                    }
4738                    // Try to get the status from User settings first
4739                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4740                    int status = (int)(packedStatus >> 32);
4741                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4742                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4743                        if (DEBUG_DOMAIN_VERIFICATION) {
4744                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4745                                    + " : linkgen=" + linkGeneration);
4746                        }
4747                        // Use link-enabled generation as preferredOrder, i.e.
4748                        // prefer newly-enabled over earlier-enabled.
4749                        info.preferredOrder = linkGeneration;
4750                        alwaysList.add(info);
4751                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4752                        if (DEBUG_DOMAIN_VERIFICATION) {
4753                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4754                        }
4755                        neverList.add(info);
4756                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4757                        if (DEBUG_DOMAIN_VERIFICATION) {
4758                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4759                        }
4760                        alwaysAskList.add(info);
4761                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4762                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4763                        if (DEBUG_DOMAIN_VERIFICATION) {
4764                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4765                        }
4766                        undefinedList.add(info);
4767                    }
4768                }
4769            }
4770
4771            // We'll want to include browser possibilities in a few cases
4772            boolean includeBrowser = false;
4773
4774            // First try to add the "always" resolution(s) for the current user, if any
4775            if (alwaysList.size() > 0) {
4776                result.addAll(alwaysList);
4777            } else {
4778                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4779                result.addAll(undefinedList);
4780                // Maybe add one for the other profile.
4781                if (xpDomainInfo != null && (
4782                        xpDomainInfo.bestDomainVerificationStatus
4783                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
4784                    result.add(xpDomainInfo.resolveInfo);
4785                }
4786                includeBrowser = true;
4787            }
4788
4789            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4790            // If there were 'always' entries their preferred order has been set, so we also
4791            // back that off to make the alternatives equivalent
4792            if (alwaysAskList.size() > 0) {
4793                for (ResolveInfo i : result) {
4794                    i.preferredOrder = 0;
4795                }
4796                result.addAll(alwaysAskList);
4797                includeBrowser = true;
4798            }
4799
4800            if (includeBrowser) {
4801                // Also add browsers (all of them or only the default one)
4802                if (DEBUG_DOMAIN_VERIFICATION) {
4803                    Slog.v(TAG, "   ...including browsers in candidate set");
4804                }
4805                if ((matchFlags & MATCH_ALL) != 0) {
4806                    result.addAll(matchAllList);
4807                } else {
4808                    // Browser/generic handling case.  If there's a default browser, go straight
4809                    // to that (but only if there is no other higher-priority match).
4810                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4811                    int maxMatchPrio = 0;
4812                    ResolveInfo defaultBrowserMatch = null;
4813                    final int numCandidates = matchAllList.size();
4814                    for (int n = 0; n < numCandidates; n++) {
4815                        ResolveInfo info = matchAllList.get(n);
4816                        // track the highest overall match priority...
4817                        if (info.priority > maxMatchPrio) {
4818                            maxMatchPrio = info.priority;
4819                        }
4820                        // ...and the highest-priority default browser match
4821                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4822                            if (defaultBrowserMatch == null
4823                                    || (defaultBrowserMatch.priority < info.priority)) {
4824                                if (debug) {
4825                                    Slog.v(TAG, "Considering default browser match " + info);
4826                                }
4827                                defaultBrowserMatch = info;
4828                            }
4829                        }
4830                    }
4831                    if (defaultBrowserMatch != null
4832                            && defaultBrowserMatch.priority >= maxMatchPrio
4833                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4834                    {
4835                        if (debug) {
4836                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4837                        }
4838                        result.add(defaultBrowserMatch);
4839                    } else {
4840                        result.addAll(matchAllList);
4841                    }
4842                }
4843
4844                // If there is nothing selected, add all candidates and remove the ones that the user
4845                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4846                if (result.size() == 0) {
4847                    result.addAll(candidates);
4848                    result.removeAll(neverList);
4849                }
4850            }
4851        }
4852        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4853            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4854                    result.size());
4855            for (ResolveInfo info : result) {
4856                Slog.v(TAG, "  + " + info.activityInfo);
4857            }
4858        }
4859        return result;
4860    }
4861
4862    // Returns a packed value as a long:
4863    //
4864    // high 'int'-sized word: link status: undefined/ask/never/always.
4865    // low 'int'-sized word: relative priority among 'always' results.
4866    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4867        long result = ps.getDomainVerificationStatusForUser(userId);
4868        // if none available, get the master status
4869        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4870            if (ps.getIntentFilterVerificationInfo() != null) {
4871                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4872            }
4873        }
4874        return result;
4875    }
4876
4877    private ResolveInfo querySkipCurrentProfileIntents(
4878            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4879            int flags, int sourceUserId) {
4880        if (matchingFilters != null) {
4881            int size = matchingFilters.size();
4882            for (int i = 0; i < size; i ++) {
4883                CrossProfileIntentFilter filter = matchingFilters.get(i);
4884                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4885                    // Checking if there are activities in the target user that can handle the
4886                    // intent.
4887                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4888                            flags, sourceUserId);
4889                    if (resolveInfo != null) {
4890                        return resolveInfo;
4891                    }
4892                }
4893            }
4894        }
4895        return null;
4896    }
4897
4898    // Return matching ResolveInfo if any for skip current profile intent filters.
4899    private ResolveInfo queryCrossProfileIntents(
4900            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4901            int flags, int sourceUserId) {
4902        if (matchingFilters != null) {
4903            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4904            // match the same intent. For performance reasons, it is better not to
4905            // run queryIntent twice for the same userId
4906            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4907            int size = matchingFilters.size();
4908            for (int i = 0; i < size; i++) {
4909                CrossProfileIntentFilter filter = matchingFilters.get(i);
4910                int targetUserId = filter.getTargetUserId();
4911                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4912                        && !alreadyTriedUserIds.get(targetUserId)) {
4913                    // Checking if there are activities in the target user that can handle the
4914                    // intent.
4915                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4916                            flags, sourceUserId);
4917                    if (resolveInfo != null) return resolveInfo;
4918                    alreadyTriedUserIds.put(targetUserId, true);
4919                }
4920            }
4921        }
4922        return null;
4923    }
4924
4925    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4926            String resolvedType, int flags, int sourceUserId) {
4927        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4928                resolvedType, flags, filter.getTargetUserId());
4929        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4930            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4931        }
4932        return null;
4933    }
4934
4935    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4936            int sourceUserId, int targetUserId) {
4937        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4938        String className;
4939        if (targetUserId == UserHandle.USER_OWNER) {
4940            className = FORWARD_INTENT_TO_USER_OWNER;
4941        } else {
4942            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4943        }
4944        ComponentName forwardingActivityComponentName = new ComponentName(
4945                mAndroidApplication.packageName, className);
4946        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4947                sourceUserId);
4948        if (targetUserId == UserHandle.USER_OWNER) {
4949            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4950            forwardingResolveInfo.noResourceId = true;
4951        }
4952        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4953        forwardingResolveInfo.priority = 0;
4954        forwardingResolveInfo.preferredOrder = 0;
4955        forwardingResolveInfo.match = 0;
4956        forwardingResolveInfo.isDefault = true;
4957        forwardingResolveInfo.filter = filter;
4958        forwardingResolveInfo.targetUserId = targetUserId;
4959        return forwardingResolveInfo;
4960    }
4961
4962    @Override
4963    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4964            Intent[] specifics, String[] specificTypes, Intent intent,
4965            String resolvedType, int flags, int userId) {
4966        if (!sUserManager.exists(userId)) return Collections.emptyList();
4967        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4968                false, "query intent activity options");
4969        final String resultsAction = intent.getAction();
4970
4971        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4972                | PackageManager.GET_RESOLVED_FILTER, userId);
4973
4974        if (DEBUG_INTENT_MATCHING) {
4975            Log.v(TAG, "Query " + intent + ": " + results);
4976        }
4977
4978        int specificsPos = 0;
4979        int N;
4980
4981        // todo: note that the algorithm used here is O(N^2).  This
4982        // isn't a problem in our current environment, but if we start running
4983        // into situations where we have more than 5 or 10 matches then this
4984        // should probably be changed to something smarter...
4985
4986        // First we go through and resolve each of the specific items
4987        // that were supplied, taking care of removing any corresponding
4988        // duplicate items in the generic resolve list.
4989        if (specifics != null) {
4990            for (int i=0; i<specifics.length; i++) {
4991                final Intent sintent = specifics[i];
4992                if (sintent == null) {
4993                    continue;
4994                }
4995
4996                if (DEBUG_INTENT_MATCHING) {
4997                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4998                }
4999
5000                String action = sintent.getAction();
5001                if (resultsAction != null && resultsAction.equals(action)) {
5002                    // If this action was explicitly requested, then don't
5003                    // remove things that have it.
5004                    action = null;
5005                }
5006
5007                ResolveInfo ri = null;
5008                ActivityInfo ai = null;
5009
5010                ComponentName comp = sintent.getComponent();
5011                if (comp == null) {
5012                    ri = resolveIntent(
5013                        sintent,
5014                        specificTypes != null ? specificTypes[i] : null,
5015                            flags, userId);
5016                    if (ri == null) {
5017                        continue;
5018                    }
5019                    if (ri == mResolveInfo) {
5020                        // ACK!  Must do something better with this.
5021                    }
5022                    ai = ri.activityInfo;
5023                    comp = new ComponentName(ai.applicationInfo.packageName,
5024                            ai.name);
5025                } else {
5026                    ai = getActivityInfo(comp, flags, userId);
5027                    if (ai == null) {
5028                        continue;
5029                    }
5030                }
5031
5032                // Look for any generic query activities that are duplicates
5033                // of this specific one, and remove them from the results.
5034                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5035                N = results.size();
5036                int j;
5037                for (j=specificsPos; j<N; j++) {
5038                    ResolveInfo sri = results.get(j);
5039                    if ((sri.activityInfo.name.equals(comp.getClassName())
5040                            && sri.activityInfo.applicationInfo.packageName.equals(
5041                                    comp.getPackageName()))
5042                        || (action != null && sri.filter.matchAction(action))) {
5043                        results.remove(j);
5044                        if (DEBUG_INTENT_MATCHING) Log.v(
5045                            TAG, "Removing duplicate item from " + j
5046                            + " due to specific " + specificsPos);
5047                        if (ri == null) {
5048                            ri = sri;
5049                        }
5050                        j--;
5051                        N--;
5052                    }
5053                }
5054
5055                // Add this specific item to its proper place.
5056                if (ri == null) {
5057                    ri = new ResolveInfo();
5058                    ri.activityInfo = ai;
5059                }
5060                results.add(specificsPos, ri);
5061                ri.specificIndex = i;
5062                specificsPos++;
5063            }
5064        }
5065
5066        // Now we go through the remaining generic results and remove any
5067        // duplicate actions that are found here.
5068        N = results.size();
5069        for (int i=specificsPos; i<N-1; i++) {
5070            final ResolveInfo rii = results.get(i);
5071            if (rii.filter == null) {
5072                continue;
5073            }
5074
5075            // Iterate over all of the actions of this result's intent
5076            // filter...  typically this should be just one.
5077            final Iterator<String> it = rii.filter.actionsIterator();
5078            if (it == null) {
5079                continue;
5080            }
5081            while (it.hasNext()) {
5082                final String action = it.next();
5083                if (resultsAction != null && resultsAction.equals(action)) {
5084                    // If this action was explicitly requested, then don't
5085                    // remove things that have it.
5086                    continue;
5087                }
5088                for (int j=i+1; j<N; j++) {
5089                    final ResolveInfo rij = results.get(j);
5090                    if (rij.filter != null && rij.filter.hasAction(action)) {
5091                        results.remove(j);
5092                        if (DEBUG_INTENT_MATCHING) Log.v(
5093                            TAG, "Removing duplicate item from " + j
5094                            + " due to action " + action + " at " + i);
5095                        j--;
5096                        N--;
5097                    }
5098                }
5099            }
5100
5101            // If the caller didn't request filter information, drop it now
5102            // so we don't have to marshall/unmarshall it.
5103            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5104                rii.filter = null;
5105            }
5106        }
5107
5108        // Filter out the caller activity if so requested.
5109        if (caller != null) {
5110            N = results.size();
5111            for (int i=0; i<N; i++) {
5112                ActivityInfo ainfo = results.get(i).activityInfo;
5113                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5114                        && caller.getClassName().equals(ainfo.name)) {
5115                    results.remove(i);
5116                    break;
5117                }
5118            }
5119        }
5120
5121        // If the caller didn't request filter information,
5122        // drop them now so we don't have to
5123        // marshall/unmarshall it.
5124        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5125            N = results.size();
5126            for (int i=0; i<N; i++) {
5127                results.get(i).filter = null;
5128            }
5129        }
5130
5131        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5132        return results;
5133    }
5134
5135    @Override
5136    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5137            int userId) {
5138        if (!sUserManager.exists(userId)) return Collections.emptyList();
5139        ComponentName comp = intent.getComponent();
5140        if (comp == null) {
5141            if (intent.getSelector() != null) {
5142                intent = intent.getSelector();
5143                comp = intent.getComponent();
5144            }
5145        }
5146        if (comp != null) {
5147            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5148            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5149            if (ai != null) {
5150                ResolveInfo ri = new ResolveInfo();
5151                ri.activityInfo = ai;
5152                list.add(ri);
5153            }
5154            return list;
5155        }
5156
5157        // reader
5158        synchronized (mPackages) {
5159            String pkgName = intent.getPackage();
5160            if (pkgName == null) {
5161                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5162            }
5163            final PackageParser.Package pkg = mPackages.get(pkgName);
5164            if (pkg != null) {
5165                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5166                        userId);
5167            }
5168            return null;
5169        }
5170    }
5171
5172    @Override
5173    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5174        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5175        if (!sUserManager.exists(userId)) return null;
5176        if (query != null) {
5177            if (query.size() >= 1) {
5178                // If there is more than one service with the same priority,
5179                // just arbitrarily pick the first one.
5180                return query.get(0);
5181            }
5182        }
5183        return null;
5184    }
5185
5186    @Override
5187    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5188            int userId) {
5189        if (!sUserManager.exists(userId)) return Collections.emptyList();
5190        ComponentName comp = intent.getComponent();
5191        if (comp == null) {
5192            if (intent.getSelector() != null) {
5193                intent = intent.getSelector();
5194                comp = intent.getComponent();
5195            }
5196        }
5197        if (comp != null) {
5198            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5199            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5200            if (si != null) {
5201                final ResolveInfo ri = new ResolveInfo();
5202                ri.serviceInfo = si;
5203                list.add(ri);
5204            }
5205            return list;
5206        }
5207
5208        // reader
5209        synchronized (mPackages) {
5210            String pkgName = intent.getPackage();
5211            if (pkgName == null) {
5212                return mServices.queryIntent(intent, resolvedType, flags, userId);
5213            }
5214            final PackageParser.Package pkg = mPackages.get(pkgName);
5215            if (pkg != null) {
5216                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5217                        userId);
5218            }
5219            return null;
5220        }
5221    }
5222
5223    @Override
5224    public List<ResolveInfo> queryIntentContentProviders(
5225            Intent intent, String resolvedType, int flags, int userId) {
5226        if (!sUserManager.exists(userId)) return Collections.emptyList();
5227        ComponentName comp = intent.getComponent();
5228        if (comp == null) {
5229            if (intent.getSelector() != null) {
5230                intent = intent.getSelector();
5231                comp = intent.getComponent();
5232            }
5233        }
5234        if (comp != null) {
5235            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5236            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5237            if (pi != null) {
5238                final ResolveInfo ri = new ResolveInfo();
5239                ri.providerInfo = pi;
5240                list.add(ri);
5241            }
5242            return list;
5243        }
5244
5245        // reader
5246        synchronized (mPackages) {
5247            String pkgName = intent.getPackage();
5248            if (pkgName == null) {
5249                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5250            }
5251            final PackageParser.Package pkg = mPackages.get(pkgName);
5252            if (pkg != null) {
5253                return mProviders.queryIntentForPackage(
5254                        intent, resolvedType, flags, pkg.providers, userId);
5255            }
5256            return null;
5257        }
5258    }
5259
5260    @Override
5261    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5262        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5263
5264        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5265
5266        // writer
5267        synchronized (mPackages) {
5268            ArrayList<PackageInfo> list;
5269            if (listUninstalled) {
5270                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5271                for (PackageSetting ps : mSettings.mPackages.values()) {
5272                    PackageInfo pi;
5273                    if (ps.pkg != null) {
5274                        pi = generatePackageInfo(ps.pkg, flags, userId);
5275                    } else {
5276                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5277                    }
5278                    if (pi != null) {
5279                        list.add(pi);
5280                    }
5281                }
5282            } else {
5283                list = new ArrayList<PackageInfo>(mPackages.size());
5284                for (PackageParser.Package p : mPackages.values()) {
5285                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5286                    if (pi != null) {
5287                        list.add(pi);
5288                    }
5289                }
5290            }
5291
5292            return new ParceledListSlice<PackageInfo>(list);
5293        }
5294    }
5295
5296    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5297            String[] permissions, boolean[] tmp, int flags, int userId) {
5298        int numMatch = 0;
5299        final PermissionsState permissionsState = ps.getPermissionsState();
5300        for (int i=0; i<permissions.length; i++) {
5301            final String permission = permissions[i];
5302            if (permissionsState.hasPermission(permission, userId)) {
5303                tmp[i] = true;
5304                numMatch++;
5305            } else {
5306                tmp[i] = false;
5307            }
5308        }
5309        if (numMatch == 0) {
5310            return;
5311        }
5312        PackageInfo pi;
5313        if (ps.pkg != null) {
5314            pi = generatePackageInfo(ps.pkg, flags, userId);
5315        } else {
5316            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5317        }
5318        // The above might return null in cases of uninstalled apps or install-state
5319        // skew across users/profiles.
5320        if (pi != null) {
5321            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5322                if (numMatch == permissions.length) {
5323                    pi.requestedPermissions = permissions;
5324                } else {
5325                    pi.requestedPermissions = new String[numMatch];
5326                    numMatch = 0;
5327                    for (int i=0; i<permissions.length; i++) {
5328                        if (tmp[i]) {
5329                            pi.requestedPermissions[numMatch] = permissions[i];
5330                            numMatch++;
5331                        }
5332                    }
5333                }
5334            }
5335            list.add(pi);
5336        }
5337    }
5338
5339    @Override
5340    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5341            String[] permissions, int flags, int userId) {
5342        if (!sUserManager.exists(userId)) return null;
5343        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5344
5345        // writer
5346        synchronized (mPackages) {
5347            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5348            boolean[] tmpBools = new boolean[permissions.length];
5349            if (listUninstalled) {
5350                for (PackageSetting ps : mSettings.mPackages.values()) {
5351                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5352                }
5353            } else {
5354                for (PackageParser.Package pkg : mPackages.values()) {
5355                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5356                    if (ps != null) {
5357                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5358                                userId);
5359                    }
5360                }
5361            }
5362
5363            return new ParceledListSlice<PackageInfo>(list);
5364        }
5365    }
5366
5367    @Override
5368    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5369        if (!sUserManager.exists(userId)) return null;
5370        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5371
5372        // writer
5373        synchronized (mPackages) {
5374            ArrayList<ApplicationInfo> list;
5375            if (listUninstalled) {
5376                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5377                for (PackageSetting ps : mSettings.mPackages.values()) {
5378                    ApplicationInfo ai;
5379                    if (ps.pkg != null) {
5380                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5381                                ps.readUserState(userId), userId);
5382                    } else {
5383                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5384                    }
5385                    if (ai != null) {
5386                        list.add(ai);
5387                    }
5388                }
5389            } else {
5390                list = new ArrayList<ApplicationInfo>(mPackages.size());
5391                for (PackageParser.Package p : mPackages.values()) {
5392                    if (p.mExtras != null) {
5393                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5394                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5395                        if (ai != null) {
5396                            list.add(ai);
5397                        }
5398                    }
5399                }
5400            }
5401
5402            return new ParceledListSlice<ApplicationInfo>(list);
5403        }
5404    }
5405
5406    public List<ApplicationInfo> getPersistentApplications(int flags) {
5407        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5408
5409        // reader
5410        synchronized (mPackages) {
5411            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5412            final int userId = UserHandle.getCallingUserId();
5413            while (i.hasNext()) {
5414                final PackageParser.Package p = i.next();
5415                if (p.applicationInfo != null
5416                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5417                        && (!mSafeMode || isSystemApp(p))) {
5418                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5419                    if (ps != null) {
5420                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5421                                ps.readUserState(userId), userId);
5422                        if (ai != null) {
5423                            finalList.add(ai);
5424                        }
5425                    }
5426                }
5427            }
5428        }
5429
5430        return finalList;
5431    }
5432
5433    @Override
5434    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5435        if (!sUserManager.exists(userId)) return null;
5436        // reader
5437        synchronized (mPackages) {
5438            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5439            PackageSetting ps = provider != null
5440                    ? mSettings.mPackages.get(provider.owner.packageName)
5441                    : null;
5442            return ps != null
5443                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5444                    && (!mSafeMode || (provider.info.applicationInfo.flags
5445                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5446                    ? PackageParser.generateProviderInfo(provider, flags,
5447                            ps.readUserState(userId), userId)
5448                    : null;
5449        }
5450    }
5451
5452    /**
5453     * @deprecated
5454     */
5455    @Deprecated
5456    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5457        // reader
5458        synchronized (mPackages) {
5459            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5460                    .entrySet().iterator();
5461            final int userId = UserHandle.getCallingUserId();
5462            while (i.hasNext()) {
5463                Map.Entry<String, PackageParser.Provider> entry = i.next();
5464                PackageParser.Provider p = entry.getValue();
5465                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5466
5467                if (ps != null && p.syncable
5468                        && (!mSafeMode || (p.info.applicationInfo.flags
5469                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5470                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5471                            ps.readUserState(userId), userId);
5472                    if (info != null) {
5473                        outNames.add(entry.getKey());
5474                        outInfo.add(info);
5475                    }
5476                }
5477            }
5478        }
5479    }
5480
5481    @Override
5482    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5483            int uid, int flags) {
5484        ArrayList<ProviderInfo> finalList = null;
5485        // reader
5486        synchronized (mPackages) {
5487            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5488            final int userId = processName != null ?
5489                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5490            while (i.hasNext()) {
5491                final PackageParser.Provider p = i.next();
5492                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5493                if (ps != null && p.info.authority != null
5494                        && (processName == null
5495                                || (p.info.processName.equals(processName)
5496                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5497                        && mSettings.isEnabledLPr(p.info, flags, userId)
5498                        && (!mSafeMode
5499                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5500                    if (finalList == null) {
5501                        finalList = new ArrayList<ProviderInfo>(3);
5502                    }
5503                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5504                            ps.readUserState(userId), userId);
5505                    if (info != null) {
5506                        finalList.add(info);
5507                    }
5508                }
5509            }
5510        }
5511
5512        if (finalList != null) {
5513            Collections.sort(finalList, mProviderInitOrderSorter);
5514            return new ParceledListSlice<ProviderInfo>(finalList);
5515        }
5516
5517        return null;
5518    }
5519
5520    @Override
5521    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5522            int flags) {
5523        // reader
5524        synchronized (mPackages) {
5525            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5526            return PackageParser.generateInstrumentationInfo(i, flags);
5527        }
5528    }
5529
5530    @Override
5531    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5532            int flags) {
5533        ArrayList<InstrumentationInfo> finalList =
5534            new ArrayList<InstrumentationInfo>();
5535
5536        // reader
5537        synchronized (mPackages) {
5538            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5539            while (i.hasNext()) {
5540                final PackageParser.Instrumentation p = i.next();
5541                if (targetPackage == null
5542                        || targetPackage.equals(p.info.targetPackage)) {
5543                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5544                            flags);
5545                    if (ii != null) {
5546                        finalList.add(ii);
5547                    }
5548                }
5549            }
5550        }
5551
5552        return finalList;
5553    }
5554
5555    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5556        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5557        if (overlays == null) {
5558            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5559            return;
5560        }
5561        for (PackageParser.Package opkg : overlays.values()) {
5562            // Not much to do if idmap fails: we already logged the error
5563            // and we certainly don't want to abort installation of pkg simply
5564            // because an overlay didn't fit properly. For these reasons,
5565            // ignore the return value of createIdmapForPackagePairLI.
5566            createIdmapForPackagePairLI(pkg, opkg);
5567        }
5568    }
5569
5570    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5571            PackageParser.Package opkg) {
5572        if (!opkg.mTrustedOverlay) {
5573            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5574                    opkg.baseCodePath + ": overlay not trusted");
5575            return false;
5576        }
5577        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5578        if (overlaySet == null) {
5579            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5580                    opkg.baseCodePath + " but target package has no known overlays");
5581            return false;
5582        }
5583        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5584        // TODO: generate idmap for split APKs
5585        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5586            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5587                    + opkg.baseCodePath);
5588            return false;
5589        }
5590        PackageParser.Package[] overlayArray =
5591            overlaySet.values().toArray(new PackageParser.Package[0]);
5592        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5593            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5594                return p1.mOverlayPriority - p2.mOverlayPriority;
5595            }
5596        };
5597        Arrays.sort(overlayArray, cmp);
5598
5599        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5600        int i = 0;
5601        for (PackageParser.Package p : overlayArray) {
5602            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5603        }
5604        return true;
5605    }
5606
5607    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5608        final File[] files = dir.listFiles();
5609        if (ArrayUtils.isEmpty(files)) {
5610            Log.d(TAG, "No files in app dir " + dir);
5611            return;
5612        }
5613
5614        if (DEBUG_PACKAGE_SCANNING) {
5615            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5616                    + " flags=0x" + Integer.toHexString(parseFlags));
5617        }
5618
5619        for (File file : files) {
5620            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5621                    && !PackageInstallerService.isStageName(file.getName());
5622            if (!isPackage) {
5623                // Ignore entries which are not packages
5624                continue;
5625            }
5626            try {
5627                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5628                        scanFlags, currentTime, null);
5629            } catch (PackageManagerException e) {
5630                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5631
5632                // Delete invalid userdata apps
5633                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5634                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5635                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5636                    if (file.isDirectory()) {
5637                        mInstaller.rmPackageDir(file.getAbsolutePath());
5638                    } else {
5639                        file.delete();
5640                    }
5641                }
5642            }
5643        }
5644    }
5645
5646    private static File getSettingsProblemFile() {
5647        File dataDir = Environment.getDataDirectory();
5648        File systemDir = new File(dataDir, "system");
5649        File fname = new File(systemDir, "uiderrors.txt");
5650        return fname;
5651    }
5652
5653    static void reportSettingsProblem(int priority, String msg) {
5654        logCriticalInfo(priority, msg);
5655    }
5656
5657    static void logCriticalInfo(int priority, String msg) {
5658        Slog.println(priority, TAG, msg);
5659        EventLogTags.writePmCriticalInfo(msg);
5660        try {
5661            File fname = getSettingsProblemFile();
5662            FileOutputStream out = new FileOutputStream(fname, true);
5663            PrintWriter pw = new FastPrintWriter(out);
5664            SimpleDateFormat formatter = new SimpleDateFormat();
5665            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5666            pw.println(dateString + ": " + msg);
5667            pw.close();
5668            FileUtils.setPermissions(
5669                    fname.toString(),
5670                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5671                    -1, -1);
5672        } catch (java.io.IOException e) {
5673        }
5674    }
5675
5676    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5677            PackageParser.Package pkg, File srcFile, int parseFlags)
5678            throws PackageManagerException {
5679        if (ps != null
5680                && ps.codePath.equals(srcFile)
5681                && ps.timeStamp == srcFile.lastModified()
5682                && !isCompatSignatureUpdateNeeded(pkg)
5683                && !isRecoverSignatureUpdateNeeded(pkg)) {
5684            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5685            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5686            ArraySet<PublicKey> signingKs;
5687            synchronized (mPackages) {
5688                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5689            }
5690            if (ps.signatures.mSignatures != null
5691                    && ps.signatures.mSignatures.length != 0
5692                    && signingKs != null) {
5693                // Optimization: reuse the existing cached certificates
5694                // if the package appears to be unchanged.
5695                pkg.mSignatures = ps.signatures.mSignatures;
5696                pkg.mSigningKeys = signingKs;
5697                return;
5698            }
5699
5700            Slog.w(TAG, "PackageSetting for " + ps.name
5701                    + " is missing signatures.  Collecting certs again to recover them.");
5702        } else {
5703            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5704        }
5705
5706        try {
5707            pp.collectCertificates(pkg, parseFlags);
5708            pp.collectManifestDigest(pkg);
5709        } catch (PackageParserException e) {
5710            throw PackageManagerException.from(e);
5711        }
5712    }
5713
5714    /*
5715     *  Scan a package and return the newly parsed package.
5716     *  Returns null in case of errors and the error code is stored in mLastScanError
5717     */
5718    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5719            long currentTime, UserHandle user) throws PackageManagerException {
5720        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5721        parseFlags |= mDefParseFlags;
5722        PackageParser pp = new PackageParser();
5723        pp.setSeparateProcesses(mSeparateProcesses);
5724        pp.setOnlyCoreApps(mOnlyCore);
5725        pp.setDisplayMetrics(mMetrics);
5726
5727        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5728            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5729        }
5730
5731        final PackageParser.Package pkg;
5732        try {
5733            pkg = pp.parsePackage(scanFile, parseFlags);
5734        } catch (PackageParserException e) {
5735            throw PackageManagerException.from(e);
5736        }
5737
5738        PackageSetting ps = null;
5739        PackageSetting updatedPkg;
5740        // reader
5741        synchronized (mPackages) {
5742            // Look to see if we already know about this package.
5743            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5744            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5745                // This package has been renamed to its original name.  Let's
5746                // use that.
5747                ps = mSettings.peekPackageLPr(oldName);
5748            }
5749            // If there was no original package, see one for the real package name.
5750            if (ps == null) {
5751                ps = mSettings.peekPackageLPr(pkg.packageName);
5752            }
5753            // Check to see if this package could be hiding/updating a system
5754            // package.  Must look for it either under the original or real
5755            // package name depending on our state.
5756            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5757            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5758        }
5759        boolean updatedPkgBetter = false;
5760        // First check if this is a system package that may involve an update
5761        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5762            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5763            // it needs to drop FLAG_PRIVILEGED.
5764            if (locationIsPrivileged(scanFile)) {
5765                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5766            } else {
5767                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5768            }
5769
5770            if (ps != null && !ps.codePath.equals(scanFile)) {
5771                // The path has changed from what was last scanned...  check the
5772                // version of the new path against what we have stored to determine
5773                // what to do.
5774                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5775                if (pkg.mVersionCode <= ps.versionCode) {
5776                    // The system package has been updated and the code path does not match
5777                    // Ignore entry. Skip it.
5778                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5779                            + " ignored: updated version " + ps.versionCode
5780                            + " better than this " + pkg.mVersionCode);
5781                    if (!updatedPkg.codePath.equals(scanFile)) {
5782                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5783                                + ps.name + " changing from " + updatedPkg.codePathString
5784                                + " to " + scanFile);
5785                        updatedPkg.codePath = scanFile;
5786                        updatedPkg.codePathString = scanFile.toString();
5787                        updatedPkg.resourcePath = scanFile;
5788                        updatedPkg.resourcePathString = scanFile.toString();
5789                    }
5790                    updatedPkg.pkg = pkg;
5791                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5792                            "Package " + ps.name + " at " + scanFile
5793                                    + " ignored: updated version " + ps.versionCode
5794                                    + " better than this " + pkg.mVersionCode);
5795                } else {
5796                    // The current app on the system partition is better than
5797                    // what we have updated to on the data partition; switch
5798                    // back to the system partition version.
5799                    // At this point, its safely assumed that package installation for
5800                    // apps in system partition will go through. If not there won't be a working
5801                    // version of the app
5802                    // writer
5803                    synchronized (mPackages) {
5804                        // Just remove the loaded entries from package lists.
5805                        mPackages.remove(ps.name);
5806                    }
5807
5808                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5809                            + " reverting from " + ps.codePathString
5810                            + ": new version " + pkg.mVersionCode
5811                            + " better than installed " + ps.versionCode);
5812
5813                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5814                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5815                    synchronized (mInstallLock) {
5816                        args.cleanUpResourcesLI();
5817                    }
5818                    synchronized (mPackages) {
5819                        mSettings.enableSystemPackageLPw(ps.name);
5820                    }
5821                    updatedPkgBetter = true;
5822                }
5823            }
5824        }
5825
5826        if (updatedPkg != null) {
5827            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5828            // initially
5829            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5830
5831            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5832            // flag set initially
5833            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5834                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5835            }
5836        }
5837
5838        // Verify certificates against what was last scanned
5839        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5840
5841        /*
5842         * A new system app appeared, but we already had a non-system one of the
5843         * same name installed earlier.
5844         */
5845        boolean shouldHideSystemApp = false;
5846        if (updatedPkg == null && ps != null
5847                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5848            /*
5849             * Check to make sure the signatures match first. If they don't,
5850             * wipe the installed application and its data.
5851             */
5852            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5853                    != PackageManager.SIGNATURE_MATCH) {
5854                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5855                        + " signatures don't match existing userdata copy; removing");
5856                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5857                ps = null;
5858            } else {
5859                /*
5860                 * If the newly-added system app is an older version than the
5861                 * already installed version, hide it. It will be scanned later
5862                 * and re-added like an update.
5863                 */
5864                if (pkg.mVersionCode <= ps.versionCode) {
5865                    shouldHideSystemApp = true;
5866                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5867                            + " but new version " + pkg.mVersionCode + " better than installed "
5868                            + ps.versionCode + "; hiding system");
5869                } else {
5870                    /*
5871                     * The newly found system app is a newer version that the
5872                     * one previously installed. Simply remove the
5873                     * already-installed application and replace it with our own
5874                     * while keeping the application data.
5875                     */
5876                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5877                            + " reverting from " + ps.codePathString + ": new version "
5878                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5879                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5880                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5881                    synchronized (mInstallLock) {
5882                        args.cleanUpResourcesLI();
5883                    }
5884                }
5885            }
5886        }
5887
5888        // The apk is forward locked (not public) if its code and resources
5889        // are kept in different files. (except for app in either system or
5890        // vendor path).
5891        // TODO grab this value from PackageSettings
5892        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5893            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5894                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5895            }
5896        }
5897
5898        // TODO: extend to support forward-locked splits
5899        String resourcePath = null;
5900        String baseResourcePath = null;
5901        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5902            if (ps != null && ps.resourcePathString != null) {
5903                resourcePath = ps.resourcePathString;
5904                baseResourcePath = ps.resourcePathString;
5905            } else {
5906                // Should not happen at all. Just log an error.
5907                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5908            }
5909        } else {
5910            resourcePath = pkg.codePath;
5911            baseResourcePath = pkg.baseCodePath;
5912        }
5913
5914        // Set application objects path explicitly.
5915        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5916        pkg.applicationInfo.setCodePath(pkg.codePath);
5917        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5918        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5919        pkg.applicationInfo.setResourcePath(resourcePath);
5920        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5921        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5922
5923        // Note that we invoke the following method only if we are about to unpack an application
5924        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5925                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5926
5927        /*
5928         * If the system app should be overridden by a previously installed
5929         * data, hide the system app now and let the /data/app scan pick it up
5930         * again.
5931         */
5932        if (shouldHideSystemApp) {
5933            synchronized (mPackages) {
5934                mSettings.disableSystemPackageLPw(pkg.packageName);
5935            }
5936        }
5937
5938        return scannedPkg;
5939    }
5940
5941    private static String fixProcessName(String defProcessName,
5942            String processName, int uid) {
5943        if (processName == null) {
5944            return defProcessName;
5945        }
5946        return processName;
5947    }
5948
5949    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5950            throws PackageManagerException {
5951        if (pkgSetting.signatures.mSignatures != null) {
5952            // Already existing package. Make sure signatures match
5953            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5954                    == PackageManager.SIGNATURE_MATCH;
5955            if (!match) {
5956                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5957                        == PackageManager.SIGNATURE_MATCH;
5958            }
5959            if (!match) {
5960                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5961                        == PackageManager.SIGNATURE_MATCH;
5962            }
5963            if (!match) {
5964                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5965                        + pkg.packageName + " signatures do not match the "
5966                        + "previously installed version; ignoring!");
5967            }
5968        }
5969
5970        // Check for shared user signatures
5971        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5972            // Already existing package. Make sure signatures match
5973            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5974                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5975            if (!match) {
5976                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5977                        == PackageManager.SIGNATURE_MATCH;
5978            }
5979            if (!match) {
5980                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5981                        == PackageManager.SIGNATURE_MATCH;
5982            }
5983            if (!match) {
5984                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5985                        "Package " + pkg.packageName
5986                        + " has no signatures that match those in shared user "
5987                        + pkgSetting.sharedUser.name + "; ignoring!");
5988            }
5989        }
5990    }
5991
5992    /**
5993     * Enforces that only the system UID or root's UID can call a method exposed
5994     * via Binder.
5995     *
5996     * @param message used as message if SecurityException is thrown
5997     * @throws SecurityException if the caller is not system or root
5998     */
5999    private static final void enforceSystemOrRoot(String message) {
6000        final int uid = Binder.getCallingUid();
6001        if (uid != Process.SYSTEM_UID && uid != 0) {
6002            throw new SecurityException(message);
6003        }
6004    }
6005
6006    @Override
6007    public void performBootDexOpt() {
6008        enforceSystemOrRoot("Only the system can request dexopt be performed");
6009
6010        // Before everything else, see whether we need to fstrim.
6011        try {
6012            IMountService ms = PackageHelper.getMountService();
6013            if (ms != null) {
6014                final boolean isUpgrade = isUpgrade();
6015                boolean doTrim = isUpgrade;
6016                if (doTrim) {
6017                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6018                } else {
6019                    final long interval = android.provider.Settings.Global.getLong(
6020                            mContext.getContentResolver(),
6021                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6022                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6023                    if (interval > 0) {
6024                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6025                        if (timeSinceLast > interval) {
6026                            doTrim = true;
6027                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6028                                    + "; running immediately");
6029                        }
6030                    }
6031                }
6032                if (doTrim) {
6033                    if (!isFirstBoot()) {
6034                        try {
6035                            ActivityManagerNative.getDefault().showBootMessage(
6036                                    mContext.getResources().getString(
6037                                            R.string.android_upgrading_fstrim), true);
6038                        } catch (RemoteException e) {
6039                        }
6040                    }
6041                    ms.runMaintenance();
6042                }
6043            } else {
6044                Slog.e(TAG, "Mount service unavailable!");
6045            }
6046        } catch (RemoteException e) {
6047            // Can't happen; MountService is local
6048        }
6049
6050        final ArraySet<PackageParser.Package> pkgs;
6051        synchronized (mPackages) {
6052            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6053        }
6054
6055        if (pkgs != null) {
6056            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6057            // in case the device runs out of space.
6058            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6059            // Give priority to core apps.
6060            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6061                PackageParser.Package pkg = it.next();
6062                if (pkg.coreApp) {
6063                    if (DEBUG_DEXOPT) {
6064                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6065                    }
6066                    sortedPkgs.add(pkg);
6067                    it.remove();
6068                }
6069            }
6070            // Give priority to system apps that listen for pre boot complete.
6071            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6072            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6073            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6074                PackageParser.Package pkg = it.next();
6075                if (pkgNames.contains(pkg.packageName)) {
6076                    if (DEBUG_DEXOPT) {
6077                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6078                    }
6079                    sortedPkgs.add(pkg);
6080                    it.remove();
6081                }
6082            }
6083            // Filter out packages that aren't recently used.
6084            filterRecentlyUsedApps(pkgs);
6085            // Add all remaining apps.
6086            for (PackageParser.Package pkg : pkgs) {
6087                if (DEBUG_DEXOPT) {
6088                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6089                }
6090                sortedPkgs.add(pkg);
6091            }
6092
6093            // If we want to be lazy, filter everything that wasn't recently used.
6094            if (mLazyDexOpt) {
6095                filterRecentlyUsedApps(sortedPkgs);
6096            }
6097
6098            int i = 0;
6099            int total = sortedPkgs.size();
6100            File dataDir = Environment.getDataDirectory();
6101            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6102            if (lowThreshold == 0) {
6103                throw new IllegalStateException("Invalid low memory threshold");
6104            }
6105            for (PackageParser.Package pkg : sortedPkgs) {
6106                long usableSpace = dataDir.getUsableSpace();
6107                if (usableSpace < lowThreshold) {
6108                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6109                    break;
6110                }
6111                performBootDexOpt(pkg, ++i, total);
6112            }
6113        }
6114    }
6115
6116    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6117        // Filter out packages that aren't recently used.
6118        //
6119        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6120        // should do a full dexopt.
6121        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6122            int total = pkgs.size();
6123            int skipped = 0;
6124            long now = System.currentTimeMillis();
6125            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6126                PackageParser.Package pkg = i.next();
6127                long then = pkg.mLastPackageUsageTimeInMills;
6128                if (then + mDexOptLRUThresholdInMills < now) {
6129                    if (DEBUG_DEXOPT) {
6130                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6131                              ((then == 0) ? "never" : new Date(then)));
6132                    }
6133                    i.remove();
6134                    skipped++;
6135                }
6136            }
6137            if (DEBUG_DEXOPT) {
6138                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6139            }
6140        }
6141    }
6142
6143    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6144        List<ResolveInfo> ris = null;
6145        try {
6146            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6147                    intent, null, 0, UserHandle.USER_OWNER);
6148        } catch (RemoteException e) {
6149        }
6150        ArraySet<String> pkgNames = new ArraySet<String>();
6151        if (ris != null) {
6152            for (ResolveInfo ri : ris) {
6153                pkgNames.add(ri.activityInfo.packageName);
6154            }
6155        }
6156        return pkgNames;
6157    }
6158
6159    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6160        if (DEBUG_DEXOPT) {
6161            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6162        }
6163        if (!isFirstBoot()) {
6164            try {
6165                ActivityManagerNative.getDefault().showBootMessage(
6166                        mContext.getResources().getString(R.string.android_upgrading_apk,
6167                                curr, total), true);
6168            } catch (RemoteException e) {
6169            }
6170        }
6171        PackageParser.Package p = pkg;
6172        synchronized (mInstallLock) {
6173            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6174                    false /* force dex */, false /* defer */, true /* include dependencies */,
6175                    false /* boot complete */);
6176        }
6177    }
6178
6179    @Override
6180    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6181        return performDexOpt(packageName, instructionSet, false);
6182    }
6183
6184    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6185        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6186        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6187        if (!dexopt && !updateUsage) {
6188            // We aren't going to dexopt or update usage, so bail early.
6189            return false;
6190        }
6191        PackageParser.Package p;
6192        final String targetInstructionSet;
6193        synchronized (mPackages) {
6194            p = mPackages.get(packageName);
6195            if (p == null) {
6196                return false;
6197            }
6198            if (updateUsage) {
6199                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6200            }
6201            mPackageUsage.write(false);
6202            if (!dexopt) {
6203                // We aren't going to dexopt, so bail early.
6204                return false;
6205            }
6206
6207            targetInstructionSet = instructionSet != null ? instructionSet :
6208                    getPrimaryInstructionSet(p.applicationInfo);
6209            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6210                return false;
6211            }
6212        }
6213        long callingId = Binder.clearCallingIdentity();
6214        try {
6215            synchronized (mInstallLock) {
6216                final String[] instructionSets = new String[] { targetInstructionSet };
6217                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6218                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6219                        true /* boot complete */);
6220                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6221            }
6222        } finally {
6223            Binder.restoreCallingIdentity(callingId);
6224        }
6225    }
6226
6227    public ArraySet<String> getPackagesThatNeedDexOpt() {
6228        ArraySet<String> pkgs = null;
6229        synchronized (mPackages) {
6230            for (PackageParser.Package p : mPackages.values()) {
6231                if (DEBUG_DEXOPT) {
6232                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6233                }
6234                if (!p.mDexOptPerformed.isEmpty()) {
6235                    continue;
6236                }
6237                if (pkgs == null) {
6238                    pkgs = new ArraySet<String>();
6239                }
6240                pkgs.add(p.packageName);
6241            }
6242        }
6243        return pkgs;
6244    }
6245
6246    public void shutdown() {
6247        mPackageUsage.write(true);
6248    }
6249
6250    @Override
6251    public void forceDexOpt(String packageName) {
6252        enforceSystemOrRoot("forceDexOpt");
6253
6254        PackageParser.Package pkg;
6255        synchronized (mPackages) {
6256            pkg = mPackages.get(packageName);
6257            if (pkg == null) {
6258                throw new IllegalArgumentException("Missing package: " + packageName);
6259            }
6260        }
6261
6262        synchronized (mInstallLock) {
6263            final String[] instructionSets = new String[] {
6264                    getPrimaryInstructionSet(pkg.applicationInfo) };
6265            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6266                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6267                    true /* boot complete */);
6268            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6269                throw new IllegalStateException("Failed to dexopt: " + res);
6270            }
6271        }
6272    }
6273
6274    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6275        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6276            Slog.w(TAG, "Unable to update from " + oldPkg.name
6277                    + " to " + newPkg.packageName
6278                    + ": old package not in system partition");
6279            return false;
6280        } else if (mPackages.get(oldPkg.name) != null) {
6281            Slog.w(TAG, "Unable to update from " + oldPkg.name
6282                    + " to " + newPkg.packageName
6283                    + ": old package still exists");
6284            return false;
6285        }
6286        return true;
6287    }
6288
6289    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6290        int[] users = sUserManager.getUserIds();
6291        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6292        if (res < 0) {
6293            return res;
6294        }
6295        for (int user : users) {
6296            if (user != 0) {
6297                res = mInstaller.createUserData(volumeUuid, packageName,
6298                        UserHandle.getUid(user, uid), user, seinfo);
6299                if (res < 0) {
6300                    return res;
6301                }
6302            }
6303        }
6304        return res;
6305    }
6306
6307    private int removeDataDirsLI(String volumeUuid, String packageName) {
6308        int[] users = sUserManager.getUserIds();
6309        int res = 0;
6310        for (int user : users) {
6311            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6312            if (resInner < 0) {
6313                res = resInner;
6314            }
6315        }
6316
6317        return res;
6318    }
6319
6320    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6321        int[] users = sUserManager.getUserIds();
6322        int res = 0;
6323        for (int user : users) {
6324            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6325            if (resInner < 0) {
6326                res = resInner;
6327            }
6328        }
6329        return res;
6330    }
6331
6332    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6333            PackageParser.Package changingLib) {
6334        if (file.path != null) {
6335            usesLibraryFiles.add(file.path);
6336            return;
6337        }
6338        PackageParser.Package p = mPackages.get(file.apk);
6339        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6340            // If we are doing this while in the middle of updating a library apk,
6341            // then we need to make sure to use that new apk for determining the
6342            // dependencies here.  (We haven't yet finished committing the new apk
6343            // to the package manager state.)
6344            if (p == null || p.packageName.equals(changingLib.packageName)) {
6345                p = changingLib;
6346            }
6347        }
6348        if (p != null) {
6349            usesLibraryFiles.addAll(p.getAllCodePaths());
6350        }
6351    }
6352
6353    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6354            PackageParser.Package changingLib) throws PackageManagerException {
6355        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6356            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6357            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6358            for (int i=0; i<N; i++) {
6359                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6360                if (file == null) {
6361                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6362                            "Package " + pkg.packageName + " requires unavailable shared library "
6363                            + pkg.usesLibraries.get(i) + "; failing!");
6364                }
6365                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6366            }
6367            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6368            for (int i=0; i<N; i++) {
6369                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6370                if (file == null) {
6371                    Slog.w(TAG, "Package " + pkg.packageName
6372                            + " desires unavailable shared library "
6373                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6374                } else {
6375                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6376                }
6377            }
6378            N = usesLibraryFiles.size();
6379            if (N > 0) {
6380                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6381            } else {
6382                pkg.usesLibraryFiles = null;
6383            }
6384        }
6385    }
6386
6387    private static boolean hasString(List<String> list, List<String> which) {
6388        if (list == null) {
6389            return false;
6390        }
6391        for (int i=list.size()-1; i>=0; i--) {
6392            for (int j=which.size()-1; j>=0; j--) {
6393                if (which.get(j).equals(list.get(i))) {
6394                    return true;
6395                }
6396            }
6397        }
6398        return false;
6399    }
6400
6401    private void updateAllSharedLibrariesLPw() {
6402        for (PackageParser.Package pkg : mPackages.values()) {
6403            try {
6404                updateSharedLibrariesLPw(pkg, null);
6405            } catch (PackageManagerException e) {
6406                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6407            }
6408        }
6409    }
6410
6411    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6412            PackageParser.Package changingPkg) {
6413        ArrayList<PackageParser.Package> res = null;
6414        for (PackageParser.Package pkg : mPackages.values()) {
6415            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6416                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6417                if (res == null) {
6418                    res = new ArrayList<PackageParser.Package>();
6419                }
6420                res.add(pkg);
6421                try {
6422                    updateSharedLibrariesLPw(pkg, changingPkg);
6423                } catch (PackageManagerException e) {
6424                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6425                }
6426            }
6427        }
6428        return res;
6429    }
6430
6431    /**
6432     * Derive the value of the {@code cpuAbiOverride} based on the provided
6433     * value and an optional stored value from the package settings.
6434     */
6435    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6436        String cpuAbiOverride = null;
6437
6438        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6439            cpuAbiOverride = null;
6440        } else if (abiOverride != null) {
6441            cpuAbiOverride = abiOverride;
6442        } else if (settings != null) {
6443            cpuAbiOverride = settings.cpuAbiOverrideString;
6444        }
6445
6446        return cpuAbiOverride;
6447    }
6448
6449    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6450            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6451        boolean success = false;
6452        try {
6453            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6454                    currentTime, user);
6455            success = true;
6456            return res;
6457        } finally {
6458            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6459                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6460            }
6461        }
6462    }
6463
6464    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6465            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6466        final File scanFile = new File(pkg.codePath);
6467        if (pkg.applicationInfo.getCodePath() == null ||
6468                pkg.applicationInfo.getResourcePath() == null) {
6469            // Bail out. The resource and code paths haven't been set.
6470            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6471                    "Code and resource paths haven't been set correctly");
6472        }
6473
6474        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6475            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6476        } else {
6477            // Only allow system apps to be flagged as core apps.
6478            pkg.coreApp = false;
6479        }
6480
6481        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6482            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6483        }
6484
6485        if (mCustomResolverComponentName != null &&
6486                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6487            setUpCustomResolverActivity(pkg);
6488        }
6489
6490        if (pkg.packageName.equals("android")) {
6491            synchronized (mPackages) {
6492                if (mAndroidApplication != null) {
6493                    Slog.w(TAG, "*************************************************");
6494                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6495                    Slog.w(TAG, " file=" + scanFile);
6496                    Slog.w(TAG, "*************************************************");
6497                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6498                            "Core android package being redefined.  Skipping.");
6499                }
6500
6501                // Set up information for our fall-back user intent resolution activity.
6502                mPlatformPackage = pkg;
6503                pkg.mVersionCode = mSdkVersion;
6504                mAndroidApplication = pkg.applicationInfo;
6505
6506                if (!mResolverReplaced) {
6507                    mResolveActivity.applicationInfo = mAndroidApplication;
6508                    mResolveActivity.name = ResolverActivity.class.getName();
6509                    mResolveActivity.packageName = mAndroidApplication.packageName;
6510                    mResolveActivity.processName = "system:ui";
6511                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6512                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6513                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6514                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6515                    mResolveActivity.exported = true;
6516                    mResolveActivity.enabled = true;
6517                    mResolveInfo.activityInfo = mResolveActivity;
6518                    mResolveInfo.priority = 0;
6519                    mResolveInfo.preferredOrder = 0;
6520                    mResolveInfo.match = 0;
6521                    mResolveComponentName = new ComponentName(
6522                            mAndroidApplication.packageName, mResolveActivity.name);
6523                }
6524            }
6525        }
6526
6527        if (DEBUG_PACKAGE_SCANNING) {
6528            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6529                Log.d(TAG, "Scanning package " + pkg.packageName);
6530        }
6531
6532        if (mPackages.containsKey(pkg.packageName)
6533                || mSharedLibraries.containsKey(pkg.packageName)) {
6534            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6535                    "Application package " + pkg.packageName
6536                    + " already installed.  Skipping duplicate.");
6537        }
6538
6539        // If we're only installing presumed-existing packages, require that the
6540        // scanned APK is both already known and at the path previously established
6541        // for it.  Previously unknown packages we pick up normally, but if we have an
6542        // a priori expectation about this package's install presence, enforce it.
6543        // With a singular exception for new system packages. When an OTA contains
6544        // a new system package, we allow the codepath to change from a system location
6545        // to the user-installed location. If we don't allow this change, any newer,
6546        // user-installed version of the application will be ignored.
6547        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6548            if (mExpectingBetter.containsKey(pkg.packageName)) {
6549                logCriticalInfo(Log.WARN,
6550                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6551            } else {
6552                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6553                if (known != null) {
6554                    if (DEBUG_PACKAGE_SCANNING) {
6555                        Log.d(TAG, "Examining " + pkg.codePath
6556                                + " and requiring known paths " + known.codePathString
6557                                + " & " + known.resourcePathString);
6558                    }
6559                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6560                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6561                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6562                                "Application package " + pkg.packageName
6563                                + " found at " + pkg.applicationInfo.getCodePath()
6564                                + " but expected at " + known.codePathString + "; ignoring.");
6565                    }
6566                }
6567            }
6568        }
6569
6570        // Initialize package source and resource directories
6571        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6572        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6573
6574        SharedUserSetting suid = null;
6575        PackageSetting pkgSetting = null;
6576
6577        if (!isSystemApp(pkg)) {
6578            // Only system apps can use these features.
6579            pkg.mOriginalPackages = null;
6580            pkg.mRealPackage = null;
6581            pkg.mAdoptPermissions = null;
6582        }
6583
6584        // writer
6585        synchronized (mPackages) {
6586            if (pkg.mSharedUserId != null) {
6587                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6588                if (suid == null) {
6589                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6590                            "Creating application package " + pkg.packageName
6591                            + " for shared user failed");
6592                }
6593                if (DEBUG_PACKAGE_SCANNING) {
6594                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6595                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6596                                + "): packages=" + suid.packages);
6597                }
6598            }
6599
6600            // Check if we are renaming from an original package name.
6601            PackageSetting origPackage = null;
6602            String realName = null;
6603            if (pkg.mOriginalPackages != null) {
6604                // This package may need to be renamed to a previously
6605                // installed name.  Let's check on that...
6606                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6607                if (pkg.mOriginalPackages.contains(renamed)) {
6608                    // This package had originally been installed as the
6609                    // original name, and we have already taken care of
6610                    // transitioning to the new one.  Just update the new
6611                    // one to continue using the old name.
6612                    realName = pkg.mRealPackage;
6613                    if (!pkg.packageName.equals(renamed)) {
6614                        // Callers into this function may have already taken
6615                        // care of renaming the package; only do it here if
6616                        // it is not already done.
6617                        pkg.setPackageName(renamed);
6618                    }
6619
6620                } else {
6621                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6622                        if ((origPackage = mSettings.peekPackageLPr(
6623                                pkg.mOriginalPackages.get(i))) != null) {
6624                            // We do have the package already installed under its
6625                            // original name...  should we use it?
6626                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6627                                // New package is not compatible with original.
6628                                origPackage = null;
6629                                continue;
6630                            } else if (origPackage.sharedUser != null) {
6631                                // Make sure uid is compatible between packages.
6632                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6633                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6634                                            + " to " + pkg.packageName + ": old uid "
6635                                            + origPackage.sharedUser.name
6636                                            + " differs from " + pkg.mSharedUserId);
6637                                    origPackage = null;
6638                                    continue;
6639                                }
6640                            } else {
6641                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6642                                        + pkg.packageName + " to old name " + origPackage.name);
6643                            }
6644                            break;
6645                        }
6646                    }
6647                }
6648            }
6649
6650            if (mTransferedPackages.contains(pkg.packageName)) {
6651                Slog.w(TAG, "Package " + pkg.packageName
6652                        + " was transferred to another, but its .apk remains");
6653            }
6654
6655            // Just create the setting, don't add it yet. For already existing packages
6656            // the PkgSetting exists already and doesn't have to be created.
6657            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6658                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6659                    pkg.applicationInfo.primaryCpuAbi,
6660                    pkg.applicationInfo.secondaryCpuAbi,
6661                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6662                    user, false);
6663            if (pkgSetting == null) {
6664                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6665                        "Creating application package " + pkg.packageName + " failed");
6666            }
6667
6668            if (pkgSetting.origPackage != null) {
6669                // If we are first transitioning from an original package,
6670                // fix up the new package's name now.  We need to do this after
6671                // looking up the package under its new name, so getPackageLP
6672                // can take care of fiddling things correctly.
6673                pkg.setPackageName(origPackage.name);
6674
6675                // File a report about this.
6676                String msg = "New package " + pkgSetting.realName
6677                        + " renamed to replace old package " + pkgSetting.name;
6678                reportSettingsProblem(Log.WARN, msg);
6679
6680                // Make a note of it.
6681                mTransferedPackages.add(origPackage.name);
6682
6683                // No longer need to retain this.
6684                pkgSetting.origPackage = null;
6685            }
6686
6687            if (realName != null) {
6688                // Make a note of it.
6689                mTransferedPackages.add(pkg.packageName);
6690            }
6691
6692            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6693                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6694            }
6695
6696            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6697                // Check all shared libraries and map to their actual file path.
6698                // We only do this here for apps not on a system dir, because those
6699                // are the only ones that can fail an install due to this.  We
6700                // will take care of the system apps by updating all of their
6701                // library paths after the scan is done.
6702                updateSharedLibrariesLPw(pkg, null);
6703            }
6704
6705            if (mFoundPolicyFile) {
6706                SELinuxMMAC.assignSeinfoValue(pkg);
6707            }
6708
6709            pkg.applicationInfo.uid = pkgSetting.appId;
6710            pkg.mExtras = pkgSetting;
6711            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6712                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6713                    // We just determined the app is signed correctly, so bring
6714                    // over the latest parsed certs.
6715                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6716                } else {
6717                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6718                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6719                                "Package " + pkg.packageName + " upgrade keys do not match the "
6720                                + "previously installed version");
6721                    } else {
6722                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6723                        String msg = "System package " + pkg.packageName
6724                            + " signature changed; retaining data.";
6725                        reportSettingsProblem(Log.WARN, msg);
6726                    }
6727                }
6728            } else {
6729                try {
6730                    verifySignaturesLP(pkgSetting, pkg);
6731                    // We just determined the app is signed correctly, so bring
6732                    // over the latest parsed certs.
6733                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6734                } catch (PackageManagerException e) {
6735                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6736                        throw e;
6737                    }
6738                    // The signature has changed, but this package is in the system
6739                    // image...  let's recover!
6740                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6741                    // However...  if this package is part of a shared user, but it
6742                    // doesn't match the signature of the shared user, let's fail.
6743                    // What this means is that you can't change the signatures
6744                    // associated with an overall shared user, which doesn't seem all
6745                    // that unreasonable.
6746                    if (pkgSetting.sharedUser != null) {
6747                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6748                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6749                            throw new PackageManagerException(
6750                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6751                                            "Signature mismatch for shared user : "
6752                                            + pkgSetting.sharedUser);
6753                        }
6754                    }
6755                    // File a report about this.
6756                    String msg = "System package " + pkg.packageName
6757                        + " signature changed; retaining data.";
6758                    reportSettingsProblem(Log.WARN, msg);
6759                }
6760            }
6761            // Verify that this new package doesn't have any content providers
6762            // that conflict with existing packages.  Only do this if the
6763            // package isn't already installed, since we don't want to break
6764            // things that are installed.
6765            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6766                final int N = pkg.providers.size();
6767                int i;
6768                for (i=0; i<N; i++) {
6769                    PackageParser.Provider p = pkg.providers.get(i);
6770                    if (p.info.authority != null) {
6771                        String names[] = p.info.authority.split(";");
6772                        for (int j = 0; j < names.length; j++) {
6773                            if (mProvidersByAuthority.containsKey(names[j])) {
6774                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6775                                final String otherPackageName =
6776                                        ((other != null && other.getComponentName() != null) ?
6777                                                other.getComponentName().getPackageName() : "?");
6778                                throw new PackageManagerException(
6779                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6780                                                "Can't install because provider name " + names[j]
6781                                                + " (in package " + pkg.applicationInfo.packageName
6782                                                + ") is already used by " + otherPackageName);
6783                            }
6784                        }
6785                    }
6786                }
6787            }
6788
6789            if (pkg.mAdoptPermissions != null) {
6790                // This package wants to adopt ownership of permissions from
6791                // another package.
6792                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6793                    final String origName = pkg.mAdoptPermissions.get(i);
6794                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6795                    if (orig != null) {
6796                        if (verifyPackageUpdateLPr(orig, pkg)) {
6797                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6798                                    + pkg.packageName);
6799                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6800                        }
6801                    }
6802                }
6803            }
6804        }
6805
6806        final String pkgName = pkg.packageName;
6807
6808        final long scanFileTime = scanFile.lastModified();
6809        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6810        pkg.applicationInfo.processName = fixProcessName(
6811                pkg.applicationInfo.packageName,
6812                pkg.applicationInfo.processName,
6813                pkg.applicationInfo.uid);
6814
6815        File dataPath;
6816        if (mPlatformPackage == pkg) {
6817            // The system package is special.
6818            dataPath = new File(Environment.getDataDirectory(), "system");
6819
6820            pkg.applicationInfo.dataDir = dataPath.getPath();
6821
6822        } else {
6823            // This is a normal package, need to make its data directory.
6824            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6825                    UserHandle.USER_OWNER, pkg.packageName);
6826
6827            boolean uidError = false;
6828            if (dataPath.exists()) {
6829                int currentUid = 0;
6830                try {
6831                    StructStat stat = Os.stat(dataPath.getPath());
6832                    currentUid = stat.st_uid;
6833                } catch (ErrnoException e) {
6834                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6835                }
6836
6837                // If we have mismatched owners for the data path, we have a problem.
6838                if (currentUid != pkg.applicationInfo.uid) {
6839                    boolean recovered = false;
6840                    if (currentUid == 0) {
6841                        // The directory somehow became owned by root.  Wow.
6842                        // This is probably because the system was stopped while
6843                        // installd was in the middle of messing with its libs
6844                        // directory.  Ask installd to fix that.
6845                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6846                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6847                        if (ret >= 0) {
6848                            recovered = true;
6849                            String msg = "Package " + pkg.packageName
6850                                    + " unexpectedly changed to uid 0; recovered to " +
6851                                    + pkg.applicationInfo.uid;
6852                            reportSettingsProblem(Log.WARN, msg);
6853                        }
6854                    }
6855                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6856                            || (scanFlags&SCAN_BOOTING) != 0)) {
6857                        // If this is a system app, we can at least delete its
6858                        // current data so the application will still work.
6859                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6860                        if (ret >= 0) {
6861                            // TODO: Kill the processes first
6862                            // Old data gone!
6863                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6864                                    ? "System package " : "Third party package ";
6865                            String msg = prefix + pkg.packageName
6866                                    + " has changed from uid: "
6867                                    + currentUid + " to "
6868                                    + pkg.applicationInfo.uid + "; old data erased";
6869                            reportSettingsProblem(Log.WARN, msg);
6870                            recovered = true;
6871
6872                            // And now re-install the app.
6873                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6874                                    pkg.applicationInfo.seinfo);
6875                            if (ret == -1) {
6876                                // Ack should not happen!
6877                                msg = prefix + pkg.packageName
6878                                        + " could not have data directory re-created after delete.";
6879                                reportSettingsProblem(Log.WARN, msg);
6880                                throw new PackageManagerException(
6881                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6882                            }
6883                        }
6884                        if (!recovered) {
6885                            mHasSystemUidErrors = true;
6886                        }
6887                    } else if (!recovered) {
6888                        // If we allow this install to proceed, we will be broken.
6889                        // Abort, abort!
6890                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6891                                "scanPackageLI");
6892                    }
6893                    if (!recovered) {
6894                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6895                            + pkg.applicationInfo.uid + "/fs_"
6896                            + currentUid;
6897                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6898                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6899                        String msg = "Package " + pkg.packageName
6900                                + " has mismatched uid: "
6901                                + currentUid + " on disk, "
6902                                + pkg.applicationInfo.uid + " in settings";
6903                        // writer
6904                        synchronized (mPackages) {
6905                            mSettings.mReadMessages.append(msg);
6906                            mSettings.mReadMessages.append('\n');
6907                            uidError = true;
6908                            if (!pkgSetting.uidError) {
6909                                reportSettingsProblem(Log.ERROR, msg);
6910                            }
6911                        }
6912                    }
6913                }
6914                pkg.applicationInfo.dataDir = dataPath.getPath();
6915                if (mShouldRestoreconData) {
6916                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6917                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6918                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6919                }
6920            } else {
6921                if (DEBUG_PACKAGE_SCANNING) {
6922                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6923                        Log.v(TAG, "Want this data dir: " + dataPath);
6924                }
6925                //invoke installer to do the actual installation
6926                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6927                        pkg.applicationInfo.seinfo);
6928                if (ret < 0) {
6929                    // Error from installer
6930                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6931                            "Unable to create data dirs [errorCode=" + ret + "]");
6932                }
6933
6934                if (dataPath.exists()) {
6935                    pkg.applicationInfo.dataDir = dataPath.getPath();
6936                } else {
6937                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6938                    pkg.applicationInfo.dataDir = null;
6939                }
6940            }
6941
6942            pkgSetting.uidError = uidError;
6943        }
6944
6945        final String path = scanFile.getPath();
6946        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6947
6948        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6949            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6950
6951            // Some system apps still use directory structure for native libraries
6952            // in which case we might end up not detecting abi solely based on apk
6953            // structure. Try to detect abi based on directory structure.
6954            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6955                    pkg.applicationInfo.primaryCpuAbi == null) {
6956                setBundledAppAbisAndRoots(pkg, pkgSetting);
6957                setNativeLibraryPaths(pkg);
6958            }
6959
6960        } else {
6961            if ((scanFlags & SCAN_MOVE) != 0) {
6962                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6963                // but we already have this packages package info in the PackageSetting. We just
6964                // use that and derive the native library path based on the new codepath.
6965                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6966                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6967            }
6968
6969            // Set native library paths again. For moves, the path will be updated based on the
6970            // ABIs we've determined above. For non-moves, the path will be updated based on the
6971            // ABIs we determined during compilation, but the path will depend on the final
6972            // package path (after the rename away from the stage path).
6973            setNativeLibraryPaths(pkg);
6974        }
6975
6976        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6977        final int[] userIds = sUserManager.getUserIds();
6978        synchronized (mInstallLock) {
6979            // Make sure all user data directories are ready to roll; we're okay
6980            // if they already exist
6981            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6982                for (int userId : userIds) {
6983                    if (userId != 0) {
6984                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6985                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6986                                pkg.applicationInfo.seinfo);
6987                    }
6988                }
6989            }
6990
6991            // Create a native library symlink only if we have native libraries
6992            // and if the native libraries are 32 bit libraries. We do not provide
6993            // this symlink for 64 bit libraries.
6994            if (pkg.applicationInfo.primaryCpuAbi != null &&
6995                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6996                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6997                for (int userId : userIds) {
6998                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6999                            nativeLibPath, userId) < 0) {
7000                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7001                                "Failed linking native library dir (user=" + userId + ")");
7002                    }
7003                }
7004            }
7005        }
7006
7007        // This is a special case for the "system" package, where the ABI is
7008        // dictated by the zygote configuration (and init.rc). We should keep track
7009        // of this ABI so that we can deal with "normal" applications that run under
7010        // the same UID correctly.
7011        if (mPlatformPackage == pkg) {
7012            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7013                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7014        }
7015
7016        // If there's a mismatch between the abi-override in the package setting
7017        // and the abiOverride specified for the install. Warn about this because we
7018        // would've already compiled the app without taking the package setting into
7019        // account.
7020        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7021            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7022                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7023                        " for package: " + pkg.packageName);
7024            }
7025        }
7026
7027        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7028        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7029        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7030
7031        // Copy the derived override back to the parsed package, so that we can
7032        // update the package settings accordingly.
7033        pkg.cpuAbiOverride = cpuAbiOverride;
7034
7035        if (DEBUG_ABI_SELECTION) {
7036            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7037                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7038                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7039        }
7040
7041        // Push the derived path down into PackageSettings so we know what to
7042        // clean up at uninstall time.
7043        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7044
7045        if (DEBUG_ABI_SELECTION) {
7046            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7047                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7048                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7049        }
7050
7051        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7052            // We don't do this here during boot because we can do it all
7053            // at once after scanning all existing packages.
7054            //
7055            // We also do this *before* we perform dexopt on this package, so that
7056            // we can avoid redundant dexopts, and also to make sure we've got the
7057            // code and package path correct.
7058            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7059                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7060        }
7061
7062        if ((scanFlags & SCAN_NO_DEX) == 0) {
7063            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7064                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7065                    (scanFlags & SCAN_BOOTING) == 0);
7066            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7067                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7068            }
7069        }
7070        if (mFactoryTest && pkg.requestedPermissions.contains(
7071                android.Manifest.permission.FACTORY_TEST)) {
7072            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7073        }
7074
7075        ArrayList<PackageParser.Package> clientLibPkgs = null;
7076
7077        // writer
7078        synchronized (mPackages) {
7079            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7080                // Only system apps can add new shared libraries.
7081                if (pkg.libraryNames != null) {
7082                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7083                        String name = pkg.libraryNames.get(i);
7084                        boolean allowed = false;
7085                        if (pkg.isUpdatedSystemApp()) {
7086                            // New library entries can only be added through the
7087                            // system image.  This is important to get rid of a lot
7088                            // of nasty edge cases: for example if we allowed a non-
7089                            // system update of the app to add a library, then uninstalling
7090                            // the update would make the library go away, and assumptions
7091                            // we made such as through app install filtering would now
7092                            // have allowed apps on the device which aren't compatible
7093                            // with it.  Better to just have the restriction here, be
7094                            // conservative, and create many fewer cases that can negatively
7095                            // impact the user experience.
7096                            final PackageSetting sysPs = mSettings
7097                                    .getDisabledSystemPkgLPr(pkg.packageName);
7098                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7099                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7100                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7101                                        allowed = true;
7102                                        allowed = true;
7103                                        break;
7104                                    }
7105                                }
7106                            }
7107                        } else {
7108                            allowed = true;
7109                        }
7110                        if (allowed) {
7111                            if (!mSharedLibraries.containsKey(name)) {
7112                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7113                            } else if (!name.equals(pkg.packageName)) {
7114                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7115                                        + name + " already exists; skipping");
7116                            }
7117                        } else {
7118                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7119                                    + name + " that is not declared on system image; skipping");
7120                        }
7121                    }
7122                    if ((scanFlags&SCAN_BOOTING) == 0) {
7123                        // If we are not booting, we need to update any applications
7124                        // that are clients of our shared library.  If we are booting,
7125                        // this will all be done once the scan is complete.
7126                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7127                    }
7128                }
7129            }
7130        }
7131
7132        // We also need to dexopt any apps that are dependent on this library.  Note that
7133        // if these fail, we should abort the install since installing the library will
7134        // result in some apps being broken.
7135        if (clientLibPkgs != null) {
7136            if ((scanFlags & SCAN_NO_DEX) == 0) {
7137                for (int i = 0; i < clientLibPkgs.size(); i++) {
7138                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7139                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7140                            null /* instruction sets */, forceDex,
7141                            (scanFlags & SCAN_DEFER_DEX) != 0, false,
7142                            (scanFlags & SCAN_BOOTING) == 0);
7143                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7144                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7145                                "scanPackageLI failed to dexopt clientLibPkgs");
7146                    }
7147                }
7148            }
7149        }
7150
7151        // Request the ActivityManager to kill the process(only for existing packages)
7152        // so that we do not end up in a confused state while the user is still using the older
7153        // version of the application while the new one gets installed.
7154        if ((scanFlags & SCAN_REPLACING) != 0) {
7155            killApplication(pkg.applicationInfo.packageName,
7156                        pkg.applicationInfo.uid, "replace pkg");
7157        }
7158
7159        // Also need to kill any apps that are dependent on the library.
7160        if (clientLibPkgs != null) {
7161            for (int i=0; i<clientLibPkgs.size(); i++) {
7162                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7163                killApplication(clientPkg.applicationInfo.packageName,
7164                        clientPkg.applicationInfo.uid, "update lib");
7165            }
7166        }
7167
7168        // Make sure we're not adding any bogus keyset info
7169        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7170        ksms.assertScannedPackageValid(pkg);
7171
7172        // writer
7173        synchronized (mPackages) {
7174            // We don't expect installation to fail beyond this point
7175
7176            // Add the new setting to mSettings
7177            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7178            // Add the new setting to mPackages
7179            mPackages.put(pkg.applicationInfo.packageName, pkg);
7180            // Make sure we don't accidentally delete its data.
7181            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7182            while (iter.hasNext()) {
7183                PackageCleanItem item = iter.next();
7184                if (pkgName.equals(item.packageName)) {
7185                    iter.remove();
7186                }
7187            }
7188
7189            // Take care of first install / last update times.
7190            if (currentTime != 0) {
7191                if (pkgSetting.firstInstallTime == 0) {
7192                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7193                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7194                    pkgSetting.lastUpdateTime = currentTime;
7195                }
7196            } else if (pkgSetting.firstInstallTime == 0) {
7197                // We need *something*.  Take time time stamp of the file.
7198                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7199            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7200                if (scanFileTime != pkgSetting.timeStamp) {
7201                    // A package on the system image has changed; consider this
7202                    // to be an update.
7203                    pkgSetting.lastUpdateTime = scanFileTime;
7204                }
7205            }
7206
7207            // Add the package's KeySets to the global KeySetManagerService
7208            ksms.addScannedPackageLPw(pkg);
7209
7210            int N = pkg.providers.size();
7211            StringBuilder r = null;
7212            int i;
7213            for (i=0; i<N; i++) {
7214                PackageParser.Provider p = pkg.providers.get(i);
7215                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7216                        p.info.processName, pkg.applicationInfo.uid);
7217                mProviders.addProvider(p);
7218                p.syncable = p.info.isSyncable;
7219                if (p.info.authority != null) {
7220                    String names[] = p.info.authority.split(";");
7221                    p.info.authority = null;
7222                    for (int j = 0; j < names.length; j++) {
7223                        if (j == 1 && p.syncable) {
7224                            // We only want the first authority for a provider to possibly be
7225                            // syncable, so if we already added this provider using a different
7226                            // authority clear the syncable flag. We copy the provider before
7227                            // changing it because the mProviders object contains a reference
7228                            // to a provider that we don't want to change.
7229                            // Only do this for the second authority since the resulting provider
7230                            // object can be the same for all future authorities for this provider.
7231                            p = new PackageParser.Provider(p);
7232                            p.syncable = false;
7233                        }
7234                        if (!mProvidersByAuthority.containsKey(names[j])) {
7235                            mProvidersByAuthority.put(names[j], p);
7236                            if (p.info.authority == null) {
7237                                p.info.authority = names[j];
7238                            } else {
7239                                p.info.authority = p.info.authority + ";" + names[j];
7240                            }
7241                            if (DEBUG_PACKAGE_SCANNING) {
7242                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7243                                    Log.d(TAG, "Registered content provider: " + names[j]
7244                                            + ", className = " + p.info.name + ", isSyncable = "
7245                                            + p.info.isSyncable);
7246                            }
7247                        } else {
7248                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7249                            Slog.w(TAG, "Skipping provider name " + names[j] +
7250                                    " (in package " + pkg.applicationInfo.packageName +
7251                                    "): name already used by "
7252                                    + ((other != null && other.getComponentName() != null)
7253                                            ? other.getComponentName().getPackageName() : "?"));
7254                        }
7255                    }
7256                }
7257                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7258                    if (r == null) {
7259                        r = new StringBuilder(256);
7260                    } else {
7261                        r.append(' ');
7262                    }
7263                    r.append(p.info.name);
7264                }
7265            }
7266            if (r != null) {
7267                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7268            }
7269
7270            N = pkg.services.size();
7271            r = null;
7272            for (i=0; i<N; i++) {
7273                PackageParser.Service s = pkg.services.get(i);
7274                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7275                        s.info.processName, pkg.applicationInfo.uid);
7276                mServices.addService(s);
7277                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7278                    if (r == null) {
7279                        r = new StringBuilder(256);
7280                    } else {
7281                        r.append(' ');
7282                    }
7283                    r.append(s.info.name);
7284                }
7285            }
7286            if (r != null) {
7287                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7288            }
7289
7290            N = pkg.receivers.size();
7291            r = null;
7292            for (i=0; i<N; i++) {
7293                PackageParser.Activity a = pkg.receivers.get(i);
7294                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7295                        a.info.processName, pkg.applicationInfo.uid);
7296                mReceivers.addActivity(a, "receiver");
7297                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7298                    if (r == null) {
7299                        r = new StringBuilder(256);
7300                    } else {
7301                        r.append(' ');
7302                    }
7303                    r.append(a.info.name);
7304                }
7305            }
7306            if (r != null) {
7307                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7308            }
7309
7310            N = pkg.activities.size();
7311            r = null;
7312            for (i=0; i<N; i++) {
7313                PackageParser.Activity a = pkg.activities.get(i);
7314                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7315                        a.info.processName, pkg.applicationInfo.uid);
7316                mActivities.addActivity(a, "activity");
7317                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7318                    if (r == null) {
7319                        r = new StringBuilder(256);
7320                    } else {
7321                        r.append(' ');
7322                    }
7323                    r.append(a.info.name);
7324                }
7325            }
7326            if (r != null) {
7327                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7328            }
7329
7330            N = pkg.permissionGroups.size();
7331            r = null;
7332            for (i=0; i<N; i++) {
7333                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7334                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7335                if (cur == null) {
7336                    mPermissionGroups.put(pg.info.name, pg);
7337                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7338                        if (r == null) {
7339                            r = new StringBuilder(256);
7340                        } else {
7341                            r.append(' ');
7342                        }
7343                        r.append(pg.info.name);
7344                    }
7345                } else {
7346                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7347                            + pg.info.packageName + " ignored: original from "
7348                            + cur.info.packageName);
7349                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7350                        if (r == null) {
7351                            r = new StringBuilder(256);
7352                        } else {
7353                            r.append(' ');
7354                        }
7355                        r.append("DUP:");
7356                        r.append(pg.info.name);
7357                    }
7358                }
7359            }
7360            if (r != null) {
7361                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7362            }
7363
7364            N = pkg.permissions.size();
7365            r = null;
7366            for (i=0; i<N; i++) {
7367                PackageParser.Permission p = pkg.permissions.get(i);
7368
7369                // Assume by default that we did not install this permission into the system.
7370                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7371
7372                // Now that permission groups have a special meaning, we ignore permission
7373                // groups for legacy apps to prevent unexpected behavior. In particular,
7374                // permissions for one app being granted to someone just becuase they happen
7375                // to be in a group defined by another app (before this had no implications).
7376                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7377                    p.group = mPermissionGroups.get(p.info.group);
7378                    // Warn for a permission in an unknown group.
7379                    if (p.info.group != null && p.group == null) {
7380                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7381                                + p.info.packageName + " in an unknown group " + p.info.group);
7382                    }
7383                }
7384
7385                ArrayMap<String, BasePermission> permissionMap =
7386                        p.tree ? mSettings.mPermissionTrees
7387                                : mSettings.mPermissions;
7388                BasePermission bp = permissionMap.get(p.info.name);
7389
7390                // Allow system apps to redefine non-system permissions
7391                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7392                    final boolean currentOwnerIsSystem = (bp.perm != null
7393                            && isSystemApp(bp.perm.owner));
7394                    if (isSystemApp(p.owner)) {
7395                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7396                            // It's a built-in permission and no owner, take ownership now
7397                            bp.packageSetting = pkgSetting;
7398                            bp.perm = p;
7399                            bp.uid = pkg.applicationInfo.uid;
7400                            bp.sourcePackage = p.info.packageName;
7401                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7402                        } else if (!currentOwnerIsSystem) {
7403                            String msg = "New decl " + p.owner + " of permission  "
7404                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7405                            reportSettingsProblem(Log.WARN, msg);
7406                            bp = null;
7407                        }
7408                    }
7409                }
7410
7411                if (bp == null) {
7412                    bp = new BasePermission(p.info.name, p.info.packageName,
7413                            BasePermission.TYPE_NORMAL);
7414                    permissionMap.put(p.info.name, bp);
7415                }
7416
7417                if (bp.perm == null) {
7418                    if (bp.sourcePackage == null
7419                            || bp.sourcePackage.equals(p.info.packageName)) {
7420                        BasePermission tree = findPermissionTreeLP(p.info.name);
7421                        if (tree == null
7422                                || tree.sourcePackage.equals(p.info.packageName)) {
7423                            bp.packageSetting = pkgSetting;
7424                            bp.perm = p;
7425                            bp.uid = pkg.applicationInfo.uid;
7426                            bp.sourcePackage = p.info.packageName;
7427                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7428                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7429                                if (r == null) {
7430                                    r = new StringBuilder(256);
7431                                } else {
7432                                    r.append(' ');
7433                                }
7434                                r.append(p.info.name);
7435                            }
7436                        } else {
7437                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7438                                    + p.info.packageName + " ignored: base tree "
7439                                    + tree.name + " is from package "
7440                                    + tree.sourcePackage);
7441                        }
7442                    } else {
7443                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7444                                + p.info.packageName + " ignored: original from "
7445                                + bp.sourcePackage);
7446                    }
7447                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7448                    if (r == null) {
7449                        r = new StringBuilder(256);
7450                    } else {
7451                        r.append(' ');
7452                    }
7453                    r.append("DUP:");
7454                    r.append(p.info.name);
7455                }
7456                if (bp.perm == p) {
7457                    bp.protectionLevel = p.info.protectionLevel;
7458                }
7459            }
7460
7461            if (r != null) {
7462                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7463            }
7464
7465            N = pkg.instrumentation.size();
7466            r = null;
7467            for (i=0; i<N; i++) {
7468                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7469                a.info.packageName = pkg.applicationInfo.packageName;
7470                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7471                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7472                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7473                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7474                a.info.dataDir = pkg.applicationInfo.dataDir;
7475
7476                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7477                // need other information about the application, like the ABI and what not ?
7478                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7479                mInstrumentation.put(a.getComponentName(), a);
7480                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7481                    if (r == null) {
7482                        r = new StringBuilder(256);
7483                    } else {
7484                        r.append(' ');
7485                    }
7486                    r.append(a.info.name);
7487                }
7488            }
7489            if (r != null) {
7490                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7491            }
7492
7493            if (pkg.protectedBroadcasts != null) {
7494                N = pkg.protectedBroadcasts.size();
7495                for (i=0; i<N; i++) {
7496                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7497                }
7498            }
7499
7500            pkgSetting.setTimeStamp(scanFileTime);
7501
7502            // Create idmap files for pairs of (packages, overlay packages).
7503            // Note: "android", ie framework-res.apk, is handled by native layers.
7504            if (pkg.mOverlayTarget != null) {
7505                // This is an overlay package.
7506                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7507                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7508                        mOverlays.put(pkg.mOverlayTarget,
7509                                new ArrayMap<String, PackageParser.Package>());
7510                    }
7511                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7512                    map.put(pkg.packageName, pkg);
7513                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7514                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7515                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7516                                "scanPackageLI failed to createIdmap");
7517                    }
7518                }
7519            } else if (mOverlays.containsKey(pkg.packageName) &&
7520                    !pkg.packageName.equals("android")) {
7521                // This is a regular package, with one or more known overlay packages.
7522                createIdmapsForPackageLI(pkg);
7523            }
7524        }
7525
7526        return pkg;
7527    }
7528
7529    /**
7530     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7531     * is derived purely on the basis of the contents of {@code scanFile} and
7532     * {@code cpuAbiOverride}.
7533     *
7534     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7535     */
7536    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7537                                 String cpuAbiOverride, boolean extractLibs)
7538            throws PackageManagerException {
7539        // TODO: We can probably be smarter about this stuff. For installed apps,
7540        // we can calculate this information at install time once and for all. For
7541        // system apps, we can probably assume that this information doesn't change
7542        // after the first boot scan. As things stand, we do lots of unnecessary work.
7543
7544        // Give ourselves some initial paths; we'll come back for another
7545        // pass once we've determined ABI below.
7546        setNativeLibraryPaths(pkg);
7547
7548        // We would never need to extract libs for forward-locked and external packages,
7549        // since the container service will do it for us. We shouldn't attempt to
7550        // extract libs from system app when it was not updated.
7551        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7552                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7553            extractLibs = false;
7554        }
7555
7556        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7557        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7558
7559        NativeLibraryHelper.Handle handle = null;
7560        try {
7561            handle = NativeLibraryHelper.Handle.create(scanFile);
7562            // TODO(multiArch): This can be null for apps that didn't go through the
7563            // usual installation process. We can calculate it again, like we
7564            // do during install time.
7565            //
7566            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7567            // unnecessary.
7568            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7569
7570            // Null out the abis so that they can be recalculated.
7571            pkg.applicationInfo.primaryCpuAbi = null;
7572            pkg.applicationInfo.secondaryCpuAbi = null;
7573            if (isMultiArch(pkg.applicationInfo)) {
7574                // Warn if we've set an abiOverride for multi-lib packages..
7575                // By definition, we need to copy both 32 and 64 bit libraries for
7576                // such packages.
7577                if (pkg.cpuAbiOverride != null
7578                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7579                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7580                }
7581
7582                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7583                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7584                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7585                    if (extractLibs) {
7586                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7587                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7588                                useIsaSpecificSubdirs);
7589                    } else {
7590                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7591                    }
7592                }
7593
7594                maybeThrowExceptionForMultiArchCopy(
7595                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7596
7597                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7598                    if (extractLibs) {
7599                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7600                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7601                                useIsaSpecificSubdirs);
7602                    } else {
7603                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7604                    }
7605                }
7606
7607                maybeThrowExceptionForMultiArchCopy(
7608                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7609
7610                if (abi64 >= 0) {
7611                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7612                }
7613
7614                if (abi32 >= 0) {
7615                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7616                    if (abi64 >= 0) {
7617                        pkg.applicationInfo.secondaryCpuAbi = abi;
7618                    } else {
7619                        pkg.applicationInfo.primaryCpuAbi = abi;
7620                    }
7621                }
7622            } else {
7623                String[] abiList = (cpuAbiOverride != null) ?
7624                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7625
7626                // Enable gross and lame hacks for apps that are built with old
7627                // SDK tools. We must scan their APKs for renderscript bitcode and
7628                // not launch them if it's present. Don't bother checking on devices
7629                // that don't have 64 bit support.
7630                boolean needsRenderScriptOverride = false;
7631                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7632                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7633                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7634                    needsRenderScriptOverride = true;
7635                }
7636
7637                final int copyRet;
7638                if (extractLibs) {
7639                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7640                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7641                } else {
7642                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7643                }
7644
7645                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7646                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7647                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7648                }
7649
7650                if (copyRet >= 0) {
7651                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7652                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7653                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7654                } else if (needsRenderScriptOverride) {
7655                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7656                }
7657            }
7658        } catch (IOException ioe) {
7659            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7660        } finally {
7661            IoUtils.closeQuietly(handle);
7662        }
7663
7664        // Now that we've calculated the ABIs and determined if it's an internal app,
7665        // we will go ahead and populate the nativeLibraryPath.
7666        setNativeLibraryPaths(pkg);
7667    }
7668
7669    /**
7670     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7671     * i.e, so that all packages can be run inside a single process if required.
7672     *
7673     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7674     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7675     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7676     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7677     * updating a package that belongs to a shared user.
7678     *
7679     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7680     * adds unnecessary complexity.
7681     */
7682    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7683            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7684            boolean bootComplete) {
7685        String requiredInstructionSet = null;
7686        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7687            requiredInstructionSet = VMRuntime.getInstructionSet(
7688                     scannedPackage.applicationInfo.primaryCpuAbi);
7689        }
7690
7691        PackageSetting requirer = null;
7692        for (PackageSetting ps : packagesForUser) {
7693            // If packagesForUser contains scannedPackage, we skip it. This will happen
7694            // when scannedPackage is an update of an existing package. Without this check,
7695            // we will never be able to change the ABI of any package belonging to a shared
7696            // user, even if it's compatible with other packages.
7697            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7698                if (ps.primaryCpuAbiString == null) {
7699                    continue;
7700                }
7701
7702                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7703                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7704                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7705                    // this but there's not much we can do.
7706                    String errorMessage = "Instruction set mismatch, "
7707                            + ((requirer == null) ? "[caller]" : requirer)
7708                            + " requires " + requiredInstructionSet + " whereas " + ps
7709                            + " requires " + instructionSet;
7710                    Slog.w(TAG, errorMessage);
7711                }
7712
7713                if (requiredInstructionSet == null) {
7714                    requiredInstructionSet = instructionSet;
7715                    requirer = ps;
7716                }
7717            }
7718        }
7719
7720        if (requiredInstructionSet != null) {
7721            String adjustedAbi;
7722            if (requirer != null) {
7723                // requirer != null implies that either scannedPackage was null or that scannedPackage
7724                // did not require an ABI, in which case we have to adjust scannedPackage to match
7725                // the ABI of the set (which is the same as requirer's ABI)
7726                adjustedAbi = requirer.primaryCpuAbiString;
7727                if (scannedPackage != null) {
7728                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7729                }
7730            } else {
7731                // requirer == null implies that we're updating all ABIs in the set to
7732                // match scannedPackage.
7733                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7734            }
7735
7736            for (PackageSetting ps : packagesForUser) {
7737                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7738                    if (ps.primaryCpuAbiString != null) {
7739                        continue;
7740                    }
7741
7742                    ps.primaryCpuAbiString = adjustedAbi;
7743                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7744                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7745                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7746
7747                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7748                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7749                                bootComplete);
7750                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7751                            ps.primaryCpuAbiString = null;
7752                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7753                            return;
7754                        } else {
7755                            mInstaller.rmdex(ps.codePathString,
7756                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7757                        }
7758                    }
7759                }
7760            }
7761        }
7762    }
7763
7764    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7765        synchronized (mPackages) {
7766            mResolverReplaced = true;
7767            // Set up information for custom user intent resolution activity.
7768            mResolveActivity.applicationInfo = pkg.applicationInfo;
7769            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7770            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7771            mResolveActivity.processName = pkg.applicationInfo.packageName;
7772            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7773            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7774                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7775            mResolveActivity.theme = 0;
7776            mResolveActivity.exported = true;
7777            mResolveActivity.enabled = true;
7778            mResolveInfo.activityInfo = mResolveActivity;
7779            mResolveInfo.priority = 0;
7780            mResolveInfo.preferredOrder = 0;
7781            mResolveInfo.match = 0;
7782            mResolveComponentName = mCustomResolverComponentName;
7783            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7784                    mResolveComponentName);
7785        }
7786    }
7787
7788    private static String calculateBundledApkRoot(final String codePathString) {
7789        final File codePath = new File(codePathString);
7790        final File codeRoot;
7791        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7792            codeRoot = Environment.getRootDirectory();
7793        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7794            codeRoot = Environment.getOemDirectory();
7795        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7796            codeRoot = Environment.getVendorDirectory();
7797        } else {
7798            // Unrecognized code path; take its top real segment as the apk root:
7799            // e.g. /something/app/blah.apk => /something
7800            try {
7801                File f = codePath.getCanonicalFile();
7802                File parent = f.getParentFile();    // non-null because codePath is a file
7803                File tmp;
7804                while ((tmp = parent.getParentFile()) != null) {
7805                    f = parent;
7806                    parent = tmp;
7807                }
7808                codeRoot = f;
7809                Slog.w(TAG, "Unrecognized code path "
7810                        + codePath + " - using " + codeRoot);
7811            } catch (IOException e) {
7812                // Can't canonicalize the code path -- shenanigans?
7813                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7814                return Environment.getRootDirectory().getPath();
7815            }
7816        }
7817        return codeRoot.getPath();
7818    }
7819
7820    /**
7821     * Derive and set the location of native libraries for the given package,
7822     * which varies depending on where and how the package was installed.
7823     */
7824    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7825        final ApplicationInfo info = pkg.applicationInfo;
7826        final String codePath = pkg.codePath;
7827        final File codeFile = new File(codePath);
7828        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7829        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
7830
7831        info.nativeLibraryRootDir = null;
7832        info.nativeLibraryRootRequiresIsa = false;
7833        info.nativeLibraryDir = null;
7834        info.secondaryNativeLibraryDir = null;
7835
7836        if (isApkFile(codeFile)) {
7837            // Monolithic install
7838            if (bundledApp) {
7839                // If "/system/lib64/apkname" exists, assume that is the per-package
7840                // native library directory to use; otherwise use "/system/lib/apkname".
7841                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7842                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7843                        getPrimaryInstructionSet(info));
7844
7845                // This is a bundled system app so choose the path based on the ABI.
7846                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7847                // is just the default path.
7848                final String apkName = deriveCodePathName(codePath);
7849                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7850                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7851                        apkName).getAbsolutePath();
7852
7853                if (info.secondaryCpuAbi != null) {
7854                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7855                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7856                            secondaryLibDir, apkName).getAbsolutePath();
7857                }
7858            } else if (asecApp) {
7859                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7860                        .getAbsolutePath();
7861            } else {
7862                final String apkName = deriveCodePathName(codePath);
7863                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7864                        .getAbsolutePath();
7865            }
7866
7867            info.nativeLibraryRootRequiresIsa = false;
7868            info.nativeLibraryDir = info.nativeLibraryRootDir;
7869        } else {
7870            // Cluster install
7871            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7872            info.nativeLibraryRootRequiresIsa = true;
7873
7874            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7875                    getPrimaryInstructionSet(info)).getAbsolutePath();
7876
7877            if (info.secondaryCpuAbi != null) {
7878                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7879                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7880            }
7881        }
7882    }
7883
7884    /**
7885     * Calculate the abis and roots for a bundled app. These can uniquely
7886     * be determined from the contents of the system partition, i.e whether
7887     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7888     * of this information, and instead assume that the system was built
7889     * sensibly.
7890     */
7891    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7892                                           PackageSetting pkgSetting) {
7893        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7894
7895        // If "/system/lib64/apkname" exists, assume that is the per-package
7896        // native library directory to use; otherwise use "/system/lib/apkname".
7897        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7898        setBundledAppAbi(pkg, apkRoot, apkName);
7899        // pkgSetting might be null during rescan following uninstall of updates
7900        // to a bundled app, so accommodate that possibility.  The settings in
7901        // that case will be established later from the parsed package.
7902        //
7903        // If the settings aren't null, sync them up with what we've just derived.
7904        // note that apkRoot isn't stored in the package settings.
7905        if (pkgSetting != null) {
7906            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7907            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7908        }
7909    }
7910
7911    /**
7912     * Deduces the ABI of a bundled app and sets the relevant fields on the
7913     * parsed pkg object.
7914     *
7915     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7916     *        under which system libraries are installed.
7917     * @param apkName the name of the installed package.
7918     */
7919    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7920        final File codeFile = new File(pkg.codePath);
7921
7922        final boolean has64BitLibs;
7923        final boolean has32BitLibs;
7924        if (isApkFile(codeFile)) {
7925            // Monolithic install
7926            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7927            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7928        } else {
7929            // Cluster install
7930            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7931            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7932                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7933                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7934                has64BitLibs = (new File(rootDir, isa)).exists();
7935            } else {
7936                has64BitLibs = false;
7937            }
7938            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7939                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7940                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7941                has32BitLibs = (new File(rootDir, isa)).exists();
7942            } else {
7943                has32BitLibs = false;
7944            }
7945        }
7946
7947        if (has64BitLibs && !has32BitLibs) {
7948            // The package has 64 bit libs, but not 32 bit libs. Its primary
7949            // ABI should be 64 bit. We can safely assume here that the bundled
7950            // native libraries correspond to the most preferred ABI in the list.
7951
7952            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7953            pkg.applicationInfo.secondaryCpuAbi = null;
7954        } else if (has32BitLibs && !has64BitLibs) {
7955            // The package has 32 bit libs but not 64 bit libs. Its primary
7956            // ABI should be 32 bit.
7957
7958            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7959            pkg.applicationInfo.secondaryCpuAbi = null;
7960        } else if (has32BitLibs && has64BitLibs) {
7961            // The application has both 64 and 32 bit bundled libraries. We check
7962            // here that the app declares multiArch support, and warn if it doesn't.
7963            //
7964            // We will be lenient here and record both ABIs. The primary will be the
7965            // ABI that's higher on the list, i.e, a device that's configured to prefer
7966            // 64 bit apps will see a 64 bit primary ABI,
7967
7968            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7969                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7970            }
7971
7972            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7973                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7974                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7975            } else {
7976                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7977                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7978            }
7979        } else {
7980            pkg.applicationInfo.primaryCpuAbi = null;
7981            pkg.applicationInfo.secondaryCpuAbi = null;
7982        }
7983    }
7984
7985    private void killApplication(String pkgName, int appId, String reason) {
7986        // Request the ActivityManager to kill the process(only for existing packages)
7987        // so that we do not end up in a confused state while the user is still using the older
7988        // version of the application while the new one gets installed.
7989        IActivityManager am = ActivityManagerNative.getDefault();
7990        if (am != null) {
7991            try {
7992                am.killApplicationWithAppId(pkgName, appId, reason);
7993            } catch (RemoteException e) {
7994            }
7995        }
7996    }
7997
7998    void removePackageLI(PackageSetting ps, boolean chatty) {
7999        if (DEBUG_INSTALL) {
8000            if (chatty)
8001                Log.d(TAG, "Removing package " + ps.name);
8002        }
8003
8004        // writer
8005        synchronized (mPackages) {
8006            mPackages.remove(ps.name);
8007            final PackageParser.Package pkg = ps.pkg;
8008            if (pkg != null) {
8009                cleanPackageDataStructuresLILPw(pkg, chatty);
8010            }
8011        }
8012    }
8013
8014    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8015        if (DEBUG_INSTALL) {
8016            if (chatty)
8017                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8018        }
8019
8020        // writer
8021        synchronized (mPackages) {
8022            mPackages.remove(pkg.applicationInfo.packageName);
8023            cleanPackageDataStructuresLILPw(pkg, chatty);
8024        }
8025    }
8026
8027    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8028        int N = pkg.providers.size();
8029        StringBuilder r = null;
8030        int i;
8031        for (i=0; i<N; i++) {
8032            PackageParser.Provider p = pkg.providers.get(i);
8033            mProviders.removeProvider(p);
8034            if (p.info.authority == null) {
8035
8036                /* There was another ContentProvider with this authority when
8037                 * this app was installed so this authority is null,
8038                 * Ignore it as we don't have to unregister the provider.
8039                 */
8040                continue;
8041            }
8042            String names[] = p.info.authority.split(";");
8043            for (int j = 0; j < names.length; j++) {
8044                if (mProvidersByAuthority.get(names[j]) == p) {
8045                    mProvidersByAuthority.remove(names[j]);
8046                    if (DEBUG_REMOVE) {
8047                        if (chatty)
8048                            Log.d(TAG, "Unregistered content provider: " + names[j]
8049                                    + ", className = " + p.info.name + ", isSyncable = "
8050                                    + p.info.isSyncable);
8051                    }
8052                }
8053            }
8054            if (DEBUG_REMOVE && chatty) {
8055                if (r == null) {
8056                    r = new StringBuilder(256);
8057                } else {
8058                    r.append(' ');
8059                }
8060                r.append(p.info.name);
8061            }
8062        }
8063        if (r != null) {
8064            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8065        }
8066
8067        N = pkg.services.size();
8068        r = null;
8069        for (i=0; i<N; i++) {
8070            PackageParser.Service s = pkg.services.get(i);
8071            mServices.removeService(s);
8072            if (chatty) {
8073                if (r == null) {
8074                    r = new StringBuilder(256);
8075                } else {
8076                    r.append(' ');
8077                }
8078                r.append(s.info.name);
8079            }
8080        }
8081        if (r != null) {
8082            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8083        }
8084
8085        N = pkg.receivers.size();
8086        r = null;
8087        for (i=0; i<N; i++) {
8088            PackageParser.Activity a = pkg.receivers.get(i);
8089            mReceivers.removeActivity(a, "receiver");
8090            if (DEBUG_REMOVE && chatty) {
8091                if (r == null) {
8092                    r = new StringBuilder(256);
8093                } else {
8094                    r.append(' ');
8095                }
8096                r.append(a.info.name);
8097            }
8098        }
8099        if (r != null) {
8100            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8101        }
8102
8103        N = pkg.activities.size();
8104        r = null;
8105        for (i=0; i<N; i++) {
8106            PackageParser.Activity a = pkg.activities.get(i);
8107            mActivities.removeActivity(a, "activity");
8108            if (DEBUG_REMOVE && chatty) {
8109                if (r == null) {
8110                    r = new StringBuilder(256);
8111                } else {
8112                    r.append(' ');
8113                }
8114                r.append(a.info.name);
8115            }
8116        }
8117        if (r != null) {
8118            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8119        }
8120
8121        N = pkg.permissions.size();
8122        r = null;
8123        for (i=0; i<N; i++) {
8124            PackageParser.Permission p = pkg.permissions.get(i);
8125            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8126            if (bp == null) {
8127                bp = mSettings.mPermissionTrees.get(p.info.name);
8128            }
8129            if (bp != null && bp.perm == p) {
8130                bp.perm = null;
8131                if (DEBUG_REMOVE && chatty) {
8132                    if (r == null) {
8133                        r = new StringBuilder(256);
8134                    } else {
8135                        r.append(' ');
8136                    }
8137                    r.append(p.info.name);
8138                }
8139            }
8140            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8141                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8142                if (appOpPerms != null) {
8143                    appOpPerms.remove(pkg.packageName);
8144                }
8145            }
8146        }
8147        if (r != null) {
8148            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8149        }
8150
8151        N = pkg.requestedPermissions.size();
8152        r = null;
8153        for (i=0; i<N; i++) {
8154            String perm = pkg.requestedPermissions.get(i);
8155            BasePermission bp = mSettings.mPermissions.get(perm);
8156            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8157                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8158                if (appOpPerms != null) {
8159                    appOpPerms.remove(pkg.packageName);
8160                    if (appOpPerms.isEmpty()) {
8161                        mAppOpPermissionPackages.remove(perm);
8162                    }
8163                }
8164            }
8165        }
8166        if (r != null) {
8167            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8168        }
8169
8170        N = pkg.instrumentation.size();
8171        r = null;
8172        for (i=0; i<N; i++) {
8173            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8174            mInstrumentation.remove(a.getComponentName());
8175            if (DEBUG_REMOVE && chatty) {
8176                if (r == null) {
8177                    r = new StringBuilder(256);
8178                } else {
8179                    r.append(' ');
8180                }
8181                r.append(a.info.name);
8182            }
8183        }
8184        if (r != null) {
8185            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8186        }
8187
8188        r = null;
8189        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8190            // Only system apps can hold shared libraries.
8191            if (pkg.libraryNames != null) {
8192                for (i=0; i<pkg.libraryNames.size(); i++) {
8193                    String name = pkg.libraryNames.get(i);
8194                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8195                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8196                        mSharedLibraries.remove(name);
8197                        if (DEBUG_REMOVE && chatty) {
8198                            if (r == null) {
8199                                r = new StringBuilder(256);
8200                            } else {
8201                                r.append(' ');
8202                            }
8203                            r.append(name);
8204                        }
8205                    }
8206                }
8207            }
8208        }
8209        if (r != null) {
8210            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8211        }
8212    }
8213
8214    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8215        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8216            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8217                return true;
8218            }
8219        }
8220        return false;
8221    }
8222
8223    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8224    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8225    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8226
8227    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8228            int flags) {
8229        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8230        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8231    }
8232
8233    private void updatePermissionsLPw(String changingPkg,
8234            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8235        // Make sure there are no dangling permission trees.
8236        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8237        while (it.hasNext()) {
8238            final BasePermission bp = it.next();
8239            if (bp.packageSetting == null) {
8240                // We may not yet have parsed the package, so just see if
8241                // we still know about its settings.
8242                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8243            }
8244            if (bp.packageSetting == null) {
8245                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8246                        + " from package " + bp.sourcePackage);
8247                it.remove();
8248            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8249                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8250                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8251                            + " from package " + bp.sourcePackage);
8252                    flags |= UPDATE_PERMISSIONS_ALL;
8253                    it.remove();
8254                }
8255            }
8256        }
8257
8258        // Make sure all dynamic permissions have been assigned to a package,
8259        // and make sure there are no dangling permissions.
8260        it = mSettings.mPermissions.values().iterator();
8261        while (it.hasNext()) {
8262            final BasePermission bp = it.next();
8263            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8264                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8265                        + bp.name + " pkg=" + bp.sourcePackage
8266                        + " info=" + bp.pendingInfo);
8267                if (bp.packageSetting == null && bp.pendingInfo != null) {
8268                    final BasePermission tree = findPermissionTreeLP(bp.name);
8269                    if (tree != null && tree.perm != null) {
8270                        bp.packageSetting = tree.packageSetting;
8271                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8272                                new PermissionInfo(bp.pendingInfo));
8273                        bp.perm.info.packageName = tree.perm.info.packageName;
8274                        bp.perm.info.name = bp.name;
8275                        bp.uid = tree.uid;
8276                    }
8277                }
8278            }
8279            if (bp.packageSetting == null) {
8280                // We may not yet have parsed the package, so just see if
8281                // we still know about its settings.
8282                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8283            }
8284            if (bp.packageSetting == null) {
8285                Slog.w(TAG, "Removing dangling permission: " + bp.name
8286                        + " from package " + bp.sourcePackage);
8287                it.remove();
8288            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8289                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8290                    Slog.i(TAG, "Removing old permission: " + bp.name
8291                            + " from package " + bp.sourcePackage);
8292                    flags |= UPDATE_PERMISSIONS_ALL;
8293                    it.remove();
8294                }
8295            }
8296        }
8297
8298        // Now update the permissions for all packages, in particular
8299        // replace the granted permissions of the system packages.
8300        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8301            for (PackageParser.Package pkg : mPackages.values()) {
8302                if (pkg != pkgInfo) {
8303                    // Only replace for packages on requested volume
8304                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8305                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8306                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8307                    grantPermissionsLPw(pkg, replace, changingPkg);
8308                }
8309            }
8310        }
8311
8312        if (pkgInfo != null) {
8313            // Only replace for packages on requested volume
8314            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8315            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8316                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8317            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8318        }
8319    }
8320
8321    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8322            String packageOfInterest) {
8323        // IMPORTANT: There are two types of permissions: install and runtime.
8324        // Install time permissions are granted when the app is installed to
8325        // all device users and users added in the future. Runtime permissions
8326        // are granted at runtime explicitly to specific users. Normal and signature
8327        // protected permissions are install time permissions. Dangerous permissions
8328        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8329        // otherwise they are runtime permissions. This function does not manage
8330        // runtime permissions except for the case an app targeting Lollipop MR1
8331        // being upgraded to target a newer SDK, in which case dangerous permissions
8332        // are transformed from install time to runtime ones.
8333
8334        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8335        if (ps == null) {
8336            return;
8337        }
8338
8339        PermissionsState permissionsState = ps.getPermissionsState();
8340        PermissionsState origPermissions = permissionsState;
8341
8342        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8343
8344        boolean runtimePermissionsRevoked = false;
8345        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8346
8347        boolean changedInstallPermission = false;
8348
8349        if (replace) {
8350            ps.installPermissionsFixed = false;
8351            if (!ps.isSharedUser()) {
8352                origPermissions = new PermissionsState(permissionsState);
8353                permissionsState.reset();
8354            } else {
8355                // We need to know only about runtime permission changes since the
8356                // calling code always writes the install permissions state but
8357                // the runtime ones are written only if changed. The only cases of
8358                // changed runtime permissions here are promotion of an install to
8359                // runtime and revocation of a runtime from a shared user.
8360                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8361                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8362                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8363                    runtimePermissionsRevoked = true;
8364                }
8365            }
8366        }
8367
8368        permissionsState.setGlobalGids(mGlobalGids);
8369
8370        final int N = pkg.requestedPermissions.size();
8371        for (int i=0; i<N; i++) {
8372            final String name = pkg.requestedPermissions.get(i);
8373            final BasePermission bp = mSettings.mPermissions.get(name);
8374
8375            if (DEBUG_INSTALL) {
8376                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8377            }
8378
8379            if (bp == null || bp.packageSetting == null) {
8380                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8381                    Slog.w(TAG, "Unknown permission " + name
8382                            + " in package " + pkg.packageName);
8383                }
8384                continue;
8385            }
8386
8387            final String perm = bp.name;
8388            boolean allowedSig = false;
8389            int grant = GRANT_DENIED;
8390
8391            // Keep track of app op permissions.
8392            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8393                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8394                if (pkgs == null) {
8395                    pkgs = new ArraySet<>();
8396                    mAppOpPermissionPackages.put(bp.name, pkgs);
8397                }
8398                pkgs.add(pkg.packageName);
8399            }
8400
8401            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8402            switch (level) {
8403                case PermissionInfo.PROTECTION_NORMAL: {
8404                    // For all apps normal permissions are install time ones.
8405                    grant = GRANT_INSTALL;
8406                } break;
8407
8408                case PermissionInfo.PROTECTION_DANGEROUS: {
8409                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8410                        // For legacy apps dangerous permissions are install time ones.
8411                        grant = GRANT_INSTALL_LEGACY;
8412                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8413                        // For legacy apps that became modern, install becomes runtime.
8414                        grant = GRANT_UPGRADE;
8415                    } else if (mPromoteSystemApps
8416                            && isSystemApp(ps)
8417                            && mExistingSystemPackages.contains(ps.name)) {
8418                        // For legacy system apps, install becomes runtime.
8419                        // We cannot check hasInstallPermission() for system apps since those
8420                        // permissions were granted implicitly and not persisted pre-M.
8421                        grant = GRANT_UPGRADE;
8422                    } else {
8423                        // For modern apps keep runtime permissions unchanged.
8424                        grant = GRANT_RUNTIME;
8425                    }
8426                } break;
8427
8428                case PermissionInfo.PROTECTION_SIGNATURE: {
8429                    // For all apps signature permissions are install time ones.
8430                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8431                    if (allowedSig) {
8432                        grant = GRANT_INSTALL;
8433                    }
8434                } break;
8435            }
8436
8437            if (DEBUG_INSTALL) {
8438                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8439            }
8440
8441            if (grant != GRANT_DENIED) {
8442                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8443                    // If this is an existing, non-system package, then
8444                    // we can't add any new permissions to it.
8445                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8446                        // Except...  if this is a permission that was added
8447                        // to the platform (note: need to only do this when
8448                        // updating the platform).
8449                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8450                            grant = GRANT_DENIED;
8451                        }
8452                    }
8453                }
8454
8455                switch (grant) {
8456                    case GRANT_INSTALL: {
8457                        // Revoke this as runtime permission to handle the case of
8458                        // a runtime permission being downgraded to an install one.
8459                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8460                            if (origPermissions.getRuntimePermissionState(
8461                                    bp.name, userId) != null) {
8462                                // Revoke the runtime permission and clear the flags.
8463                                origPermissions.revokeRuntimePermission(bp, userId);
8464                                origPermissions.updatePermissionFlags(bp, userId,
8465                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8466                                // If we revoked a permission permission, we have to write.
8467                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8468                                        changedRuntimePermissionUserIds, userId);
8469                            }
8470                        }
8471                        // Grant an install permission.
8472                        if (permissionsState.grantInstallPermission(bp) !=
8473                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8474                            changedInstallPermission = true;
8475                        }
8476                    } break;
8477
8478                    case GRANT_INSTALL_LEGACY: {
8479                        // Grant an install permission.
8480                        if (permissionsState.grantInstallPermission(bp) !=
8481                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8482                            changedInstallPermission = true;
8483                        }
8484                    } break;
8485
8486                    case GRANT_RUNTIME: {
8487                        // Grant previously granted runtime permissions.
8488                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8489                            PermissionState permissionState = origPermissions
8490                                    .getRuntimePermissionState(bp.name, userId);
8491                            final int flags = permissionState != null
8492                                    ? permissionState.getFlags() : 0;
8493                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8494                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8495                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8496                                    // If we cannot put the permission as it was, we have to write.
8497                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8498                                            changedRuntimePermissionUserIds, userId);
8499                                }
8500                            }
8501                            // Propagate the permission flags.
8502                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8503                        }
8504                    } break;
8505
8506                    case GRANT_UPGRADE: {
8507                        // Grant runtime permissions for a previously held install permission.
8508                        PermissionState permissionState = origPermissions
8509                                .getInstallPermissionState(bp.name);
8510                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8511
8512                        if (origPermissions.revokeInstallPermission(bp)
8513                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8514                            // We will be transferring the permission flags, so clear them.
8515                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8516                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8517                            changedInstallPermission = true;
8518                        }
8519
8520                        // If the permission is not to be promoted to runtime we ignore it and
8521                        // also its other flags as they are not applicable to install permissions.
8522                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8523                            for (int userId : currentUserIds) {
8524                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8525                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8526                                    // Transfer the permission flags.
8527                                    permissionsState.updatePermissionFlags(bp, userId,
8528                                            flags, flags);
8529                                    // If we granted the permission, we have to write.
8530                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8531                                            changedRuntimePermissionUserIds, userId);
8532                                }
8533                            }
8534                        }
8535                    } break;
8536
8537                    default: {
8538                        if (packageOfInterest == null
8539                                || packageOfInterest.equals(pkg.packageName)) {
8540                            Slog.w(TAG, "Not granting permission " + perm
8541                                    + " to package " + pkg.packageName
8542                                    + " because it was previously installed without");
8543                        }
8544                    } break;
8545                }
8546            } else {
8547                if (permissionsState.revokeInstallPermission(bp) !=
8548                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8549                    // Also drop the permission flags.
8550                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8551                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8552                    changedInstallPermission = true;
8553                    Slog.i(TAG, "Un-granting permission " + perm
8554                            + " from package " + pkg.packageName
8555                            + " (protectionLevel=" + bp.protectionLevel
8556                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8557                            + ")");
8558                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8559                    // Don't print warning for app op permissions, since it is fine for them
8560                    // not to be granted, there is a UI for the user to decide.
8561                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8562                        Slog.w(TAG, "Not granting permission " + perm
8563                                + " to package " + pkg.packageName
8564                                + " (protectionLevel=" + bp.protectionLevel
8565                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8566                                + ")");
8567                    }
8568                }
8569            }
8570        }
8571
8572        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8573                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8574            // This is the first that we have heard about this package, so the
8575            // permissions we have now selected are fixed until explicitly
8576            // changed.
8577            ps.installPermissionsFixed = true;
8578        }
8579
8580        // Persist the runtime permissions state for users with changes. If permissions
8581        // were revoked because no app in the shared user declares them we have to
8582        // write synchronously to avoid losing runtime permissions state.
8583        for (int userId : changedRuntimePermissionUserIds) {
8584            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8585        }
8586    }
8587
8588    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8589        boolean allowed = false;
8590        final int NP = PackageParser.NEW_PERMISSIONS.length;
8591        for (int ip=0; ip<NP; ip++) {
8592            final PackageParser.NewPermissionInfo npi
8593                    = PackageParser.NEW_PERMISSIONS[ip];
8594            if (npi.name.equals(perm)
8595                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8596                allowed = true;
8597                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8598                        + pkg.packageName);
8599                break;
8600            }
8601        }
8602        return allowed;
8603    }
8604
8605    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8606            BasePermission bp, PermissionsState origPermissions) {
8607        boolean allowed;
8608        allowed = (compareSignatures(
8609                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8610                        == PackageManager.SIGNATURE_MATCH)
8611                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8612                        == PackageManager.SIGNATURE_MATCH);
8613        if (!allowed && (bp.protectionLevel
8614                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8615            if (isSystemApp(pkg)) {
8616                // For updated system applications, a system permission
8617                // is granted only if it had been defined by the original application.
8618                if (pkg.isUpdatedSystemApp()) {
8619                    final PackageSetting sysPs = mSettings
8620                            .getDisabledSystemPkgLPr(pkg.packageName);
8621                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8622                        // If the original was granted this permission, we take
8623                        // that grant decision as read and propagate it to the
8624                        // update.
8625                        if (sysPs.isPrivileged()) {
8626                            allowed = true;
8627                        }
8628                    } else {
8629                        // The system apk may have been updated with an older
8630                        // version of the one on the data partition, but which
8631                        // granted a new system permission that it didn't have
8632                        // before.  In this case we do want to allow the app to
8633                        // now get the new permission if the ancestral apk is
8634                        // privileged to get it.
8635                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8636                            for (int j=0;
8637                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8638                                if (perm.equals(
8639                                        sysPs.pkg.requestedPermissions.get(j))) {
8640                                    allowed = true;
8641                                    break;
8642                                }
8643                            }
8644                        }
8645                    }
8646                } else {
8647                    allowed = isPrivilegedApp(pkg);
8648                }
8649            }
8650        }
8651        if (!allowed) {
8652            if (!allowed && (bp.protectionLevel
8653                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8654                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8655                // If this was a previously normal/dangerous permission that got moved
8656                // to a system permission as part of the runtime permission redesign, then
8657                // we still want to blindly grant it to old apps.
8658                allowed = true;
8659            }
8660            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8661                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8662                // If this permission is to be granted to the system installer and
8663                // this app is an installer, then it gets the permission.
8664                allowed = true;
8665            }
8666            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8667                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8668                // If this permission is to be granted to the system verifier and
8669                // this app is a verifier, then it gets the permission.
8670                allowed = true;
8671            }
8672            if (!allowed && (bp.protectionLevel
8673                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8674                    && isSystemApp(pkg)) {
8675                // Any pre-installed system app is allowed to get this permission.
8676                allowed = true;
8677            }
8678            if (!allowed && (bp.protectionLevel
8679                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8680                // For development permissions, a development permission
8681                // is granted only if it was already granted.
8682                allowed = origPermissions.hasInstallPermission(perm);
8683            }
8684        }
8685        return allowed;
8686    }
8687
8688    final class ActivityIntentResolver
8689            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8690        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8691                boolean defaultOnly, int userId) {
8692            if (!sUserManager.exists(userId)) return null;
8693            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8694            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8695        }
8696
8697        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8698                int userId) {
8699            if (!sUserManager.exists(userId)) return null;
8700            mFlags = flags;
8701            return super.queryIntent(intent, resolvedType,
8702                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8703        }
8704
8705        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8706                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8707            if (!sUserManager.exists(userId)) return null;
8708            if (packageActivities == null) {
8709                return null;
8710            }
8711            mFlags = flags;
8712            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8713            final int N = packageActivities.size();
8714            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8715                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8716
8717            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8718            for (int i = 0; i < N; ++i) {
8719                intentFilters = packageActivities.get(i).intents;
8720                if (intentFilters != null && intentFilters.size() > 0) {
8721                    PackageParser.ActivityIntentInfo[] array =
8722                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8723                    intentFilters.toArray(array);
8724                    listCut.add(array);
8725                }
8726            }
8727            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8728        }
8729
8730        public final void addActivity(PackageParser.Activity a, String type) {
8731            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8732            mActivities.put(a.getComponentName(), a);
8733            if (DEBUG_SHOW_INFO)
8734                Log.v(
8735                TAG, "  " + type + " " +
8736                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8737            if (DEBUG_SHOW_INFO)
8738                Log.v(TAG, "    Class=" + a.info.name);
8739            final int NI = a.intents.size();
8740            for (int j=0; j<NI; j++) {
8741                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8742                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8743                    intent.setPriority(0);
8744                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8745                            + a.className + " with priority > 0, forcing to 0");
8746                }
8747                if (DEBUG_SHOW_INFO) {
8748                    Log.v(TAG, "    IntentFilter:");
8749                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8750                }
8751                if (!intent.debugCheck()) {
8752                    Log.w(TAG, "==> For Activity " + a.info.name);
8753                }
8754                addFilter(intent);
8755            }
8756        }
8757
8758        public final void removeActivity(PackageParser.Activity a, String type) {
8759            mActivities.remove(a.getComponentName());
8760            if (DEBUG_SHOW_INFO) {
8761                Log.v(TAG, "  " + type + " "
8762                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8763                                : a.info.name) + ":");
8764                Log.v(TAG, "    Class=" + a.info.name);
8765            }
8766            final int NI = a.intents.size();
8767            for (int j=0; j<NI; j++) {
8768                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8769                if (DEBUG_SHOW_INFO) {
8770                    Log.v(TAG, "    IntentFilter:");
8771                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8772                }
8773                removeFilter(intent);
8774            }
8775        }
8776
8777        @Override
8778        protected boolean allowFilterResult(
8779                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8780            ActivityInfo filterAi = filter.activity.info;
8781            for (int i=dest.size()-1; i>=0; i--) {
8782                ActivityInfo destAi = dest.get(i).activityInfo;
8783                if (destAi.name == filterAi.name
8784                        && destAi.packageName == filterAi.packageName) {
8785                    return false;
8786                }
8787            }
8788            return true;
8789        }
8790
8791        @Override
8792        protected ActivityIntentInfo[] newArray(int size) {
8793            return new ActivityIntentInfo[size];
8794        }
8795
8796        @Override
8797        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8798            if (!sUserManager.exists(userId)) return true;
8799            PackageParser.Package p = filter.activity.owner;
8800            if (p != null) {
8801                PackageSetting ps = (PackageSetting)p.mExtras;
8802                if (ps != null) {
8803                    // System apps are never considered stopped for purposes of
8804                    // filtering, because there may be no way for the user to
8805                    // actually re-launch them.
8806                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8807                            && ps.getStopped(userId);
8808                }
8809            }
8810            return false;
8811        }
8812
8813        @Override
8814        protected boolean isPackageForFilter(String packageName,
8815                PackageParser.ActivityIntentInfo info) {
8816            return packageName.equals(info.activity.owner.packageName);
8817        }
8818
8819        @Override
8820        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8821                int match, int userId) {
8822            if (!sUserManager.exists(userId)) return null;
8823            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8824                return null;
8825            }
8826            final PackageParser.Activity activity = info.activity;
8827            if (mSafeMode && (activity.info.applicationInfo.flags
8828                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8829                return null;
8830            }
8831            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8832            if (ps == null) {
8833                return null;
8834            }
8835            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8836                    ps.readUserState(userId), userId);
8837            if (ai == null) {
8838                return null;
8839            }
8840            final ResolveInfo res = new ResolveInfo();
8841            res.activityInfo = ai;
8842            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8843                res.filter = info;
8844            }
8845            if (info != null) {
8846                res.handleAllWebDataURI = info.handleAllWebDataURI();
8847            }
8848            res.priority = info.getPriority();
8849            res.preferredOrder = activity.owner.mPreferredOrder;
8850            //System.out.println("Result: " + res.activityInfo.className +
8851            //                   " = " + res.priority);
8852            res.match = match;
8853            res.isDefault = info.hasDefault;
8854            res.labelRes = info.labelRes;
8855            res.nonLocalizedLabel = info.nonLocalizedLabel;
8856            if (userNeedsBadging(userId)) {
8857                res.noResourceId = true;
8858            } else {
8859                res.icon = info.icon;
8860            }
8861            res.iconResourceId = info.icon;
8862            res.system = res.activityInfo.applicationInfo.isSystemApp();
8863            return res;
8864        }
8865
8866        @Override
8867        protected void sortResults(List<ResolveInfo> results) {
8868            Collections.sort(results, mResolvePrioritySorter);
8869        }
8870
8871        @Override
8872        protected void dumpFilter(PrintWriter out, String prefix,
8873                PackageParser.ActivityIntentInfo filter) {
8874            out.print(prefix); out.print(
8875                    Integer.toHexString(System.identityHashCode(filter.activity)));
8876                    out.print(' ');
8877                    filter.activity.printComponentShortName(out);
8878                    out.print(" filter ");
8879                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8880        }
8881
8882        @Override
8883        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8884            return filter.activity;
8885        }
8886
8887        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8888            PackageParser.Activity activity = (PackageParser.Activity)label;
8889            out.print(prefix); out.print(
8890                    Integer.toHexString(System.identityHashCode(activity)));
8891                    out.print(' ');
8892                    activity.printComponentShortName(out);
8893            if (count > 1) {
8894                out.print(" ("); out.print(count); out.print(" filters)");
8895            }
8896            out.println();
8897        }
8898
8899//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8900//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8901//            final List<ResolveInfo> retList = Lists.newArrayList();
8902//            while (i.hasNext()) {
8903//                final ResolveInfo resolveInfo = i.next();
8904//                if (isEnabledLP(resolveInfo.activityInfo)) {
8905//                    retList.add(resolveInfo);
8906//                }
8907//            }
8908//            return retList;
8909//        }
8910
8911        // Keys are String (activity class name), values are Activity.
8912        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8913                = new ArrayMap<ComponentName, PackageParser.Activity>();
8914        private int mFlags;
8915    }
8916
8917    private final class ServiceIntentResolver
8918            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8919        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8920                boolean defaultOnly, int userId) {
8921            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8922            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8923        }
8924
8925        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8926                int userId) {
8927            if (!sUserManager.exists(userId)) return null;
8928            mFlags = flags;
8929            return super.queryIntent(intent, resolvedType,
8930                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8931        }
8932
8933        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8934                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8935            if (!sUserManager.exists(userId)) return null;
8936            if (packageServices == null) {
8937                return null;
8938            }
8939            mFlags = flags;
8940            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8941            final int N = packageServices.size();
8942            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8943                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8944
8945            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8946            for (int i = 0; i < N; ++i) {
8947                intentFilters = packageServices.get(i).intents;
8948                if (intentFilters != null && intentFilters.size() > 0) {
8949                    PackageParser.ServiceIntentInfo[] array =
8950                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8951                    intentFilters.toArray(array);
8952                    listCut.add(array);
8953                }
8954            }
8955            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8956        }
8957
8958        public final void addService(PackageParser.Service s) {
8959            mServices.put(s.getComponentName(), s);
8960            if (DEBUG_SHOW_INFO) {
8961                Log.v(TAG, "  "
8962                        + (s.info.nonLocalizedLabel != null
8963                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8964                Log.v(TAG, "    Class=" + s.info.name);
8965            }
8966            final int NI = s.intents.size();
8967            int j;
8968            for (j=0; j<NI; j++) {
8969                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8970                if (DEBUG_SHOW_INFO) {
8971                    Log.v(TAG, "    IntentFilter:");
8972                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8973                }
8974                if (!intent.debugCheck()) {
8975                    Log.w(TAG, "==> For Service " + s.info.name);
8976                }
8977                addFilter(intent);
8978            }
8979        }
8980
8981        public final void removeService(PackageParser.Service s) {
8982            mServices.remove(s.getComponentName());
8983            if (DEBUG_SHOW_INFO) {
8984                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8985                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8986                Log.v(TAG, "    Class=" + s.info.name);
8987            }
8988            final int NI = s.intents.size();
8989            int j;
8990            for (j=0; j<NI; j++) {
8991                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8992                if (DEBUG_SHOW_INFO) {
8993                    Log.v(TAG, "    IntentFilter:");
8994                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8995                }
8996                removeFilter(intent);
8997            }
8998        }
8999
9000        @Override
9001        protected boolean allowFilterResult(
9002                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9003            ServiceInfo filterSi = filter.service.info;
9004            for (int i=dest.size()-1; i>=0; i--) {
9005                ServiceInfo destAi = dest.get(i).serviceInfo;
9006                if (destAi.name == filterSi.name
9007                        && destAi.packageName == filterSi.packageName) {
9008                    return false;
9009                }
9010            }
9011            return true;
9012        }
9013
9014        @Override
9015        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9016            return new PackageParser.ServiceIntentInfo[size];
9017        }
9018
9019        @Override
9020        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9021            if (!sUserManager.exists(userId)) return true;
9022            PackageParser.Package p = filter.service.owner;
9023            if (p != null) {
9024                PackageSetting ps = (PackageSetting)p.mExtras;
9025                if (ps != null) {
9026                    // System apps are never considered stopped for purposes of
9027                    // filtering, because there may be no way for the user to
9028                    // actually re-launch them.
9029                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9030                            && ps.getStopped(userId);
9031                }
9032            }
9033            return false;
9034        }
9035
9036        @Override
9037        protected boolean isPackageForFilter(String packageName,
9038                PackageParser.ServiceIntentInfo info) {
9039            return packageName.equals(info.service.owner.packageName);
9040        }
9041
9042        @Override
9043        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9044                int match, int userId) {
9045            if (!sUserManager.exists(userId)) return null;
9046            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9047            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9048                return null;
9049            }
9050            final PackageParser.Service service = info.service;
9051            if (mSafeMode && (service.info.applicationInfo.flags
9052                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9053                return null;
9054            }
9055            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9056            if (ps == null) {
9057                return null;
9058            }
9059            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9060                    ps.readUserState(userId), userId);
9061            if (si == null) {
9062                return null;
9063            }
9064            final ResolveInfo res = new ResolveInfo();
9065            res.serviceInfo = si;
9066            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9067                res.filter = filter;
9068            }
9069            res.priority = info.getPriority();
9070            res.preferredOrder = service.owner.mPreferredOrder;
9071            res.match = match;
9072            res.isDefault = info.hasDefault;
9073            res.labelRes = info.labelRes;
9074            res.nonLocalizedLabel = info.nonLocalizedLabel;
9075            res.icon = info.icon;
9076            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9077            return res;
9078        }
9079
9080        @Override
9081        protected void sortResults(List<ResolveInfo> results) {
9082            Collections.sort(results, mResolvePrioritySorter);
9083        }
9084
9085        @Override
9086        protected void dumpFilter(PrintWriter out, String prefix,
9087                PackageParser.ServiceIntentInfo filter) {
9088            out.print(prefix); out.print(
9089                    Integer.toHexString(System.identityHashCode(filter.service)));
9090                    out.print(' ');
9091                    filter.service.printComponentShortName(out);
9092                    out.print(" filter ");
9093                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9094        }
9095
9096        @Override
9097        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9098            return filter.service;
9099        }
9100
9101        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9102            PackageParser.Service service = (PackageParser.Service)label;
9103            out.print(prefix); out.print(
9104                    Integer.toHexString(System.identityHashCode(service)));
9105                    out.print(' ');
9106                    service.printComponentShortName(out);
9107            if (count > 1) {
9108                out.print(" ("); out.print(count); out.print(" filters)");
9109            }
9110            out.println();
9111        }
9112
9113//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9114//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9115//            final List<ResolveInfo> retList = Lists.newArrayList();
9116//            while (i.hasNext()) {
9117//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9118//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9119//                    retList.add(resolveInfo);
9120//                }
9121//            }
9122//            return retList;
9123//        }
9124
9125        // Keys are String (activity class name), values are Activity.
9126        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9127                = new ArrayMap<ComponentName, PackageParser.Service>();
9128        private int mFlags;
9129    };
9130
9131    private final class ProviderIntentResolver
9132            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9133        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9134                boolean defaultOnly, int userId) {
9135            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9136            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9137        }
9138
9139        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9140                int userId) {
9141            if (!sUserManager.exists(userId))
9142                return null;
9143            mFlags = flags;
9144            return super.queryIntent(intent, resolvedType,
9145                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9146        }
9147
9148        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9149                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9150            if (!sUserManager.exists(userId))
9151                return null;
9152            if (packageProviders == null) {
9153                return null;
9154            }
9155            mFlags = flags;
9156            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9157            final int N = packageProviders.size();
9158            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9159                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9160
9161            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9162            for (int i = 0; i < N; ++i) {
9163                intentFilters = packageProviders.get(i).intents;
9164                if (intentFilters != null && intentFilters.size() > 0) {
9165                    PackageParser.ProviderIntentInfo[] array =
9166                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9167                    intentFilters.toArray(array);
9168                    listCut.add(array);
9169                }
9170            }
9171            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9172        }
9173
9174        public final void addProvider(PackageParser.Provider p) {
9175            if (mProviders.containsKey(p.getComponentName())) {
9176                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9177                return;
9178            }
9179
9180            mProviders.put(p.getComponentName(), p);
9181            if (DEBUG_SHOW_INFO) {
9182                Log.v(TAG, "  "
9183                        + (p.info.nonLocalizedLabel != null
9184                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9185                Log.v(TAG, "    Class=" + p.info.name);
9186            }
9187            final int NI = p.intents.size();
9188            int j;
9189            for (j = 0; j < NI; j++) {
9190                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9191                if (DEBUG_SHOW_INFO) {
9192                    Log.v(TAG, "    IntentFilter:");
9193                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9194                }
9195                if (!intent.debugCheck()) {
9196                    Log.w(TAG, "==> For Provider " + p.info.name);
9197                }
9198                addFilter(intent);
9199            }
9200        }
9201
9202        public final void removeProvider(PackageParser.Provider p) {
9203            mProviders.remove(p.getComponentName());
9204            if (DEBUG_SHOW_INFO) {
9205                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9206                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9207                Log.v(TAG, "    Class=" + p.info.name);
9208            }
9209            final int NI = p.intents.size();
9210            int j;
9211            for (j = 0; j < NI; j++) {
9212                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9213                if (DEBUG_SHOW_INFO) {
9214                    Log.v(TAG, "    IntentFilter:");
9215                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9216                }
9217                removeFilter(intent);
9218            }
9219        }
9220
9221        @Override
9222        protected boolean allowFilterResult(
9223                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9224            ProviderInfo filterPi = filter.provider.info;
9225            for (int i = dest.size() - 1; i >= 0; i--) {
9226                ProviderInfo destPi = dest.get(i).providerInfo;
9227                if (destPi.name == filterPi.name
9228                        && destPi.packageName == filterPi.packageName) {
9229                    return false;
9230                }
9231            }
9232            return true;
9233        }
9234
9235        @Override
9236        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9237            return new PackageParser.ProviderIntentInfo[size];
9238        }
9239
9240        @Override
9241        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9242            if (!sUserManager.exists(userId))
9243                return true;
9244            PackageParser.Package p = filter.provider.owner;
9245            if (p != null) {
9246                PackageSetting ps = (PackageSetting) p.mExtras;
9247                if (ps != null) {
9248                    // System apps are never considered stopped for purposes of
9249                    // filtering, because there may be no way for the user to
9250                    // actually re-launch them.
9251                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9252                            && ps.getStopped(userId);
9253                }
9254            }
9255            return false;
9256        }
9257
9258        @Override
9259        protected boolean isPackageForFilter(String packageName,
9260                PackageParser.ProviderIntentInfo info) {
9261            return packageName.equals(info.provider.owner.packageName);
9262        }
9263
9264        @Override
9265        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9266                int match, int userId) {
9267            if (!sUserManager.exists(userId))
9268                return null;
9269            final PackageParser.ProviderIntentInfo info = filter;
9270            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9271                return null;
9272            }
9273            final PackageParser.Provider provider = info.provider;
9274            if (mSafeMode && (provider.info.applicationInfo.flags
9275                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9276                return null;
9277            }
9278            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9279            if (ps == null) {
9280                return null;
9281            }
9282            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9283                    ps.readUserState(userId), userId);
9284            if (pi == null) {
9285                return null;
9286            }
9287            final ResolveInfo res = new ResolveInfo();
9288            res.providerInfo = pi;
9289            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9290                res.filter = filter;
9291            }
9292            res.priority = info.getPriority();
9293            res.preferredOrder = provider.owner.mPreferredOrder;
9294            res.match = match;
9295            res.isDefault = info.hasDefault;
9296            res.labelRes = info.labelRes;
9297            res.nonLocalizedLabel = info.nonLocalizedLabel;
9298            res.icon = info.icon;
9299            res.system = res.providerInfo.applicationInfo.isSystemApp();
9300            return res;
9301        }
9302
9303        @Override
9304        protected void sortResults(List<ResolveInfo> results) {
9305            Collections.sort(results, mResolvePrioritySorter);
9306        }
9307
9308        @Override
9309        protected void dumpFilter(PrintWriter out, String prefix,
9310                PackageParser.ProviderIntentInfo filter) {
9311            out.print(prefix);
9312            out.print(
9313                    Integer.toHexString(System.identityHashCode(filter.provider)));
9314            out.print(' ');
9315            filter.provider.printComponentShortName(out);
9316            out.print(" filter ");
9317            out.println(Integer.toHexString(System.identityHashCode(filter)));
9318        }
9319
9320        @Override
9321        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9322            return filter.provider;
9323        }
9324
9325        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9326            PackageParser.Provider provider = (PackageParser.Provider)label;
9327            out.print(prefix); out.print(
9328                    Integer.toHexString(System.identityHashCode(provider)));
9329                    out.print(' ');
9330                    provider.printComponentShortName(out);
9331            if (count > 1) {
9332                out.print(" ("); out.print(count); out.print(" filters)");
9333            }
9334            out.println();
9335        }
9336
9337        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9338                = new ArrayMap<ComponentName, PackageParser.Provider>();
9339        private int mFlags;
9340    };
9341
9342    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9343            new Comparator<ResolveInfo>() {
9344        public int compare(ResolveInfo r1, ResolveInfo r2) {
9345            int v1 = r1.priority;
9346            int v2 = r2.priority;
9347            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9348            if (v1 != v2) {
9349                return (v1 > v2) ? -1 : 1;
9350            }
9351            v1 = r1.preferredOrder;
9352            v2 = r2.preferredOrder;
9353            if (v1 != v2) {
9354                return (v1 > v2) ? -1 : 1;
9355            }
9356            if (r1.isDefault != r2.isDefault) {
9357                return r1.isDefault ? -1 : 1;
9358            }
9359            v1 = r1.match;
9360            v2 = r2.match;
9361            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9362            if (v1 != v2) {
9363                return (v1 > v2) ? -1 : 1;
9364            }
9365            if (r1.system != r2.system) {
9366                return r1.system ? -1 : 1;
9367            }
9368            return 0;
9369        }
9370    };
9371
9372    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9373            new Comparator<ProviderInfo>() {
9374        public int compare(ProviderInfo p1, ProviderInfo p2) {
9375            final int v1 = p1.initOrder;
9376            final int v2 = p2.initOrder;
9377            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9378        }
9379    };
9380
9381    final void sendPackageBroadcast(final String action, final String pkg,
9382            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9383            final int[] userIds) {
9384        mHandler.post(new Runnable() {
9385            @Override
9386            public void run() {
9387                try {
9388                    final IActivityManager am = ActivityManagerNative.getDefault();
9389                    if (am == null) return;
9390                    final int[] resolvedUserIds;
9391                    if (userIds == null) {
9392                        resolvedUserIds = am.getRunningUserIds();
9393                    } else {
9394                        resolvedUserIds = userIds;
9395                    }
9396                    for (int id : resolvedUserIds) {
9397                        final Intent intent = new Intent(action,
9398                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9399                        if (extras != null) {
9400                            intent.putExtras(extras);
9401                        }
9402                        if (targetPkg != null) {
9403                            intent.setPackage(targetPkg);
9404                        }
9405                        // Modify the UID when posting to other users
9406                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9407                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9408                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9409                            intent.putExtra(Intent.EXTRA_UID, uid);
9410                        }
9411                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9412                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9413                        if (DEBUG_BROADCASTS) {
9414                            RuntimeException here = new RuntimeException("here");
9415                            here.fillInStackTrace();
9416                            Slog.d(TAG, "Sending to user " + id + ": "
9417                                    + intent.toShortString(false, true, false, false)
9418                                    + " " + intent.getExtras(), here);
9419                        }
9420                        am.broadcastIntent(null, intent, null, finishedReceiver,
9421                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9422                                null, finishedReceiver != null, false, id);
9423                    }
9424                } catch (RemoteException ex) {
9425                }
9426            }
9427        });
9428    }
9429
9430    /**
9431     * Check if the external storage media is available. This is true if there
9432     * is a mounted external storage medium or if the external storage is
9433     * emulated.
9434     */
9435    private boolean isExternalMediaAvailable() {
9436        return mMediaMounted || Environment.isExternalStorageEmulated();
9437    }
9438
9439    @Override
9440    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9441        // writer
9442        synchronized (mPackages) {
9443            if (!isExternalMediaAvailable()) {
9444                // If the external storage is no longer mounted at this point,
9445                // the caller may not have been able to delete all of this
9446                // packages files and can not delete any more.  Bail.
9447                return null;
9448            }
9449            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9450            if (lastPackage != null) {
9451                pkgs.remove(lastPackage);
9452            }
9453            if (pkgs.size() > 0) {
9454                return pkgs.get(0);
9455            }
9456        }
9457        return null;
9458    }
9459
9460    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9461        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9462                userId, andCode ? 1 : 0, packageName);
9463        if (mSystemReady) {
9464            msg.sendToTarget();
9465        } else {
9466            if (mPostSystemReadyMessages == null) {
9467                mPostSystemReadyMessages = new ArrayList<>();
9468            }
9469            mPostSystemReadyMessages.add(msg);
9470        }
9471    }
9472
9473    void startCleaningPackages() {
9474        // reader
9475        synchronized (mPackages) {
9476            if (!isExternalMediaAvailable()) {
9477                return;
9478            }
9479            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9480                return;
9481            }
9482        }
9483        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9484        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9485        IActivityManager am = ActivityManagerNative.getDefault();
9486        if (am != null) {
9487            try {
9488                am.startService(null, intent, null, mContext.getOpPackageName(),
9489                        UserHandle.USER_OWNER);
9490            } catch (RemoteException e) {
9491            }
9492        }
9493    }
9494
9495    @Override
9496    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9497            int installFlags, String installerPackageName, VerificationParams verificationParams,
9498            String packageAbiOverride) {
9499        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9500                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9501    }
9502
9503    @Override
9504    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9505            int installFlags, String installerPackageName, VerificationParams verificationParams,
9506            String packageAbiOverride, int userId) {
9507        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9508
9509        final int callingUid = Binder.getCallingUid();
9510        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9511
9512        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9513            try {
9514                if (observer != null) {
9515                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9516                }
9517            } catch (RemoteException re) {
9518            }
9519            return;
9520        }
9521
9522        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9523            installFlags |= PackageManager.INSTALL_FROM_ADB;
9524
9525        } else {
9526            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9527            // about installerPackageName.
9528
9529            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9530            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9531        }
9532
9533        UserHandle user;
9534        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9535            user = UserHandle.ALL;
9536        } else {
9537            user = new UserHandle(userId);
9538        }
9539
9540        // Only system components can circumvent runtime permissions when installing.
9541        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9542                && mContext.checkCallingOrSelfPermission(Manifest.permission
9543                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9544            throw new SecurityException("You need the "
9545                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9546                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9547        }
9548
9549        verificationParams.setInstallerUid(callingUid);
9550
9551        final File originFile = new File(originPath);
9552        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9553
9554        final Message msg = mHandler.obtainMessage(INIT_COPY);
9555        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9556                null, verificationParams, user, packageAbiOverride, null);
9557        mHandler.sendMessage(msg);
9558    }
9559
9560    void installStage(String packageName, File stagedDir, String stagedCid,
9561            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9562            String installerPackageName, int installerUid, UserHandle user) {
9563        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9564                params.referrerUri, installerUid, null);
9565        verifParams.setInstallerUid(installerUid);
9566
9567        final OriginInfo origin;
9568        if (stagedDir != null) {
9569            origin = OriginInfo.fromStagedFile(stagedDir);
9570        } else {
9571            origin = OriginInfo.fromStagedContainer(stagedCid);
9572        }
9573
9574        final Message msg = mHandler.obtainMessage(INIT_COPY);
9575        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9576                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9577                params.grantedRuntimePermissions);
9578        mHandler.sendMessage(msg);
9579    }
9580
9581    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9582        Bundle extras = new Bundle(1);
9583        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9584
9585        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9586                packageName, extras, null, null, new int[] {userId});
9587        try {
9588            IActivityManager am = ActivityManagerNative.getDefault();
9589            final boolean isSystem =
9590                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9591            if (isSystem && am.isUserRunning(userId, false)) {
9592                // The just-installed/enabled app is bundled on the system, so presumed
9593                // to be able to run automatically without needing an explicit launch.
9594                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9595                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9596                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9597                        .setPackage(packageName);
9598                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9599                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9600            }
9601        } catch (RemoteException e) {
9602            // shouldn't happen
9603            Slog.w(TAG, "Unable to bootstrap installed package", e);
9604        }
9605    }
9606
9607    @Override
9608    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9609            int userId) {
9610        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9611        PackageSetting pkgSetting;
9612        final int uid = Binder.getCallingUid();
9613        enforceCrossUserPermission(uid, userId, true, true,
9614                "setApplicationHiddenSetting for user " + userId);
9615
9616        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9617            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9618            return false;
9619        }
9620
9621        long callingId = Binder.clearCallingIdentity();
9622        try {
9623            boolean sendAdded = false;
9624            boolean sendRemoved = false;
9625            // writer
9626            synchronized (mPackages) {
9627                pkgSetting = mSettings.mPackages.get(packageName);
9628                if (pkgSetting == null) {
9629                    return false;
9630                }
9631                if (pkgSetting.getHidden(userId) != hidden) {
9632                    pkgSetting.setHidden(hidden, userId);
9633                    mSettings.writePackageRestrictionsLPr(userId);
9634                    if (hidden) {
9635                        sendRemoved = true;
9636                    } else {
9637                        sendAdded = true;
9638                    }
9639                }
9640            }
9641            if (sendAdded) {
9642                sendPackageAddedForUser(packageName, pkgSetting, userId);
9643                return true;
9644            }
9645            if (sendRemoved) {
9646                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9647                        "hiding pkg");
9648                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9649                return true;
9650            }
9651        } finally {
9652            Binder.restoreCallingIdentity(callingId);
9653        }
9654        return false;
9655    }
9656
9657    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9658            int userId) {
9659        final PackageRemovedInfo info = new PackageRemovedInfo();
9660        info.removedPackage = packageName;
9661        info.removedUsers = new int[] {userId};
9662        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9663        info.sendBroadcast(false, false, false);
9664    }
9665
9666    /**
9667     * Returns true if application is not found or there was an error. Otherwise it returns
9668     * the hidden state of the package for the given user.
9669     */
9670    @Override
9671    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9672        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9673        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9674                false, "getApplicationHidden for user " + userId);
9675        PackageSetting pkgSetting;
9676        long callingId = Binder.clearCallingIdentity();
9677        try {
9678            // writer
9679            synchronized (mPackages) {
9680                pkgSetting = mSettings.mPackages.get(packageName);
9681                if (pkgSetting == null) {
9682                    return true;
9683                }
9684                return pkgSetting.getHidden(userId);
9685            }
9686        } finally {
9687            Binder.restoreCallingIdentity(callingId);
9688        }
9689    }
9690
9691    /**
9692     * @hide
9693     */
9694    @Override
9695    public int installExistingPackageAsUser(String packageName, int userId) {
9696        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9697                null);
9698        PackageSetting pkgSetting;
9699        final int uid = Binder.getCallingUid();
9700        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9701                + userId);
9702        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9703            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9704        }
9705
9706        long callingId = Binder.clearCallingIdentity();
9707        try {
9708            boolean sendAdded = false;
9709
9710            // writer
9711            synchronized (mPackages) {
9712                pkgSetting = mSettings.mPackages.get(packageName);
9713                if (pkgSetting == null) {
9714                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9715                }
9716                if (!pkgSetting.getInstalled(userId)) {
9717                    pkgSetting.setInstalled(true, userId);
9718                    pkgSetting.setHidden(false, userId);
9719                    mSettings.writePackageRestrictionsLPr(userId);
9720                    sendAdded = true;
9721                }
9722            }
9723
9724            if (sendAdded) {
9725                sendPackageAddedForUser(packageName, pkgSetting, userId);
9726            }
9727        } finally {
9728            Binder.restoreCallingIdentity(callingId);
9729        }
9730
9731        return PackageManager.INSTALL_SUCCEEDED;
9732    }
9733
9734    boolean isUserRestricted(int userId, String restrictionKey) {
9735        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9736        if (restrictions.getBoolean(restrictionKey, false)) {
9737            Log.w(TAG, "User is restricted: " + restrictionKey);
9738            return true;
9739        }
9740        return false;
9741    }
9742
9743    @Override
9744    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9745        mContext.enforceCallingOrSelfPermission(
9746                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9747                "Only package verification agents can verify applications");
9748
9749        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9750        final PackageVerificationResponse response = new PackageVerificationResponse(
9751                verificationCode, Binder.getCallingUid());
9752        msg.arg1 = id;
9753        msg.obj = response;
9754        mHandler.sendMessage(msg);
9755    }
9756
9757    @Override
9758    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9759            long millisecondsToDelay) {
9760        mContext.enforceCallingOrSelfPermission(
9761                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9762                "Only package verification agents can extend verification timeouts");
9763
9764        final PackageVerificationState state = mPendingVerification.get(id);
9765        final PackageVerificationResponse response = new PackageVerificationResponse(
9766                verificationCodeAtTimeout, Binder.getCallingUid());
9767
9768        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9769            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9770        }
9771        if (millisecondsToDelay < 0) {
9772            millisecondsToDelay = 0;
9773        }
9774        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9775                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9776            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9777        }
9778
9779        if ((state != null) && !state.timeoutExtended()) {
9780            state.extendTimeout();
9781
9782            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9783            msg.arg1 = id;
9784            msg.obj = response;
9785            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9786        }
9787    }
9788
9789    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9790            int verificationCode, UserHandle user) {
9791        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9792        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9793        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9794        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9795        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9796
9797        mContext.sendBroadcastAsUser(intent, user,
9798                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9799    }
9800
9801    private ComponentName matchComponentForVerifier(String packageName,
9802            List<ResolveInfo> receivers) {
9803        ActivityInfo targetReceiver = null;
9804
9805        final int NR = receivers.size();
9806        for (int i = 0; i < NR; i++) {
9807            final ResolveInfo info = receivers.get(i);
9808            if (info.activityInfo == null) {
9809                continue;
9810            }
9811
9812            if (packageName.equals(info.activityInfo.packageName)) {
9813                targetReceiver = info.activityInfo;
9814                break;
9815            }
9816        }
9817
9818        if (targetReceiver == null) {
9819            return null;
9820        }
9821
9822        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9823    }
9824
9825    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9826            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9827        if (pkgInfo.verifiers.length == 0) {
9828            return null;
9829        }
9830
9831        final int N = pkgInfo.verifiers.length;
9832        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9833        for (int i = 0; i < N; i++) {
9834            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9835
9836            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9837                    receivers);
9838            if (comp == null) {
9839                continue;
9840            }
9841
9842            final int verifierUid = getUidForVerifier(verifierInfo);
9843            if (verifierUid == -1) {
9844                continue;
9845            }
9846
9847            if (DEBUG_VERIFY) {
9848                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9849                        + " with the correct signature");
9850            }
9851            sufficientVerifiers.add(comp);
9852            verificationState.addSufficientVerifier(verifierUid);
9853        }
9854
9855        return sufficientVerifiers;
9856    }
9857
9858    private int getUidForVerifier(VerifierInfo verifierInfo) {
9859        synchronized (mPackages) {
9860            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9861            if (pkg == null) {
9862                return -1;
9863            } else if (pkg.mSignatures.length != 1) {
9864                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9865                        + " has more than one signature; ignoring");
9866                return -1;
9867            }
9868
9869            /*
9870             * If the public key of the package's signature does not match
9871             * our expected public key, then this is a different package and
9872             * we should skip.
9873             */
9874
9875            final byte[] expectedPublicKey;
9876            try {
9877                final Signature verifierSig = pkg.mSignatures[0];
9878                final PublicKey publicKey = verifierSig.getPublicKey();
9879                expectedPublicKey = publicKey.getEncoded();
9880            } catch (CertificateException e) {
9881                return -1;
9882            }
9883
9884            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9885
9886            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9887                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9888                        + " does not have the expected public key; ignoring");
9889                return -1;
9890            }
9891
9892            return pkg.applicationInfo.uid;
9893        }
9894    }
9895
9896    @Override
9897    public void finishPackageInstall(int token) {
9898        enforceSystemOrRoot("Only the system is allowed to finish installs");
9899
9900        if (DEBUG_INSTALL) {
9901            Slog.v(TAG, "BM finishing package install for " + token);
9902        }
9903
9904        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9905        mHandler.sendMessage(msg);
9906    }
9907
9908    /**
9909     * Get the verification agent timeout.
9910     *
9911     * @return verification timeout in milliseconds
9912     */
9913    private long getVerificationTimeout() {
9914        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9915                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9916                DEFAULT_VERIFICATION_TIMEOUT);
9917    }
9918
9919    /**
9920     * Get the default verification agent response code.
9921     *
9922     * @return default verification response code
9923     */
9924    private int getDefaultVerificationResponse() {
9925        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9926                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9927                DEFAULT_VERIFICATION_RESPONSE);
9928    }
9929
9930    /**
9931     * Check whether or not package verification has been enabled.
9932     *
9933     * @return true if verification should be performed
9934     */
9935    private boolean isVerificationEnabled(int userId, int installFlags) {
9936        if (!DEFAULT_VERIFY_ENABLE) {
9937            return false;
9938        }
9939
9940        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9941
9942        // Check if installing from ADB
9943        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9944            // Do not run verification in a test harness environment
9945            if (ActivityManager.isRunningInTestHarness()) {
9946                return false;
9947            }
9948            if (ensureVerifyAppsEnabled) {
9949                return true;
9950            }
9951            // Check if the developer does not want package verification for ADB installs
9952            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9953                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9954                return false;
9955            }
9956        }
9957
9958        if (ensureVerifyAppsEnabled) {
9959            return true;
9960        }
9961
9962        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9963                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9964    }
9965
9966    @Override
9967    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9968            throws RemoteException {
9969        mContext.enforceCallingOrSelfPermission(
9970                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9971                "Only intentfilter verification agents can verify applications");
9972
9973        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9974        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9975                Binder.getCallingUid(), verificationCode, failedDomains);
9976        msg.arg1 = id;
9977        msg.obj = response;
9978        mHandler.sendMessage(msg);
9979    }
9980
9981    @Override
9982    public int getIntentVerificationStatus(String packageName, int userId) {
9983        synchronized (mPackages) {
9984            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9985        }
9986    }
9987
9988    @Override
9989    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9990        mContext.enforceCallingOrSelfPermission(
9991                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9992
9993        boolean result = false;
9994        synchronized (mPackages) {
9995            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9996        }
9997        if (result) {
9998            scheduleWritePackageRestrictionsLocked(userId);
9999        }
10000        return result;
10001    }
10002
10003    @Override
10004    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10005        synchronized (mPackages) {
10006            return mSettings.getIntentFilterVerificationsLPr(packageName);
10007        }
10008    }
10009
10010    @Override
10011    public List<IntentFilter> getAllIntentFilters(String packageName) {
10012        if (TextUtils.isEmpty(packageName)) {
10013            return Collections.<IntentFilter>emptyList();
10014        }
10015        synchronized (mPackages) {
10016            PackageParser.Package pkg = mPackages.get(packageName);
10017            if (pkg == null || pkg.activities == null) {
10018                return Collections.<IntentFilter>emptyList();
10019            }
10020            final int count = pkg.activities.size();
10021            ArrayList<IntentFilter> result = new ArrayList<>();
10022            for (int n=0; n<count; n++) {
10023                PackageParser.Activity activity = pkg.activities.get(n);
10024                if (activity.intents != null || activity.intents.size() > 0) {
10025                    result.addAll(activity.intents);
10026                }
10027            }
10028            return result;
10029        }
10030    }
10031
10032    @Override
10033    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10034        mContext.enforceCallingOrSelfPermission(
10035                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10036
10037        synchronized (mPackages) {
10038            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10039            if (packageName != null) {
10040                result |= updateIntentVerificationStatus(packageName,
10041                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10042                        userId);
10043                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10044                        packageName, userId);
10045            }
10046            return result;
10047        }
10048    }
10049
10050    @Override
10051    public String getDefaultBrowserPackageName(int userId) {
10052        synchronized (mPackages) {
10053            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10054        }
10055    }
10056
10057    /**
10058     * Get the "allow unknown sources" setting.
10059     *
10060     * @return the current "allow unknown sources" setting
10061     */
10062    private int getUnknownSourcesSettings() {
10063        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10064                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10065                -1);
10066    }
10067
10068    @Override
10069    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10070        final int uid = Binder.getCallingUid();
10071        // writer
10072        synchronized (mPackages) {
10073            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10074            if (targetPackageSetting == null) {
10075                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10076            }
10077
10078            PackageSetting installerPackageSetting;
10079            if (installerPackageName != null) {
10080                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10081                if (installerPackageSetting == null) {
10082                    throw new IllegalArgumentException("Unknown installer package: "
10083                            + installerPackageName);
10084                }
10085            } else {
10086                installerPackageSetting = null;
10087            }
10088
10089            Signature[] callerSignature;
10090            Object obj = mSettings.getUserIdLPr(uid);
10091            if (obj != null) {
10092                if (obj instanceof SharedUserSetting) {
10093                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10094                } else if (obj instanceof PackageSetting) {
10095                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10096                } else {
10097                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10098                }
10099            } else {
10100                throw new SecurityException("Unknown calling uid " + uid);
10101            }
10102
10103            // Verify: can't set installerPackageName to a package that is
10104            // not signed with the same cert as the caller.
10105            if (installerPackageSetting != null) {
10106                if (compareSignatures(callerSignature,
10107                        installerPackageSetting.signatures.mSignatures)
10108                        != PackageManager.SIGNATURE_MATCH) {
10109                    throw new SecurityException(
10110                            "Caller does not have same cert as new installer package "
10111                            + installerPackageName);
10112                }
10113            }
10114
10115            // Verify: if target already has an installer package, it must
10116            // be signed with the same cert as the caller.
10117            if (targetPackageSetting.installerPackageName != null) {
10118                PackageSetting setting = mSettings.mPackages.get(
10119                        targetPackageSetting.installerPackageName);
10120                // If the currently set package isn't valid, then it's always
10121                // okay to change it.
10122                if (setting != null) {
10123                    if (compareSignatures(callerSignature,
10124                            setting.signatures.mSignatures)
10125                            != PackageManager.SIGNATURE_MATCH) {
10126                        throw new SecurityException(
10127                                "Caller does not have same cert as old installer package "
10128                                + targetPackageSetting.installerPackageName);
10129                    }
10130                }
10131            }
10132
10133            // Okay!
10134            targetPackageSetting.installerPackageName = installerPackageName;
10135            scheduleWriteSettingsLocked();
10136        }
10137    }
10138
10139    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10140        // Queue up an async operation since the package installation may take a little while.
10141        mHandler.post(new Runnable() {
10142            public void run() {
10143                mHandler.removeCallbacks(this);
10144                 // Result object to be returned
10145                PackageInstalledInfo res = new PackageInstalledInfo();
10146                res.returnCode = currentStatus;
10147                res.uid = -1;
10148                res.pkg = null;
10149                res.removedInfo = new PackageRemovedInfo();
10150                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10151                    args.doPreInstall(res.returnCode);
10152                    synchronized (mInstallLock) {
10153                        installPackageLI(args, res);
10154                    }
10155                    args.doPostInstall(res.returnCode, res.uid);
10156                }
10157
10158                // A restore should be performed at this point if (a) the install
10159                // succeeded, (b) the operation is not an update, and (c) the new
10160                // package has not opted out of backup participation.
10161                final boolean update = res.removedInfo.removedPackage != null;
10162                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10163                boolean doRestore = !update
10164                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10165
10166                // Set up the post-install work request bookkeeping.  This will be used
10167                // and cleaned up by the post-install event handling regardless of whether
10168                // there's a restore pass performed.  Token values are >= 1.
10169                int token;
10170                if (mNextInstallToken < 0) mNextInstallToken = 1;
10171                token = mNextInstallToken++;
10172
10173                PostInstallData data = new PostInstallData(args, res);
10174                mRunningInstalls.put(token, data);
10175                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10176
10177                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10178                    // Pass responsibility to the Backup Manager.  It will perform a
10179                    // restore if appropriate, then pass responsibility back to the
10180                    // Package Manager to run the post-install observer callbacks
10181                    // and broadcasts.
10182                    IBackupManager bm = IBackupManager.Stub.asInterface(
10183                            ServiceManager.getService(Context.BACKUP_SERVICE));
10184                    if (bm != null) {
10185                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10186                                + " to BM for possible restore");
10187                        try {
10188                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10189                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10190                            } else {
10191                                doRestore = false;
10192                            }
10193                        } catch (RemoteException e) {
10194                            // can't happen; the backup manager is local
10195                        } catch (Exception e) {
10196                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10197                            doRestore = false;
10198                        }
10199                    } else {
10200                        Slog.e(TAG, "Backup Manager not found!");
10201                        doRestore = false;
10202                    }
10203                }
10204
10205                if (!doRestore) {
10206                    // No restore possible, or the Backup Manager was mysteriously not
10207                    // available -- just fire the post-install work request directly.
10208                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10209                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10210                    mHandler.sendMessage(msg);
10211                }
10212            }
10213        });
10214    }
10215
10216    private abstract class HandlerParams {
10217        private static final int MAX_RETRIES = 4;
10218
10219        /**
10220         * Number of times startCopy() has been attempted and had a non-fatal
10221         * error.
10222         */
10223        private int mRetries = 0;
10224
10225        /** User handle for the user requesting the information or installation. */
10226        private final UserHandle mUser;
10227
10228        HandlerParams(UserHandle user) {
10229            mUser = user;
10230        }
10231
10232        UserHandle getUser() {
10233            return mUser;
10234        }
10235
10236        final boolean startCopy() {
10237            boolean res;
10238            try {
10239                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10240
10241                if (++mRetries > MAX_RETRIES) {
10242                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10243                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10244                    handleServiceError();
10245                    return false;
10246                } else {
10247                    handleStartCopy();
10248                    res = true;
10249                }
10250            } catch (RemoteException e) {
10251                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10252                mHandler.sendEmptyMessage(MCS_RECONNECT);
10253                res = false;
10254            }
10255            handleReturnCode();
10256            return res;
10257        }
10258
10259        final void serviceError() {
10260            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10261            handleServiceError();
10262            handleReturnCode();
10263        }
10264
10265        abstract void handleStartCopy() throws RemoteException;
10266        abstract void handleServiceError();
10267        abstract void handleReturnCode();
10268    }
10269
10270    class MeasureParams extends HandlerParams {
10271        private final PackageStats mStats;
10272        private boolean mSuccess;
10273
10274        private final IPackageStatsObserver mObserver;
10275
10276        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10277            super(new UserHandle(stats.userHandle));
10278            mObserver = observer;
10279            mStats = stats;
10280        }
10281
10282        @Override
10283        public String toString() {
10284            return "MeasureParams{"
10285                + Integer.toHexString(System.identityHashCode(this))
10286                + " " + mStats.packageName + "}";
10287        }
10288
10289        @Override
10290        void handleStartCopy() throws RemoteException {
10291            synchronized (mInstallLock) {
10292                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10293            }
10294
10295            if (mSuccess) {
10296                final boolean mounted;
10297                if (Environment.isExternalStorageEmulated()) {
10298                    mounted = true;
10299                } else {
10300                    final String status = Environment.getExternalStorageState();
10301                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10302                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10303                }
10304
10305                if (mounted) {
10306                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10307
10308                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10309                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10310
10311                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10312                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10313
10314                    // Always subtract cache size, since it's a subdirectory
10315                    mStats.externalDataSize -= mStats.externalCacheSize;
10316
10317                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10318                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10319
10320                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10321                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10322                }
10323            }
10324        }
10325
10326        @Override
10327        void handleReturnCode() {
10328            if (mObserver != null) {
10329                try {
10330                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10331                } catch (RemoteException e) {
10332                    Slog.i(TAG, "Observer no longer exists.");
10333                }
10334            }
10335        }
10336
10337        @Override
10338        void handleServiceError() {
10339            Slog.e(TAG, "Could not measure application " + mStats.packageName
10340                            + " external storage");
10341        }
10342    }
10343
10344    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10345            throws RemoteException {
10346        long result = 0;
10347        for (File path : paths) {
10348            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10349        }
10350        return result;
10351    }
10352
10353    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10354        for (File path : paths) {
10355            try {
10356                mcs.clearDirectory(path.getAbsolutePath());
10357            } catch (RemoteException e) {
10358            }
10359        }
10360    }
10361
10362    static class OriginInfo {
10363        /**
10364         * Location where install is coming from, before it has been
10365         * copied/renamed into place. This could be a single monolithic APK
10366         * file, or a cluster directory. This location may be untrusted.
10367         */
10368        final File file;
10369        final String cid;
10370
10371        /**
10372         * Flag indicating that {@link #file} or {@link #cid} has already been
10373         * staged, meaning downstream users don't need to defensively copy the
10374         * contents.
10375         */
10376        final boolean staged;
10377
10378        /**
10379         * Flag indicating that {@link #file} or {@link #cid} is an already
10380         * installed app that is being moved.
10381         */
10382        final boolean existing;
10383
10384        final String resolvedPath;
10385        final File resolvedFile;
10386
10387        static OriginInfo fromNothing() {
10388            return new OriginInfo(null, null, false, false);
10389        }
10390
10391        static OriginInfo fromUntrustedFile(File file) {
10392            return new OriginInfo(file, null, false, false);
10393        }
10394
10395        static OriginInfo fromExistingFile(File file) {
10396            return new OriginInfo(file, null, false, true);
10397        }
10398
10399        static OriginInfo fromStagedFile(File file) {
10400            return new OriginInfo(file, null, true, false);
10401        }
10402
10403        static OriginInfo fromStagedContainer(String cid) {
10404            return new OriginInfo(null, cid, true, false);
10405        }
10406
10407        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10408            this.file = file;
10409            this.cid = cid;
10410            this.staged = staged;
10411            this.existing = existing;
10412
10413            if (cid != null) {
10414                resolvedPath = PackageHelper.getSdDir(cid);
10415                resolvedFile = new File(resolvedPath);
10416            } else if (file != null) {
10417                resolvedPath = file.getAbsolutePath();
10418                resolvedFile = file;
10419            } else {
10420                resolvedPath = null;
10421                resolvedFile = null;
10422            }
10423        }
10424    }
10425
10426    class MoveInfo {
10427        final int moveId;
10428        final String fromUuid;
10429        final String toUuid;
10430        final String packageName;
10431        final String dataAppName;
10432        final int appId;
10433        final String seinfo;
10434
10435        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10436                String dataAppName, int appId, String seinfo) {
10437            this.moveId = moveId;
10438            this.fromUuid = fromUuid;
10439            this.toUuid = toUuid;
10440            this.packageName = packageName;
10441            this.dataAppName = dataAppName;
10442            this.appId = appId;
10443            this.seinfo = seinfo;
10444        }
10445    }
10446
10447    class InstallParams extends HandlerParams {
10448        final OriginInfo origin;
10449        final MoveInfo move;
10450        final IPackageInstallObserver2 observer;
10451        int installFlags;
10452        final String installerPackageName;
10453        final String volumeUuid;
10454        final VerificationParams verificationParams;
10455        private InstallArgs mArgs;
10456        private int mRet;
10457        final String packageAbiOverride;
10458        final String[] grantedRuntimePermissions;
10459
10460
10461        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10462                int installFlags, String installerPackageName, String volumeUuid,
10463                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10464                String[] grantedPermissions) {
10465            super(user);
10466            this.origin = origin;
10467            this.move = move;
10468            this.observer = observer;
10469            this.installFlags = installFlags;
10470            this.installerPackageName = installerPackageName;
10471            this.volumeUuid = volumeUuid;
10472            this.verificationParams = verificationParams;
10473            this.packageAbiOverride = packageAbiOverride;
10474            this.grantedRuntimePermissions = grantedPermissions;
10475        }
10476
10477        @Override
10478        public String toString() {
10479            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10480                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10481        }
10482
10483        public ManifestDigest getManifestDigest() {
10484            if (verificationParams == null) {
10485                return null;
10486            }
10487            return verificationParams.getManifestDigest();
10488        }
10489
10490        private int installLocationPolicy(PackageInfoLite pkgLite) {
10491            String packageName = pkgLite.packageName;
10492            int installLocation = pkgLite.installLocation;
10493            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10494            // reader
10495            synchronized (mPackages) {
10496                PackageParser.Package pkg = mPackages.get(packageName);
10497                if (pkg != null) {
10498                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10499                        // Check for downgrading.
10500                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10501                            try {
10502                                checkDowngrade(pkg, pkgLite);
10503                            } catch (PackageManagerException e) {
10504                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10505                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10506                            }
10507                        }
10508                        // Check for updated system application.
10509                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10510                            if (onSd) {
10511                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10512                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10513                            }
10514                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10515                        } else {
10516                            if (onSd) {
10517                                // Install flag overrides everything.
10518                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10519                            }
10520                            // If current upgrade specifies particular preference
10521                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10522                                // Application explicitly specified internal.
10523                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10524                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10525                                // App explictly prefers external. Let policy decide
10526                            } else {
10527                                // Prefer previous location
10528                                if (isExternal(pkg)) {
10529                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10530                                }
10531                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10532                            }
10533                        }
10534                    } else {
10535                        // Invalid install. Return error code
10536                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10537                    }
10538                }
10539            }
10540            // All the special cases have been taken care of.
10541            // Return result based on recommended install location.
10542            if (onSd) {
10543                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10544            }
10545            return pkgLite.recommendedInstallLocation;
10546        }
10547
10548        /*
10549         * Invoke remote method to get package information and install
10550         * location values. Override install location based on default
10551         * policy if needed and then create install arguments based
10552         * on the install location.
10553         */
10554        public void handleStartCopy() throws RemoteException {
10555            int ret = PackageManager.INSTALL_SUCCEEDED;
10556
10557            // If we're already staged, we've firmly committed to an install location
10558            if (origin.staged) {
10559                if (origin.file != null) {
10560                    installFlags |= PackageManager.INSTALL_INTERNAL;
10561                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10562                } else if (origin.cid != null) {
10563                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10564                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10565                } else {
10566                    throw new IllegalStateException("Invalid stage location");
10567                }
10568            }
10569
10570            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10571            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10572
10573            PackageInfoLite pkgLite = null;
10574
10575            if (onInt && onSd) {
10576                // Check if both bits are set.
10577                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10578                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10579            } else {
10580                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10581                        packageAbiOverride);
10582
10583                /*
10584                 * If we have too little free space, try to free cache
10585                 * before giving up.
10586                 */
10587                if (!origin.staged && pkgLite.recommendedInstallLocation
10588                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10589                    // TODO: focus freeing disk space on the target device
10590                    final StorageManager storage = StorageManager.from(mContext);
10591                    final long lowThreshold = storage.getStorageLowBytes(
10592                            Environment.getDataDirectory());
10593
10594                    final long sizeBytes = mContainerService.calculateInstalledSize(
10595                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10596
10597                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10598                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10599                                installFlags, packageAbiOverride);
10600                    }
10601
10602                    /*
10603                     * The cache free must have deleted the file we
10604                     * downloaded to install.
10605                     *
10606                     * TODO: fix the "freeCache" call to not delete
10607                     *       the file we care about.
10608                     */
10609                    if (pkgLite.recommendedInstallLocation
10610                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10611                        pkgLite.recommendedInstallLocation
10612                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10613                    }
10614                }
10615            }
10616
10617            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10618                int loc = pkgLite.recommendedInstallLocation;
10619                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10620                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10621                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10622                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10623                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10624                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10625                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10626                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10627                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10628                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10629                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10630                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10631                } else {
10632                    // Override with defaults if needed.
10633                    loc = installLocationPolicy(pkgLite);
10634                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10635                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10636                    } else if (!onSd && !onInt) {
10637                        // Override install location with flags
10638                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10639                            // Set the flag to install on external media.
10640                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10641                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10642                        } else {
10643                            // Make sure the flag for installing on external
10644                            // media is unset
10645                            installFlags |= PackageManager.INSTALL_INTERNAL;
10646                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10647                        }
10648                    }
10649                }
10650            }
10651
10652            final InstallArgs args = createInstallArgs(this);
10653            mArgs = args;
10654
10655            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10656                 /*
10657                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10658                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10659                 */
10660                int userIdentifier = getUser().getIdentifier();
10661                if (userIdentifier == UserHandle.USER_ALL
10662                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10663                    userIdentifier = UserHandle.USER_OWNER;
10664                }
10665
10666                /*
10667                 * Determine if we have any installed package verifiers. If we
10668                 * do, then we'll defer to them to verify the packages.
10669                 */
10670                final int requiredUid = mRequiredVerifierPackage == null ? -1
10671                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10672                if (!origin.existing && requiredUid != -1
10673                        && isVerificationEnabled(userIdentifier, installFlags)) {
10674                    final Intent verification = new Intent(
10675                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10676                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10677                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10678                            PACKAGE_MIME_TYPE);
10679                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10680
10681                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10682                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10683                            0 /* TODO: Which userId? */);
10684
10685                    if (DEBUG_VERIFY) {
10686                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10687                                + verification.toString() + " with " + pkgLite.verifiers.length
10688                                + " optional verifiers");
10689                    }
10690
10691                    final int verificationId = mPendingVerificationToken++;
10692
10693                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10694
10695                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10696                            installerPackageName);
10697
10698                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10699                            installFlags);
10700
10701                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10702                            pkgLite.packageName);
10703
10704                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10705                            pkgLite.versionCode);
10706
10707                    if (verificationParams != null) {
10708                        if (verificationParams.getVerificationURI() != null) {
10709                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10710                                 verificationParams.getVerificationURI());
10711                        }
10712                        if (verificationParams.getOriginatingURI() != null) {
10713                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10714                                  verificationParams.getOriginatingURI());
10715                        }
10716                        if (verificationParams.getReferrer() != null) {
10717                            verification.putExtra(Intent.EXTRA_REFERRER,
10718                                  verificationParams.getReferrer());
10719                        }
10720                        if (verificationParams.getOriginatingUid() >= 0) {
10721                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10722                                  verificationParams.getOriginatingUid());
10723                        }
10724                        if (verificationParams.getInstallerUid() >= 0) {
10725                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10726                                  verificationParams.getInstallerUid());
10727                        }
10728                    }
10729
10730                    final PackageVerificationState verificationState = new PackageVerificationState(
10731                            requiredUid, args);
10732
10733                    mPendingVerification.append(verificationId, verificationState);
10734
10735                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10736                            receivers, verificationState);
10737
10738                    // Apps installed for "all" users use the device owner to verify the app
10739                    UserHandle verifierUser = getUser();
10740                    if (verifierUser == UserHandle.ALL) {
10741                        verifierUser = UserHandle.OWNER;
10742                    }
10743
10744                    /*
10745                     * If any sufficient verifiers were listed in the package
10746                     * manifest, attempt to ask them.
10747                     */
10748                    if (sufficientVerifiers != null) {
10749                        final int N = sufficientVerifiers.size();
10750                        if (N == 0) {
10751                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10752                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10753                        } else {
10754                            for (int i = 0; i < N; i++) {
10755                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10756
10757                                final Intent sufficientIntent = new Intent(verification);
10758                                sufficientIntent.setComponent(verifierComponent);
10759                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10760                            }
10761                        }
10762                    }
10763
10764                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10765                            mRequiredVerifierPackage, receivers);
10766                    if (ret == PackageManager.INSTALL_SUCCEEDED
10767                            && mRequiredVerifierPackage != null) {
10768                        /*
10769                         * Send the intent to the required verification agent,
10770                         * but only start the verification timeout after the
10771                         * target BroadcastReceivers have run.
10772                         */
10773                        verification.setComponent(requiredVerifierComponent);
10774                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10775                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10776                                new BroadcastReceiver() {
10777                                    @Override
10778                                    public void onReceive(Context context, Intent intent) {
10779                                        final Message msg = mHandler
10780                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10781                                        msg.arg1 = verificationId;
10782                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10783                                    }
10784                                }, null, 0, null, null);
10785
10786                        /*
10787                         * We don't want the copy to proceed until verification
10788                         * succeeds, so null out this field.
10789                         */
10790                        mArgs = null;
10791                    }
10792                } else {
10793                    /*
10794                     * No package verification is enabled, so immediately start
10795                     * the remote call to initiate copy using temporary file.
10796                     */
10797                    ret = args.copyApk(mContainerService, true);
10798                }
10799            }
10800
10801            mRet = ret;
10802        }
10803
10804        @Override
10805        void handleReturnCode() {
10806            // If mArgs is null, then MCS couldn't be reached. When it
10807            // reconnects, it will try again to install. At that point, this
10808            // will succeed.
10809            if (mArgs != null) {
10810                processPendingInstall(mArgs, mRet);
10811            }
10812        }
10813
10814        @Override
10815        void handleServiceError() {
10816            mArgs = createInstallArgs(this);
10817            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10818        }
10819
10820        public boolean isForwardLocked() {
10821            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10822        }
10823    }
10824
10825    /**
10826     * Used during creation of InstallArgs
10827     *
10828     * @param installFlags package installation flags
10829     * @return true if should be installed on external storage
10830     */
10831    private static boolean installOnExternalAsec(int installFlags) {
10832        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10833            return false;
10834        }
10835        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10836            return true;
10837        }
10838        return false;
10839    }
10840
10841    /**
10842     * Used during creation of InstallArgs
10843     *
10844     * @param installFlags package installation flags
10845     * @return true if should be installed as forward locked
10846     */
10847    private static boolean installForwardLocked(int installFlags) {
10848        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10849    }
10850
10851    private InstallArgs createInstallArgs(InstallParams params) {
10852        if (params.move != null) {
10853            return new MoveInstallArgs(params);
10854        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10855            return new AsecInstallArgs(params);
10856        } else {
10857            return new FileInstallArgs(params);
10858        }
10859    }
10860
10861    /**
10862     * Create args that describe an existing installed package. Typically used
10863     * when cleaning up old installs, or used as a move source.
10864     */
10865    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10866            String resourcePath, String[] instructionSets) {
10867        final boolean isInAsec;
10868        if (installOnExternalAsec(installFlags)) {
10869            /* Apps on SD card are always in ASEC containers. */
10870            isInAsec = true;
10871        } else if (installForwardLocked(installFlags)
10872                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10873            /*
10874             * Forward-locked apps are only in ASEC containers if they're the
10875             * new style
10876             */
10877            isInAsec = true;
10878        } else {
10879            isInAsec = false;
10880        }
10881
10882        if (isInAsec) {
10883            return new AsecInstallArgs(codePath, instructionSets,
10884                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10885        } else {
10886            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10887        }
10888    }
10889
10890    static abstract class InstallArgs {
10891        /** @see InstallParams#origin */
10892        final OriginInfo origin;
10893        /** @see InstallParams#move */
10894        final MoveInfo move;
10895
10896        final IPackageInstallObserver2 observer;
10897        // Always refers to PackageManager flags only
10898        final int installFlags;
10899        final String installerPackageName;
10900        final String volumeUuid;
10901        final ManifestDigest manifestDigest;
10902        final UserHandle user;
10903        final String abiOverride;
10904        final String[] installGrantPermissions;
10905
10906        // The list of instruction sets supported by this app. This is currently
10907        // only used during the rmdex() phase to clean up resources. We can get rid of this
10908        // if we move dex files under the common app path.
10909        /* nullable */ String[] instructionSets;
10910
10911        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10912                int installFlags, String installerPackageName, String volumeUuid,
10913                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10914                String abiOverride, String[] installGrantPermissions) {
10915            this.origin = origin;
10916            this.move = move;
10917            this.installFlags = installFlags;
10918            this.observer = observer;
10919            this.installerPackageName = installerPackageName;
10920            this.volumeUuid = volumeUuid;
10921            this.manifestDigest = manifestDigest;
10922            this.user = user;
10923            this.instructionSets = instructionSets;
10924            this.abiOverride = abiOverride;
10925            this.installGrantPermissions = installGrantPermissions;
10926        }
10927
10928        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10929        abstract int doPreInstall(int status);
10930
10931        /**
10932         * Rename package into final resting place. All paths on the given
10933         * scanned package should be updated to reflect the rename.
10934         */
10935        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10936        abstract int doPostInstall(int status, int uid);
10937
10938        /** @see PackageSettingBase#codePathString */
10939        abstract String getCodePath();
10940        /** @see PackageSettingBase#resourcePathString */
10941        abstract String getResourcePath();
10942
10943        // Need installer lock especially for dex file removal.
10944        abstract void cleanUpResourcesLI();
10945        abstract boolean doPostDeleteLI(boolean delete);
10946
10947        /**
10948         * Called before the source arguments are copied. This is used mostly
10949         * for MoveParams when it needs to read the source file to put it in the
10950         * destination.
10951         */
10952        int doPreCopy() {
10953            return PackageManager.INSTALL_SUCCEEDED;
10954        }
10955
10956        /**
10957         * Called after the source arguments are copied. This is used mostly for
10958         * MoveParams when it needs to read the source file to put it in the
10959         * destination.
10960         *
10961         * @return
10962         */
10963        int doPostCopy(int uid) {
10964            return PackageManager.INSTALL_SUCCEEDED;
10965        }
10966
10967        protected boolean isFwdLocked() {
10968            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10969        }
10970
10971        protected boolean isExternalAsec() {
10972            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10973        }
10974
10975        UserHandle getUser() {
10976            return user;
10977        }
10978    }
10979
10980    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10981        if (!allCodePaths.isEmpty()) {
10982            if (instructionSets == null) {
10983                throw new IllegalStateException("instructionSet == null");
10984            }
10985            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10986            for (String codePath : allCodePaths) {
10987                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10988                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10989                    if (retCode < 0) {
10990                        Slog.w(TAG, "Couldn't remove dex file for package: "
10991                                + " at location " + codePath + ", retcode=" + retCode);
10992                        // we don't consider this to be a failure of the core package deletion
10993                    }
10994                }
10995            }
10996        }
10997    }
10998
10999    /**
11000     * Logic to handle installation of non-ASEC applications, including copying
11001     * and renaming logic.
11002     */
11003    class FileInstallArgs extends InstallArgs {
11004        private File codeFile;
11005        private File resourceFile;
11006
11007        // Example topology:
11008        // /data/app/com.example/base.apk
11009        // /data/app/com.example/split_foo.apk
11010        // /data/app/com.example/lib/arm/libfoo.so
11011        // /data/app/com.example/lib/arm64/libfoo.so
11012        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11013
11014        /** New install */
11015        FileInstallArgs(InstallParams params) {
11016            super(params.origin, params.move, params.observer, params.installFlags,
11017                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11018                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11019                    params.grantedRuntimePermissions);
11020            if (isFwdLocked()) {
11021                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11022            }
11023        }
11024
11025        /** Existing install */
11026        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11027            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11028                    null, null);
11029            this.codeFile = (codePath != null) ? new File(codePath) : null;
11030            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11031        }
11032
11033        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11034            if (origin.staged) {
11035                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11036                codeFile = origin.file;
11037                resourceFile = origin.file;
11038                return PackageManager.INSTALL_SUCCEEDED;
11039            }
11040
11041            try {
11042                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11043                codeFile = tempDir;
11044                resourceFile = tempDir;
11045            } catch (IOException e) {
11046                Slog.w(TAG, "Failed to create copy file: " + e);
11047                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11048            }
11049
11050            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11051                @Override
11052                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11053                    if (!FileUtils.isValidExtFilename(name)) {
11054                        throw new IllegalArgumentException("Invalid filename: " + name);
11055                    }
11056                    try {
11057                        final File file = new File(codeFile, name);
11058                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11059                                O_RDWR | O_CREAT, 0644);
11060                        Os.chmod(file.getAbsolutePath(), 0644);
11061                        return new ParcelFileDescriptor(fd);
11062                    } catch (ErrnoException e) {
11063                        throw new RemoteException("Failed to open: " + e.getMessage());
11064                    }
11065                }
11066            };
11067
11068            int ret = PackageManager.INSTALL_SUCCEEDED;
11069            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11070            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11071                Slog.e(TAG, "Failed to copy package");
11072                return ret;
11073            }
11074
11075            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11076            NativeLibraryHelper.Handle handle = null;
11077            try {
11078                handle = NativeLibraryHelper.Handle.create(codeFile);
11079                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11080                        abiOverride);
11081            } catch (IOException e) {
11082                Slog.e(TAG, "Copying native libraries failed", e);
11083                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11084            } finally {
11085                IoUtils.closeQuietly(handle);
11086            }
11087
11088            return ret;
11089        }
11090
11091        int doPreInstall(int status) {
11092            if (status != PackageManager.INSTALL_SUCCEEDED) {
11093                cleanUp();
11094            }
11095            return status;
11096        }
11097
11098        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11099            if (status != PackageManager.INSTALL_SUCCEEDED) {
11100                cleanUp();
11101                return false;
11102            }
11103
11104            final File targetDir = codeFile.getParentFile();
11105            final File beforeCodeFile = codeFile;
11106            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11107
11108            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11109            try {
11110                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11111            } catch (ErrnoException e) {
11112                Slog.w(TAG, "Failed to rename", e);
11113                return false;
11114            }
11115
11116            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11117                Slog.w(TAG, "Failed to restorecon");
11118                return false;
11119            }
11120
11121            // Reflect the rename internally
11122            codeFile = afterCodeFile;
11123            resourceFile = afterCodeFile;
11124
11125            // Reflect the rename in scanned details
11126            pkg.codePath = afterCodeFile.getAbsolutePath();
11127            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11128                    pkg.baseCodePath);
11129            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11130                    pkg.splitCodePaths);
11131
11132            // Reflect the rename in app info
11133            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11134            pkg.applicationInfo.setCodePath(pkg.codePath);
11135            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11136            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11137            pkg.applicationInfo.setResourcePath(pkg.codePath);
11138            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11139            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11140
11141            return true;
11142        }
11143
11144        int doPostInstall(int status, int uid) {
11145            if (status != PackageManager.INSTALL_SUCCEEDED) {
11146                cleanUp();
11147            }
11148            return status;
11149        }
11150
11151        @Override
11152        String getCodePath() {
11153            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11154        }
11155
11156        @Override
11157        String getResourcePath() {
11158            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11159        }
11160
11161        private boolean cleanUp() {
11162            if (codeFile == null || !codeFile.exists()) {
11163                return false;
11164            }
11165
11166            if (codeFile.isDirectory()) {
11167                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11168            } else {
11169                codeFile.delete();
11170            }
11171
11172            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11173                resourceFile.delete();
11174            }
11175
11176            return true;
11177        }
11178
11179        void cleanUpResourcesLI() {
11180            // Try enumerating all code paths before deleting
11181            List<String> allCodePaths = Collections.EMPTY_LIST;
11182            if (codeFile != null && codeFile.exists()) {
11183                try {
11184                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11185                    allCodePaths = pkg.getAllCodePaths();
11186                } catch (PackageParserException e) {
11187                    // Ignored; we tried our best
11188                }
11189            }
11190
11191            cleanUp();
11192            removeDexFiles(allCodePaths, instructionSets);
11193        }
11194
11195        boolean doPostDeleteLI(boolean delete) {
11196            // XXX err, shouldn't we respect the delete flag?
11197            cleanUpResourcesLI();
11198            return true;
11199        }
11200    }
11201
11202    private boolean isAsecExternal(String cid) {
11203        final String asecPath = PackageHelper.getSdFilesystem(cid);
11204        return !asecPath.startsWith(mAsecInternalPath);
11205    }
11206
11207    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11208            PackageManagerException {
11209        if (copyRet < 0) {
11210            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11211                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11212                throw new PackageManagerException(copyRet, message);
11213            }
11214        }
11215    }
11216
11217    /**
11218     * Extract the MountService "container ID" from the full code path of an
11219     * .apk.
11220     */
11221    static String cidFromCodePath(String fullCodePath) {
11222        int eidx = fullCodePath.lastIndexOf("/");
11223        String subStr1 = fullCodePath.substring(0, eidx);
11224        int sidx = subStr1.lastIndexOf("/");
11225        return subStr1.substring(sidx+1, eidx);
11226    }
11227
11228    /**
11229     * Logic to handle installation of ASEC applications, including copying and
11230     * renaming logic.
11231     */
11232    class AsecInstallArgs extends InstallArgs {
11233        static final String RES_FILE_NAME = "pkg.apk";
11234        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11235
11236        String cid;
11237        String packagePath;
11238        String resourcePath;
11239
11240        /** New install */
11241        AsecInstallArgs(InstallParams params) {
11242            super(params.origin, params.move, params.observer, params.installFlags,
11243                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11244                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11245                    params.grantedRuntimePermissions);
11246        }
11247
11248        /** Existing install */
11249        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11250                        boolean isExternal, boolean isForwardLocked) {
11251            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11252                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11253                    instructionSets, null, null);
11254            // Hackily pretend we're still looking at a full code path
11255            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11256                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11257            }
11258
11259            // Extract cid from fullCodePath
11260            int eidx = fullCodePath.lastIndexOf("/");
11261            String subStr1 = fullCodePath.substring(0, eidx);
11262            int sidx = subStr1.lastIndexOf("/");
11263            cid = subStr1.substring(sidx+1, eidx);
11264            setMountPath(subStr1);
11265        }
11266
11267        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11268            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11269                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11270                    instructionSets, null, null);
11271            this.cid = cid;
11272            setMountPath(PackageHelper.getSdDir(cid));
11273        }
11274
11275        void createCopyFile() {
11276            cid = mInstallerService.allocateExternalStageCidLegacy();
11277        }
11278
11279        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11280            if (origin.staged) {
11281                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11282                cid = origin.cid;
11283                setMountPath(PackageHelper.getSdDir(cid));
11284                return PackageManager.INSTALL_SUCCEEDED;
11285            }
11286
11287            if (temp) {
11288                createCopyFile();
11289            } else {
11290                /*
11291                 * Pre-emptively destroy the container since it's destroyed if
11292                 * copying fails due to it existing anyway.
11293                 */
11294                PackageHelper.destroySdDir(cid);
11295            }
11296
11297            final String newMountPath = imcs.copyPackageToContainer(
11298                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11299                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11300
11301            if (newMountPath != null) {
11302                setMountPath(newMountPath);
11303                return PackageManager.INSTALL_SUCCEEDED;
11304            } else {
11305                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11306            }
11307        }
11308
11309        @Override
11310        String getCodePath() {
11311            return packagePath;
11312        }
11313
11314        @Override
11315        String getResourcePath() {
11316            return resourcePath;
11317        }
11318
11319        int doPreInstall(int status) {
11320            if (status != PackageManager.INSTALL_SUCCEEDED) {
11321                // Destroy container
11322                PackageHelper.destroySdDir(cid);
11323            } else {
11324                boolean mounted = PackageHelper.isContainerMounted(cid);
11325                if (!mounted) {
11326                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11327                            Process.SYSTEM_UID);
11328                    if (newMountPath != null) {
11329                        setMountPath(newMountPath);
11330                    } else {
11331                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11332                    }
11333                }
11334            }
11335            return status;
11336        }
11337
11338        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11339            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11340            String newMountPath = null;
11341            if (PackageHelper.isContainerMounted(cid)) {
11342                // Unmount the container
11343                if (!PackageHelper.unMountSdDir(cid)) {
11344                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11345                    return false;
11346                }
11347            }
11348            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11349                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11350                        " which might be stale. Will try to clean up.");
11351                // Clean up the stale container and proceed to recreate.
11352                if (!PackageHelper.destroySdDir(newCacheId)) {
11353                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11354                    return false;
11355                }
11356                // Successfully cleaned up stale container. Try to rename again.
11357                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11358                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11359                            + " inspite of cleaning it up.");
11360                    return false;
11361                }
11362            }
11363            if (!PackageHelper.isContainerMounted(newCacheId)) {
11364                Slog.w(TAG, "Mounting container " + newCacheId);
11365                newMountPath = PackageHelper.mountSdDir(newCacheId,
11366                        getEncryptKey(), Process.SYSTEM_UID);
11367            } else {
11368                newMountPath = PackageHelper.getSdDir(newCacheId);
11369            }
11370            if (newMountPath == null) {
11371                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11372                return false;
11373            }
11374            Log.i(TAG, "Succesfully renamed " + cid +
11375                    " to " + newCacheId +
11376                    " at new path: " + newMountPath);
11377            cid = newCacheId;
11378
11379            final File beforeCodeFile = new File(packagePath);
11380            setMountPath(newMountPath);
11381            final File afterCodeFile = new File(packagePath);
11382
11383            // Reflect the rename in scanned details
11384            pkg.codePath = afterCodeFile.getAbsolutePath();
11385            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11386                    pkg.baseCodePath);
11387            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11388                    pkg.splitCodePaths);
11389
11390            // Reflect the rename in app info
11391            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11392            pkg.applicationInfo.setCodePath(pkg.codePath);
11393            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11394            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11395            pkg.applicationInfo.setResourcePath(pkg.codePath);
11396            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11397            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11398
11399            return true;
11400        }
11401
11402        private void setMountPath(String mountPath) {
11403            final File mountFile = new File(mountPath);
11404
11405            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11406            if (monolithicFile.exists()) {
11407                packagePath = monolithicFile.getAbsolutePath();
11408                if (isFwdLocked()) {
11409                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11410                } else {
11411                    resourcePath = packagePath;
11412                }
11413            } else {
11414                packagePath = mountFile.getAbsolutePath();
11415                resourcePath = packagePath;
11416            }
11417        }
11418
11419        int doPostInstall(int status, int uid) {
11420            if (status != PackageManager.INSTALL_SUCCEEDED) {
11421                cleanUp();
11422            } else {
11423                final int groupOwner;
11424                final String protectedFile;
11425                if (isFwdLocked()) {
11426                    groupOwner = UserHandle.getSharedAppGid(uid);
11427                    protectedFile = RES_FILE_NAME;
11428                } else {
11429                    groupOwner = -1;
11430                    protectedFile = null;
11431                }
11432
11433                if (uid < Process.FIRST_APPLICATION_UID
11434                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11435                    Slog.e(TAG, "Failed to finalize " + cid);
11436                    PackageHelper.destroySdDir(cid);
11437                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11438                }
11439
11440                boolean mounted = PackageHelper.isContainerMounted(cid);
11441                if (!mounted) {
11442                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11443                }
11444            }
11445            return status;
11446        }
11447
11448        private void cleanUp() {
11449            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11450
11451            // Destroy secure container
11452            PackageHelper.destroySdDir(cid);
11453        }
11454
11455        private List<String> getAllCodePaths() {
11456            final File codeFile = new File(getCodePath());
11457            if (codeFile != null && codeFile.exists()) {
11458                try {
11459                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11460                    return pkg.getAllCodePaths();
11461                } catch (PackageParserException e) {
11462                    // Ignored; we tried our best
11463                }
11464            }
11465            return Collections.EMPTY_LIST;
11466        }
11467
11468        void cleanUpResourcesLI() {
11469            // Enumerate all code paths before deleting
11470            cleanUpResourcesLI(getAllCodePaths());
11471        }
11472
11473        private void cleanUpResourcesLI(List<String> allCodePaths) {
11474            cleanUp();
11475            removeDexFiles(allCodePaths, instructionSets);
11476        }
11477
11478        String getPackageName() {
11479            return getAsecPackageName(cid);
11480        }
11481
11482        boolean doPostDeleteLI(boolean delete) {
11483            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11484            final List<String> allCodePaths = getAllCodePaths();
11485            boolean mounted = PackageHelper.isContainerMounted(cid);
11486            if (mounted) {
11487                // Unmount first
11488                if (PackageHelper.unMountSdDir(cid)) {
11489                    mounted = false;
11490                }
11491            }
11492            if (!mounted && delete) {
11493                cleanUpResourcesLI(allCodePaths);
11494            }
11495            return !mounted;
11496        }
11497
11498        @Override
11499        int doPreCopy() {
11500            if (isFwdLocked()) {
11501                if (!PackageHelper.fixSdPermissions(cid,
11502                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11503                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11504                }
11505            }
11506
11507            return PackageManager.INSTALL_SUCCEEDED;
11508        }
11509
11510        @Override
11511        int doPostCopy(int uid) {
11512            if (isFwdLocked()) {
11513                if (uid < Process.FIRST_APPLICATION_UID
11514                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11515                                RES_FILE_NAME)) {
11516                    Slog.e(TAG, "Failed to finalize " + cid);
11517                    PackageHelper.destroySdDir(cid);
11518                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11519                }
11520            }
11521
11522            return PackageManager.INSTALL_SUCCEEDED;
11523        }
11524    }
11525
11526    /**
11527     * Logic to handle movement of existing installed applications.
11528     */
11529    class MoveInstallArgs extends InstallArgs {
11530        private File codeFile;
11531        private File resourceFile;
11532
11533        /** New install */
11534        MoveInstallArgs(InstallParams params) {
11535            super(params.origin, params.move, params.observer, params.installFlags,
11536                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11537                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11538                    params.grantedRuntimePermissions);
11539        }
11540
11541        int copyApk(IMediaContainerService imcs, boolean temp) {
11542            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11543                    + move.fromUuid + " to " + move.toUuid);
11544            synchronized (mInstaller) {
11545                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11546                        move.dataAppName, move.appId, move.seinfo) != 0) {
11547                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11548                }
11549            }
11550
11551            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11552            resourceFile = codeFile;
11553            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11554
11555            return PackageManager.INSTALL_SUCCEEDED;
11556        }
11557
11558        int doPreInstall(int status) {
11559            if (status != PackageManager.INSTALL_SUCCEEDED) {
11560                cleanUp(move.toUuid);
11561            }
11562            return status;
11563        }
11564
11565        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11566            if (status != PackageManager.INSTALL_SUCCEEDED) {
11567                cleanUp(move.toUuid);
11568                return false;
11569            }
11570
11571            // Reflect the move in app info
11572            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11573            pkg.applicationInfo.setCodePath(pkg.codePath);
11574            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11575            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11576            pkg.applicationInfo.setResourcePath(pkg.codePath);
11577            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11578            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11579
11580            return true;
11581        }
11582
11583        int doPostInstall(int status, int uid) {
11584            if (status == PackageManager.INSTALL_SUCCEEDED) {
11585                cleanUp(move.fromUuid);
11586            } else {
11587                cleanUp(move.toUuid);
11588            }
11589            return status;
11590        }
11591
11592        @Override
11593        String getCodePath() {
11594            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11595        }
11596
11597        @Override
11598        String getResourcePath() {
11599            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11600        }
11601
11602        private boolean cleanUp(String volumeUuid) {
11603            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11604                    move.dataAppName);
11605            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11606            synchronized (mInstallLock) {
11607                // Clean up both app data and code
11608                removeDataDirsLI(volumeUuid, move.packageName);
11609                if (codeFile.isDirectory()) {
11610                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11611                } else {
11612                    codeFile.delete();
11613                }
11614            }
11615            return true;
11616        }
11617
11618        void cleanUpResourcesLI() {
11619            throw new UnsupportedOperationException();
11620        }
11621
11622        boolean doPostDeleteLI(boolean delete) {
11623            throw new UnsupportedOperationException();
11624        }
11625    }
11626
11627    static String getAsecPackageName(String packageCid) {
11628        int idx = packageCid.lastIndexOf("-");
11629        if (idx == -1) {
11630            return packageCid;
11631        }
11632        return packageCid.substring(0, idx);
11633    }
11634
11635    // Utility method used to create code paths based on package name and available index.
11636    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11637        String idxStr = "";
11638        int idx = 1;
11639        // Fall back to default value of idx=1 if prefix is not
11640        // part of oldCodePath
11641        if (oldCodePath != null) {
11642            String subStr = oldCodePath;
11643            // Drop the suffix right away
11644            if (suffix != null && subStr.endsWith(suffix)) {
11645                subStr = subStr.substring(0, subStr.length() - suffix.length());
11646            }
11647            // If oldCodePath already contains prefix find out the
11648            // ending index to either increment or decrement.
11649            int sidx = subStr.lastIndexOf(prefix);
11650            if (sidx != -1) {
11651                subStr = subStr.substring(sidx + prefix.length());
11652                if (subStr != null) {
11653                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11654                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11655                    }
11656                    try {
11657                        idx = Integer.parseInt(subStr);
11658                        if (idx <= 1) {
11659                            idx++;
11660                        } else {
11661                            idx--;
11662                        }
11663                    } catch(NumberFormatException e) {
11664                    }
11665                }
11666            }
11667        }
11668        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11669        return prefix + idxStr;
11670    }
11671
11672    private File getNextCodePath(File targetDir, String packageName) {
11673        int suffix = 1;
11674        File result;
11675        do {
11676            result = new File(targetDir, packageName + "-" + suffix);
11677            suffix++;
11678        } while (result.exists());
11679        return result;
11680    }
11681
11682    // Utility method that returns the relative package path with respect
11683    // to the installation directory. Like say for /data/data/com.test-1.apk
11684    // string com.test-1 is returned.
11685    static String deriveCodePathName(String codePath) {
11686        if (codePath == null) {
11687            return null;
11688        }
11689        final File codeFile = new File(codePath);
11690        final String name = codeFile.getName();
11691        if (codeFile.isDirectory()) {
11692            return name;
11693        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11694            final int lastDot = name.lastIndexOf('.');
11695            return name.substring(0, lastDot);
11696        } else {
11697            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11698            return null;
11699        }
11700    }
11701
11702    class PackageInstalledInfo {
11703        String name;
11704        int uid;
11705        // The set of users that originally had this package installed.
11706        int[] origUsers;
11707        // The set of users that now have this package installed.
11708        int[] newUsers;
11709        PackageParser.Package pkg;
11710        int returnCode;
11711        String returnMsg;
11712        PackageRemovedInfo removedInfo;
11713
11714        public void setError(int code, String msg) {
11715            returnCode = code;
11716            returnMsg = msg;
11717            Slog.w(TAG, msg);
11718        }
11719
11720        public void setError(String msg, PackageParserException e) {
11721            returnCode = e.error;
11722            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11723            Slog.w(TAG, msg, e);
11724        }
11725
11726        public void setError(String msg, PackageManagerException e) {
11727            returnCode = e.error;
11728            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11729            Slog.w(TAG, msg, e);
11730        }
11731
11732        // In some error cases we want to convey more info back to the observer
11733        String origPackage;
11734        String origPermission;
11735    }
11736
11737    /*
11738     * Install a non-existing package.
11739     */
11740    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11741            UserHandle user, String installerPackageName, String volumeUuid,
11742            PackageInstalledInfo res) {
11743        // Remember this for later, in case we need to rollback this install
11744        String pkgName = pkg.packageName;
11745
11746        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11747        final boolean dataDirExists = Environment
11748                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11749        synchronized(mPackages) {
11750            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11751                // A package with the same name is already installed, though
11752                // it has been renamed to an older name.  The package we
11753                // are trying to install should be installed as an update to
11754                // the existing one, but that has not been requested, so bail.
11755                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11756                        + " without first uninstalling package running as "
11757                        + mSettings.mRenamedPackages.get(pkgName));
11758                return;
11759            }
11760            if (mPackages.containsKey(pkgName)) {
11761                // Don't allow installation over an existing package with the same name.
11762                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11763                        + " without first uninstalling.");
11764                return;
11765            }
11766        }
11767
11768        try {
11769            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11770                    System.currentTimeMillis(), user);
11771
11772            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11773            // delete the partially installed application. the data directory will have to be
11774            // restored if it was already existing
11775            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11776                // remove package from internal structures.  Note that we want deletePackageX to
11777                // delete the package data and cache directories that it created in
11778                // scanPackageLocked, unless those directories existed before we even tried to
11779                // install.
11780                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11781                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11782                                res.removedInfo, true);
11783            }
11784
11785        } catch (PackageManagerException e) {
11786            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11787        }
11788    }
11789
11790    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11791        // Can't rotate keys during boot or if sharedUser.
11792        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11793                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11794            return false;
11795        }
11796        // app is using upgradeKeySets; make sure all are valid
11797        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11798        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11799        for (int i = 0; i < upgradeKeySets.length; i++) {
11800            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11801                Slog.wtf(TAG, "Package "
11802                         + (oldPs.name != null ? oldPs.name : "<null>")
11803                         + " contains upgrade-key-set reference to unknown key-set: "
11804                         + upgradeKeySets[i]
11805                         + " reverting to signatures check.");
11806                return false;
11807            }
11808        }
11809        return true;
11810    }
11811
11812    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11813        // Upgrade keysets are being used.  Determine if new package has a superset of the
11814        // required keys.
11815        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11816        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11817        for (int i = 0; i < upgradeKeySets.length; i++) {
11818            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11819            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11820                return true;
11821            }
11822        }
11823        return false;
11824    }
11825
11826    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11827            UserHandle user, String installerPackageName, String volumeUuid,
11828            PackageInstalledInfo res) {
11829        final PackageParser.Package oldPackage;
11830        final String pkgName = pkg.packageName;
11831        final int[] allUsers;
11832        final boolean[] perUserInstalled;
11833
11834        // First find the old package info and check signatures
11835        synchronized(mPackages) {
11836            oldPackage = mPackages.get(pkgName);
11837            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11838            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11839            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11840                if(!checkUpgradeKeySetLP(ps, pkg)) {
11841                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11842                            "New package not signed by keys specified by upgrade-keysets: "
11843                            + pkgName);
11844                    return;
11845                }
11846            } else {
11847                // default to original signature matching
11848                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11849                    != PackageManager.SIGNATURE_MATCH) {
11850                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11851                            "New package has a different signature: " + pkgName);
11852                    return;
11853                }
11854            }
11855
11856            // In case of rollback, remember per-user/profile install state
11857            allUsers = sUserManager.getUserIds();
11858            perUserInstalled = new boolean[allUsers.length];
11859            for (int i = 0; i < allUsers.length; i++) {
11860                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11861            }
11862        }
11863
11864        boolean sysPkg = (isSystemApp(oldPackage));
11865        if (sysPkg) {
11866            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11867                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11868        } else {
11869            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11870                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11871        }
11872    }
11873
11874    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11875            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11876            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11877            String volumeUuid, PackageInstalledInfo res) {
11878        String pkgName = deletedPackage.packageName;
11879        boolean deletedPkg = true;
11880        boolean updatedSettings = false;
11881
11882        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11883                + deletedPackage);
11884        long origUpdateTime;
11885        if (pkg.mExtras != null) {
11886            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11887        } else {
11888            origUpdateTime = 0;
11889        }
11890
11891        // First delete the existing package while retaining the data directory
11892        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11893                res.removedInfo, true)) {
11894            // If the existing package wasn't successfully deleted
11895            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11896            deletedPkg = false;
11897        } else {
11898            // Successfully deleted the old package; proceed with replace.
11899
11900            // If deleted package lived in a container, give users a chance to
11901            // relinquish resources before killing.
11902            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11903                if (DEBUG_INSTALL) {
11904                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11905                }
11906                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11907                final ArrayList<String> pkgList = new ArrayList<String>(1);
11908                pkgList.add(deletedPackage.applicationInfo.packageName);
11909                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11910            }
11911
11912            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11913            try {
11914                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11915                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11916                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11917                        perUserInstalled, res, user);
11918                updatedSettings = true;
11919            } catch (PackageManagerException e) {
11920                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11921            }
11922        }
11923
11924        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11925            // remove package from internal structures.  Note that we want deletePackageX to
11926            // delete the package data and cache directories that it created in
11927            // scanPackageLocked, unless those directories existed before we even tried to
11928            // install.
11929            if(updatedSettings) {
11930                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11931                deletePackageLI(
11932                        pkgName, null, true, allUsers, perUserInstalled,
11933                        PackageManager.DELETE_KEEP_DATA,
11934                                res.removedInfo, true);
11935            }
11936            // Since we failed to install the new package we need to restore the old
11937            // package that we deleted.
11938            if (deletedPkg) {
11939                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11940                File restoreFile = new File(deletedPackage.codePath);
11941                // Parse old package
11942                boolean oldExternal = isExternal(deletedPackage);
11943                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11944                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11945                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11946                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11947                try {
11948                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11949                } catch (PackageManagerException e) {
11950                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11951                            + e.getMessage());
11952                    return;
11953                }
11954                // Restore of old package succeeded. Update permissions.
11955                // writer
11956                synchronized (mPackages) {
11957                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11958                            UPDATE_PERMISSIONS_ALL);
11959                    // can downgrade to reader
11960                    mSettings.writeLPr();
11961                }
11962                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11963            }
11964        }
11965    }
11966
11967    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11968            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11969            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11970            String volumeUuid, PackageInstalledInfo res) {
11971        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11972                + ", old=" + deletedPackage);
11973        boolean disabledSystem = false;
11974        boolean updatedSettings = false;
11975        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11976        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11977                != 0) {
11978            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11979        }
11980        String packageName = deletedPackage.packageName;
11981        if (packageName == null) {
11982            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11983                    "Attempt to delete null packageName.");
11984            return;
11985        }
11986        PackageParser.Package oldPkg;
11987        PackageSetting oldPkgSetting;
11988        // reader
11989        synchronized (mPackages) {
11990            oldPkg = mPackages.get(packageName);
11991            oldPkgSetting = mSettings.mPackages.get(packageName);
11992            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11993                    (oldPkgSetting == null)) {
11994                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11995                        "Couldn't find package:" + packageName + " information");
11996                return;
11997            }
11998        }
11999
12000        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12001
12002        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12003        res.removedInfo.removedPackage = packageName;
12004        // Remove existing system package
12005        removePackageLI(oldPkgSetting, true);
12006        // writer
12007        synchronized (mPackages) {
12008            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12009            if (!disabledSystem && deletedPackage != null) {
12010                // We didn't need to disable the .apk as a current system package,
12011                // which means we are replacing another update that is already
12012                // installed.  We need to make sure to delete the older one's .apk.
12013                res.removedInfo.args = createInstallArgsForExisting(0,
12014                        deletedPackage.applicationInfo.getCodePath(),
12015                        deletedPackage.applicationInfo.getResourcePath(),
12016                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12017            } else {
12018                res.removedInfo.args = null;
12019            }
12020        }
12021
12022        // Successfully disabled the old package. Now proceed with re-installation
12023        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12024
12025        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12026        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12027
12028        PackageParser.Package newPackage = null;
12029        try {
12030            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12031            if (newPackage.mExtras != null) {
12032                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12033                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12034                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12035
12036                // is the update attempting to change shared user? that isn't going to work...
12037                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12038                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12039                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12040                            + " to " + newPkgSetting.sharedUser);
12041                    updatedSettings = true;
12042                }
12043            }
12044
12045            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12046                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12047                        perUserInstalled, res, user);
12048                updatedSettings = true;
12049            }
12050
12051        } catch (PackageManagerException e) {
12052            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12053        }
12054
12055        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12056            // Re installation failed. Restore old information
12057            // Remove new pkg information
12058            if (newPackage != null) {
12059                removeInstalledPackageLI(newPackage, true);
12060            }
12061            // Add back the old system package
12062            try {
12063                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12064            } catch (PackageManagerException e) {
12065                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12066            }
12067            // Restore the old system information in Settings
12068            synchronized (mPackages) {
12069                if (disabledSystem) {
12070                    mSettings.enableSystemPackageLPw(packageName);
12071                }
12072                if (updatedSettings) {
12073                    mSettings.setInstallerPackageName(packageName,
12074                            oldPkgSetting.installerPackageName);
12075                }
12076                mSettings.writeLPr();
12077            }
12078        }
12079    }
12080
12081    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12082        // Collect all used permissions in the UID
12083        ArraySet<String> usedPermissions = new ArraySet<>();
12084        final int packageCount = su.packages.size();
12085        for (int i = 0; i < packageCount; i++) {
12086            PackageSetting ps = su.packages.valueAt(i);
12087            if (ps.pkg == null) {
12088                continue;
12089            }
12090            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12091            for (int j = 0; j < requestedPermCount; j++) {
12092                String permission = ps.pkg.requestedPermissions.get(j);
12093                BasePermission bp = mSettings.mPermissions.get(permission);
12094                if (bp != null) {
12095                    usedPermissions.add(permission);
12096                }
12097            }
12098        }
12099
12100        PermissionsState permissionsState = su.getPermissionsState();
12101        // Prune install permissions
12102        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12103        final int installPermCount = installPermStates.size();
12104        for (int i = installPermCount - 1; i >= 0;  i--) {
12105            PermissionState permissionState = installPermStates.get(i);
12106            if (!usedPermissions.contains(permissionState.getName())) {
12107                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12108                if (bp != null) {
12109                    permissionsState.revokeInstallPermission(bp);
12110                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12111                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12112                }
12113            }
12114        }
12115
12116        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12117
12118        // Prune runtime permissions
12119        for (int userId : allUserIds) {
12120            List<PermissionState> runtimePermStates = permissionsState
12121                    .getRuntimePermissionStates(userId);
12122            final int runtimePermCount = runtimePermStates.size();
12123            for (int i = runtimePermCount - 1; i >= 0; i--) {
12124                PermissionState permissionState = runtimePermStates.get(i);
12125                if (!usedPermissions.contains(permissionState.getName())) {
12126                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12127                    if (bp != null) {
12128                        permissionsState.revokeRuntimePermission(bp, userId);
12129                        permissionsState.updatePermissionFlags(bp, userId,
12130                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12131                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12132                                runtimePermissionChangedUserIds, userId);
12133                    }
12134                }
12135            }
12136        }
12137
12138        return runtimePermissionChangedUserIds;
12139    }
12140
12141    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12142            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12143            UserHandle user) {
12144        String pkgName = newPackage.packageName;
12145        synchronized (mPackages) {
12146            //write settings. the installStatus will be incomplete at this stage.
12147            //note that the new package setting would have already been
12148            //added to mPackages. It hasn't been persisted yet.
12149            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12150            mSettings.writeLPr();
12151        }
12152
12153        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12154
12155        synchronized (mPackages) {
12156            updatePermissionsLPw(newPackage.packageName, newPackage,
12157                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12158                            ? UPDATE_PERMISSIONS_ALL : 0));
12159            // For system-bundled packages, we assume that installing an upgraded version
12160            // of the package implies that the user actually wants to run that new code,
12161            // so we enable the package.
12162            PackageSetting ps = mSettings.mPackages.get(pkgName);
12163            if (ps != null) {
12164                if (isSystemApp(newPackage)) {
12165                    // NB: implicit assumption that system package upgrades apply to all users
12166                    if (DEBUG_INSTALL) {
12167                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12168                    }
12169                    if (res.origUsers != null) {
12170                        for (int userHandle : res.origUsers) {
12171                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12172                                    userHandle, installerPackageName);
12173                        }
12174                    }
12175                    // Also convey the prior install/uninstall state
12176                    if (allUsers != null && perUserInstalled != null) {
12177                        for (int i = 0; i < allUsers.length; i++) {
12178                            if (DEBUG_INSTALL) {
12179                                Slog.d(TAG, "    user " + allUsers[i]
12180                                        + " => " + perUserInstalled[i]);
12181                            }
12182                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12183                        }
12184                        // these install state changes will be persisted in the
12185                        // upcoming call to mSettings.writeLPr().
12186                    }
12187                }
12188                // It's implied that when a user requests installation, they want the app to be
12189                // installed and enabled.
12190                int userId = user.getIdentifier();
12191                if (userId != UserHandle.USER_ALL) {
12192                    ps.setInstalled(true, userId);
12193                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12194                }
12195            }
12196            res.name = pkgName;
12197            res.uid = newPackage.applicationInfo.uid;
12198            res.pkg = newPackage;
12199            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12200            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12201            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12202            //to update install status
12203            mSettings.writeLPr();
12204        }
12205    }
12206
12207    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12208        final int installFlags = args.installFlags;
12209        final String installerPackageName = args.installerPackageName;
12210        final String volumeUuid = args.volumeUuid;
12211        final File tmpPackageFile = new File(args.getCodePath());
12212        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12213        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12214                || (args.volumeUuid != null));
12215        boolean replace = false;
12216        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12217        if (args.move != null) {
12218            // moving a complete application; perfom an initial scan on the new install location
12219            scanFlags |= SCAN_INITIAL;
12220        }
12221        // Result object to be returned
12222        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12223
12224        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12225        // Retrieve PackageSettings and parse package
12226        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12227                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12228                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12229        PackageParser pp = new PackageParser();
12230        pp.setSeparateProcesses(mSeparateProcesses);
12231        pp.setDisplayMetrics(mMetrics);
12232
12233        final PackageParser.Package pkg;
12234        try {
12235            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12236        } catch (PackageParserException e) {
12237            res.setError("Failed parse during installPackageLI", e);
12238            return;
12239        }
12240
12241        // Mark that we have an install time CPU ABI override.
12242        pkg.cpuAbiOverride = args.abiOverride;
12243
12244        String pkgName = res.name = pkg.packageName;
12245        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12246            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12247                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12248                return;
12249            }
12250        }
12251
12252        try {
12253            pp.collectCertificates(pkg, parseFlags);
12254            pp.collectManifestDigest(pkg);
12255        } catch (PackageParserException e) {
12256            res.setError("Failed collect during installPackageLI", e);
12257            return;
12258        }
12259
12260        /* If the installer passed in a manifest digest, compare it now. */
12261        if (args.manifestDigest != null) {
12262            if (DEBUG_INSTALL) {
12263                final String parsedManifest = pkg.manifestDigest == null ? "null"
12264                        : pkg.manifestDigest.toString();
12265                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12266                        + parsedManifest);
12267            }
12268
12269            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12270                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12271                return;
12272            }
12273        } else if (DEBUG_INSTALL) {
12274            final String parsedManifest = pkg.manifestDigest == null
12275                    ? "null" : pkg.manifestDigest.toString();
12276            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12277        }
12278
12279        // Get rid of all references to package scan path via parser.
12280        pp = null;
12281        String oldCodePath = null;
12282        boolean systemApp = false;
12283        synchronized (mPackages) {
12284            // Check if installing already existing package
12285            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12286                String oldName = mSettings.mRenamedPackages.get(pkgName);
12287                if (pkg.mOriginalPackages != null
12288                        && pkg.mOriginalPackages.contains(oldName)
12289                        && mPackages.containsKey(oldName)) {
12290                    // This package is derived from an original package,
12291                    // and this device has been updating from that original
12292                    // name.  We must continue using the original name, so
12293                    // rename the new package here.
12294                    pkg.setPackageName(oldName);
12295                    pkgName = pkg.packageName;
12296                    replace = true;
12297                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12298                            + oldName + " pkgName=" + pkgName);
12299                } else if (mPackages.containsKey(pkgName)) {
12300                    // This package, under its official name, already exists
12301                    // on the device; we should replace it.
12302                    replace = true;
12303                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12304                }
12305
12306                // Prevent apps opting out from runtime permissions
12307                if (replace) {
12308                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12309                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12310                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12311                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12312                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12313                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12314                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12315                                        + " doesn't support runtime permissions but the old"
12316                                        + " target SDK " + oldTargetSdk + " does.");
12317                        return;
12318                    }
12319                }
12320            }
12321
12322            PackageSetting ps = mSettings.mPackages.get(pkgName);
12323            if (ps != null) {
12324                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12325
12326                // Quick sanity check that we're signed correctly if updating;
12327                // we'll check this again later when scanning, but we want to
12328                // bail early here before tripping over redefined permissions.
12329                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12330                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12331                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12332                                + pkg.packageName + " upgrade keys do not match the "
12333                                + "previously installed version");
12334                        return;
12335                    }
12336                } else {
12337                    try {
12338                        verifySignaturesLP(ps, pkg);
12339                    } catch (PackageManagerException e) {
12340                        res.setError(e.error, e.getMessage());
12341                        return;
12342                    }
12343                }
12344
12345                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12346                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12347                    systemApp = (ps.pkg.applicationInfo.flags &
12348                            ApplicationInfo.FLAG_SYSTEM) != 0;
12349                }
12350                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12351            }
12352
12353            // Check whether the newly-scanned package wants to define an already-defined perm
12354            int N = pkg.permissions.size();
12355            for (int i = N-1; i >= 0; i--) {
12356                PackageParser.Permission perm = pkg.permissions.get(i);
12357                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12358                if (bp != null) {
12359                    // If the defining package is signed with our cert, it's okay.  This
12360                    // also includes the "updating the same package" case, of course.
12361                    // "updating same package" could also involve key-rotation.
12362                    final boolean sigsOk;
12363                    if (bp.sourcePackage.equals(pkg.packageName)
12364                            && (bp.packageSetting instanceof PackageSetting)
12365                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12366                                    scanFlags))) {
12367                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12368                    } else {
12369                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12370                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12371                    }
12372                    if (!sigsOk) {
12373                        // If the owning package is the system itself, we log but allow
12374                        // install to proceed; we fail the install on all other permission
12375                        // redefinitions.
12376                        if (!bp.sourcePackage.equals("android")) {
12377                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12378                                    + pkg.packageName + " attempting to redeclare permission "
12379                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12380                            res.origPermission = perm.info.name;
12381                            res.origPackage = bp.sourcePackage;
12382                            return;
12383                        } else {
12384                            Slog.w(TAG, "Package " + pkg.packageName
12385                                    + " attempting to redeclare system permission "
12386                                    + perm.info.name + "; ignoring new declaration");
12387                            pkg.permissions.remove(i);
12388                        }
12389                    }
12390                }
12391            }
12392
12393        }
12394
12395        if (systemApp && onExternal) {
12396            // Disable updates to system apps on sdcard
12397            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12398                    "Cannot install updates to system apps on sdcard");
12399            return;
12400        }
12401
12402        if (args.move != null) {
12403            // We did an in-place move, so dex is ready to roll
12404            scanFlags |= SCAN_NO_DEX;
12405            scanFlags |= SCAN_MOVE;
12406
12407            synchronized (mPackages) {
12408                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12409                if (ps == null) {
12410                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12411                            "Missing settings for moved package " + pkgName);
12412                }
12413
12414                // We moved the entire application as-is, so bring over the
12415                // previously derived ABI information.
12416                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12417                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12418            }
12419
12420        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12421            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12422            scanFlags |= SCAN_NO_DEX;
12423
12424            try {
12425                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12426                        true /* extract libs */);
12427            } catch (PackageManagerException pme) {
12428                Slog.e(TAG, "Error deriving application ABI", pme);
12429                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12430                return;
12431            }
12432
12433            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12434            int result = mPackageDexOptimizer
12435                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12436                            false /* defer */, false /* inclDependencies */,
12437                            true /* boot complete */);
12438            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12439                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12440                return;
12441            }
12442        }
12443
12444        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12445            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12446            return;
12447        }
12448
12449        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12450
12451        if (replace) {
12452            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12453                    installerPackageName, volumeUuid, res);
12454        } else {
12455            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12456                    args.user, installerPackageName, volumeUuid, res);
12457        }
12458        synchronized (mPackages) {
12459            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12460            if (ps != null) {
12461                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12462            }
12463        }
12464    }
12465
12466    private void startIntentFilterVerifications(int userId, boolean replacing,
12467            PackageParser.Package pkg) {
12468        if (mIntentFilterVerifierComponent == null) {
12469            Slog.w(TAG, "No IntentFilter verification will not be done as "
12470                    + "there is no IntentFilterVerifier available!");
12471            return;
12472        }
12473
12474        final int verifierUid = getPackageUid(
12475                mIntentFilterVerifierComponent.getPackageName(),
12476                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12477
12478        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12479        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12480        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12481        mHandler.sendMessage(msg);
12482    }
12483
12484    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12485            PackageParser.Package pkg) {
12486        int size = pkg.activities.size();
12487        if (size == 0) {
12488            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12489                    "No activity, so no need to verify any IntentFilter!");
12490            return;
12491        }
12492
12493        final boolean hasDomainURLs = hasDomainURLs(pkg);
12494        if (!hasDomainURLs) {
12495            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12496                    "No domain URLs, so no need to verify any IntentFilter!");
12497            return;
12498        }
12499
12500        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12501                + " if any IntentFilter from the " + size
12502                + " Activities needs verification ...");
12503
12504        int count = 0;
12505        final String packageName = pkg.packageName;
12506
12507        synchronized (mPackages) {
12508            // If this is a new install and we see that we've already run verification for this
12509            // package, we have nothing to do: it means the state was restored from backup.
12510            if (!replacing) {
12511                IntentFilterVerificationInfo ivi =
12512                        mSettings.getIntentFilterVerificationLPr(packageName);
12513                if (ivi != null) {
12514                    if (DEBUG_DOMAIN_VERIFICATION) {
12515                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12516                                + ivi.getStatusString());
12517                    }
12518                    return;
12519                }
12520            }
12521
12522            // If any filters need to be verified, then all need to be.
12523            boolean needToVerify = false;
12524            for (PackageParser.Activity a : pkg.activities) {
12525                for (ActivityIntentInfo filter : a.intents) {
12526                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12527                        if (DEBUG_DOMAIN_VERIFICATION) {
12528                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12529                        }
12530                        needToVerify = true;
12531                        break;
12532                    }
12533                }
12534            }
12535
12536            if (needToVerify) {
12537                final int verificationId = mIntentFilterVerificationToken++;
12538                for (PackageParser.Activity a : pkg.activities) {
12539                    for (ActivityIntentInfo filter : a.intents) {
12540                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12541                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12542                                    "Verification needed for IntentFilter:" + filter.toString());
12543                            mIntentFilterVerifier.addOneIntentFilterVerification(
12544                                    verifierUid, userId, verificationId, filter, packageName);
12545                            count++;
12546                        }
12547                    }
12548                }
12549            }
12550        }
12551
12552        if (count > 0) {
12553            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12554                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12555                    +  " for userId:" + userId);
12556            mIntentFilterVerifier.startVerifications(userId);
12557        } else {
12558            if (DEBUG_DOMAIN_VERIFICATION) {
12559                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12560            }
12561        }
12562    }
12563
12564    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12565        final ComponentName cn  = filter.activity.getComponentName();
12566        final String packageName = cn.getPackageName();
12567
12568        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12569                packageName);
12570        if (ivi == null) {
12571            return true;
12572        }
12573        int status = ivi.getStatus();
12574        switch (status) {
12575            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12576            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12577                return true;
12578
12579            default:
12580                // Nothing to do
12581                return false;
12582        }
12583    }
12584
12585    private static boolean isMultiArch(PackageSetting ps) {
12586        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12587    }
12588
12589    private static boolean isMultiArch(ApplicationInfo info) {
12590        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12591    }
12592
12593    private static boolean isExternal(PackageParser.Package pkg) {
12594        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12595    }
12596
12597    private static boolean isExternal(PackageSetting ps) {
12598        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12599    }
12600
12601    private static boolean isExternal(ApplicationInfo info) {
12602        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12603    }
12604
12605    private static boolean isSystemApp(PackageParser.Package pkg) {
12606        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12607    }
12608
12609    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12610        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12611    }
12612
12613    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12614        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12615    }
12616
12617    private static boolean isSystemApp(PackageSetting ps) {
12618        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12619    }
12620
12621    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12622        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12623    }
12624
12625    private int packageFlagsToInstallFlags(PackageSetting ps) {
12626        int installFlags = 0;
12627        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12628            // This existing package was an external ASEC install when we have
12629            // the external flag without a UUID
12630            installFlags |= PackageManager.INSTALL_EXTERNAL;
12631        }
12632        if (ps.isForwardLocked()) {
12633            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12634        }
12635        return installFlags;
12636    }
12637
12638    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12639        if (isExternal(pkg)) {
12640            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12641                return StorageManager.UUID_PRIMARY_PHYSICAL;
12642            } else {
12643                return pkg.volumeUuid;
12644            }
12645        } else {
12646            return StorageManager.UUID_PRIVATE_INTERNAL;
12647        }
12648    }
12649
12650    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12651        if (isExternal(pkg)) {
12652            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12653                return mSettings.getExternalVersion();
12654            } else {
12655                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12656            }
12657        } else {
12658            return mSettings.getInternalVersion();
12659        }
12660    }
12661
12662    private void deleteTempPackageFiles() {
12663        final FilenameFilter filter = new FilenameFilter() {
12664            public boolean accept(File dir, String name) {
12665                return name.startsWith("vmdl") && name.endsWith(".tmp");
12666            }
12667        };
12668        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12669            file.delete();
12670        }
12671    }
12672
12673    @Override
12674    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12675            int flags) {
12676        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12677                flags);
12678    }
12679
12680    @Override
12681    public void deletePackage(final String packageName,
12682            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12683        mContext.enforceCallingOrSelfPermission(
12684                android.Manifest.permission.DELETE_PACKAGES, null);
12685        Preconditions.checkNotNull(packageName);
12686        Preconditions.checkNotNull(observer);
12687        final int uid = Binder.getCallingUid();
12688        if (UserHandle.getUserId(uid) != userId) {
12689            mContext.enforceCallingPermission(
12690                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12691                    "deletePackage for user " + userId);
12692        }
12693        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12694            try {
12695                observer.onPackageDeleted(packageName,
12696                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12697            } catch (RemoteException re) {
12698            }
12699            return;
12700        }
12701
12702        boolean uninstallBlocked = false;
12703        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12704            int[] users = sUserManager.getUserIds();
12705            for (int i = 0; i < users.length; ++i) {
12706                if (getBlockUninstallForUser(packageName, users[i])) {
12707                    uninstallBlocked = true;
12708                    break;
12709                }
12710            }
12711        } else {
12712            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12713        }
12714        if (uninstallBlocked) {
12715            try {
12716                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12717                        null);
12718            } catch (RemoteException re) {
12719            }
12720            return;
12721        }
12722
12723        if (DEBUG_REMOVE) {
12724            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12725        }
12726        // Queue up an async operation since the package deletion may take a little while.
12727        mHandler.post(new Runnable() {
12728            public void run() {
12729                mHandler.removeCallbacks(this);
12730                final int returnCode = deletePackageX(packageName, userId, flags);
12731                if (observer != null) {
12732                    try {
12733                        observer.onPackageDeleted(packageName, returnCode, null);
12734                    } catch (RemoteException e) {
12735                        Log.i(TAG, "Observer no longer exists.");
12736                    } //end catch
12737                } //end if
12738            } //end run
12739        });
12740    }
12741
12742    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12743        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12744                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12745        try {
12746            if (dpm != null) {
12747                if (dpm.isDeviceOwner(packageName)) {
12748                    return true;
12749                }
12750                int[] users;
12751                if (userId == UserHandle.USER_ALL) {
12752                    users = sUserManager.getUserIds();
12753                } else {
12754                    users = new int[]{userId};
12755                }
12756                for (int i = 0; i < users.length; ++i) {
12757                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12758                        return true;
12759                    }
12760                }
12761            }
12762        } catch (RemoteException e) {
12763        }
12764        return false;
12765    }
12766
12767    /**
12768     *  This method is an internal method that could be get invoked either
12769     *  to delete an installed package or to clean up a failed installation.
12770     *  After deleting an installed package, a broadcast is sent to notify any
12771     *  listeners that the package has been installed. For cleaning up a failed
12772     *  installation, the broadcast is not necessary since the package's
12773     *  installation wouldn't have sent the initial broadcast either
12774     *  The key steps in deleting a package are
12775     *  deleting the package information in internal structures like mPackages,
12776     *  deleting the packages base directories through installd
12777     *  updating mSettings to reflect current status
12778     *  persisting settings for later use
12779     *  sending a broadcast if necessary
12780     */
12781    private int deletePackageX(String packageName, int userId, int flags) {
12782        final PackageRemovedInfo info = new PackageRemovedInfo();
12783        final boolean res;
12784
12785        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12786                ? UserHandle.ALL : new UserHandle(userId);
12787
12788        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12789            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12790            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12791        }
12792
12793        boolean removedForAllUsers = false;
12794        boolean systemUpdate = false;
12795
12796        // for the uninstall-updates case and restricted profiles, remember the per-
12797        // userhandle installed state
12798        int[] allUsers;
12799        boolean[] perUserInstalled;
12800        synchronized (mPackages) {
12801            PackageSetting ps = mSettings.mPackages.get(packageName);
12802            allUsers = sUserManager.getUserIds();
12803            perUserInstalled = new boolean[allUsers.length];
12804            for (int i = 0; i < allUsers.length; i++) {
12805                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12806            }
12807        }
12808
12809        synchronized (mInstallLock) {
12810            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12811            res = deletePackageLI(packageName, removeForUser,
12812                    true, allUsers, perUserInstalled,
12813                    flags | REMOVE_CHATTY, info, true);
12814            systemUpdate = info.isRemovedPackageSystemUpdate;
12815            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12816                removedForAllUsers = true;
12817            }
12818            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12819                    + " removedForAllUsers=" + removedForAllUsers);
12820        }
12821
12822        if (res) {
12823            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12824
12825            // If the removed package was a system update, the old system package
12826            // was re-enabled; we need to broadcast this information
12827            if (systemUpdate) {
12828                Bundle extras = new Bundle(1);
12829                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12830                        ? info.removedAppId : info.uid);
12831                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12832
12833                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12834                        extras, null, null, null);
12835                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12836                        extras, null, null, null);
12837                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12838                        null, packageName, null, null);
12839            }
12840        }
12841        // Force a gc here.
12842        Runtime.getRuntime().gc();
12843        // Delete the resources here after sending the broadcast to let
12844        // other processes clean up before deleting resources.
12845        if (info.args != null) {
12846            synchronized (mInstallLock) {
12847                info.args.doPostDeleteLI(true);
12848            }
12849        }
12850
12851        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12852    }
12853
12854    class PackageRemovedInfo {
12855        String removedPackage;
12856        int uid = -1;
12857        int removedAppId = -1;
12858        int[] removedUsers = null;
12859        boolean isRemovedPackageSystemUpdate = false;
12860        // Clean up resources deleted packages.
12861        InstallArgs args = null;
12862
12863        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12864            Bundle extras = new Bundle(1);
12865            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12866            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12867            if (replacing) {
12868                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12869            }
12870            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12871            if (removedPackage != null) {
12872                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12873                        extras, null, null, removedUsers);
12874                if (fullRemove && !replacing) {
12875                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12876                            extras, null, null, removedUsers);
12877                }
12878            }
12879            if (removedAppId >= 0) {
12880                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12881                        removedUsers);
12882            }
12883        }
12884    }
12885
12886    /*
12887     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12888     * flag is not set, the data directory is removed as well.
12889     * make sure this flag is set for partially installed apps. If not its meaningless to
12890     * delete a partially installed application.
12891     */
12892    private void removePackageDataLI(PackageSetting ps,
12893            int[] allUserHandles, boolean[] perUserInstalled,
12894            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12895        String packageName = ps.name;
12896        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12897        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12898        // Retrieve object to delete permissions for shared user later on
12899        final PackageSetting deletedPs;
12900        // reader
12901        synchronized (mPackages) {
12902            deletedPs = mSettings.mPackages.get(packageName);
12903            if (outInfo != null) {
12904                outInfo.removedPackage = packageName;
12905                outInfo.removedUsers = deletedPs != null
12906                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12907                        : null;
12908            }
12909        }
12910        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12911            removeDataDirsLI(ps.volumeUuid, packageName);
12912            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12913        }
12914        // writer
12915        synchronized (mPackages) {
12916            if (deletedPs != null) {
12917                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12918                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12919                    clearDefaultBrowserIfNeeded(packageName);
12920                    if (outInfo != null) {
12921                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12922                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12923                    }
12924                    updatePermissionsLPw(deletedPs.name, null, 0);
12925                    if (deletedPs.sharedUser != null) {
12926                        // Remove permissions associated with package. Since runtime
12927                        // permissions are per user we have to kill the removed package
12928                        // or packages running under the shared user of the removed
12929                        // package if revoking the permissions requested only by the removed
12930                        // package is successful and this causes a change in gids.
12931                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12932                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12933                                    userId);
12934                            if (userIdToKill == UserHandle.USER_ALL
12935                                    || userIdToKill >= UserHandle.USER_OWNER) {
12936                                // If gids changed for this user, kill all affected packages.
12937                                mHandler.post(new Runnable() {
12938                                    @Override
12939                                    public void run() {
12940                                        // This has to happen with no lock held.
12941                                        killApplication(deletedPs.name, deletedPs.appId,
12942                                                KILL_APP_REASON_GIDS_CHANGED);
12943                                    }
12944                                });
12945                                break;
12946                            }
12947                        }
12948                    }
12949                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12950                }
12951                // make sure to preserve per-user disabled state if this removal was just
12952                // a downgrade of a system app to the factory package
12953                if (allUserHandles != null && perUserInstalled != null) {
12954                    if (DEBUG_REMOVE) {
12955                        Slog.d(TAG, "Propagating install state across downgrade");
12956                    }
12957                    for (int i = 0; i < allUserHandles.length; i++) {
12958                        if (DEBUG_REMOVE) {
12959                            Slog.d(TAG, "    user " + allUserHandles[i]
12960                                    + " => " + perUserInstalled[i]);
12961                        }
12962                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12963                    }
12964                }
12965            }
12966            // can downgrade to reader
12967            if (writeSettings) {
12968                // Save settings now
12969                mSettings.writeLPr();
12970            }
12971        }
12972        if (outInfo != null) {
12973            // A user ID was deleted here. Go through all users and remove it
12974            // from KeyStore.
12975            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12976        }
12977    }
12978
12979    static boolean locationIsPrivileged(File path) {
12980        try {
12981            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12982                    .getCanonicalPath();
12983            return path.getCanonicalPath().startsWith(privilegedAppDir);
12984        } catch (IOException e) {
12985            Slog.e(TAG, "Unable to access code path " + path);
12986        }
12987        return false;
12988    }
12989
12990    /*
12991     * Tries to delete system package.
12992     */
12993    private boolean deleteSystemPackageLI(PackageSetting newPs,
12994            int[] allUserHandles, boolean[] perUserInstalled,
12995            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12996        final boolean applyUserRestrictions
12997                = (allUserHandles != null) && (perUserInstalled != null);
12998        PackageSetting disabledPs = null;
12999        // Confirm if the system package has been updated
13000        // An updated system app can be deleted. This will also have to restore
13001        // the system pkg from system partition
13002        // reader
13003        synchronized (mPackages) {
13004            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13005        }
13006        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13007                + " disabledPs=" + disabledPs);
13008        if (disabledPs == null) {
13009            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13010            return false;
13011        } else if (DEBUG_REMOVE) {
13012            Slog.d(TAG, "Deleting system pkg from data partition");
13013        }
13014        if (DEBUG_REMOVE) {
13015            if (applyUserRestrictions) {
13016                Slog.d(TAG, "Remembering install states:");
13017                for (int i = 0; i < allUserHandles.length; i++) {
13018                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13019                }
13020            }
13021        }
13022        // Delete the updated package
13023        outInfo.isRemovedPackageSystemUpdate = true;
13024        if (disabledPs.versionCode < newPs.versionCode) {
13025            // Delete data for downgrades
13026            flags &= ~PackageManager.DELETE_KEEP_DATA;
13027        } else {
13028            // Preserve data by setting flag
13029            flags |= PackageManager.DELETE_KEEP_DATA;
13030        }
13031        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13032                allUserHandles, perUserInstalled, outInfo, writeSettings);
13033        if (!ret) {
13034            return false;
13035        }
13036        // writer
13037        synchronized (mPackages) {
13038            // Reinstate the old system package
13039            mSettings.enableSystemPackageLPw(newPs.name);
13040            // Remove any native libraries from the upgraded package.
13041            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13042        }
13043        // Install the system package
13044        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13045        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13046        if (locationIsPrivileged(disabledPs.codePath)) {
13047            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13048        }
13049
13050        final PackageParser.Package newPkg;
13051        try {
13052            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13053        } catch (PackageManagerException e) {
13054            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13055            return false;
13056        }
13057
13058        // writer
13059        synchronized (mPackages) {
13060            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13061
13062            // Propagate the permissions state as we do not want to drop on the floor
13063            // runtime permissions. The update permissions method below will take
13064            // care of removing obsolete permissions and grant install permissions.
13065            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13066            updatePermissionsLPw(newPkg.packageName, newPkg,
13067                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13068
13069            if (applyUserRestrictions) {
13070                if (DEBUG_REMOVE) {
13071                    Slog.d(TAG, "Propagating install state across reinstall");
13072                }
13073                for (int i = 0; i < allUserHandles.length; i++) {
13074                    if (DEBUG_REMOVE) {
13075                        Slog.d(TAG, "    user " + allUserHandles[i]
13076                                + " => " + perUserInstalled[i]);
13077                    }
13078                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13079
13080                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13081                }
13082                // Regardless of writeSettings we need to ensure that this restriction
13083                // state propagation is persisted
13084                mSettings.writeAllUsersPackageRestrictionsLPr();
13085            }
13086            // can downgrade to reader here
13087            if (writeSettings) {
13088                mSettings.writeLPr();
13089            }
13090        }
13091        return true;
13092    }
13093
13094    private boolean deleteInstalledPackageLI(PackageSetting ps,
13095            boolean deleteCodeAndResources, int flags,
13096            int[] allUserHandles, boolean[] perUserInstalled,
13097            PackageRemovedInfo outInfo, boolean writeSettings) {
13098        if (outInfo != null) {
13099            outInfo.uid = ps.appId;
13100        }
13101
13102        // Delete package data from internal structures and also remove data if flag is set
13103        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13104
13105        // Delete application code and resources
13106        if (deleteCodeAndResources && (outInfo != null)) {
13107            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13108                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13109            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13110        }
13111        return true;
13112    }
13113
13114    @Override
13115    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13116            int userId) {
13117        mContext.enforceCallingOrSelfPermission(
13118                android.Manifest.permission.DELETE_PACKAGES, null);
13119        synchronized (mPackages) {
13120            PackageSetting ps = mSettings.mPackages.get(packageName);
13121            if (ps == null) {
13122                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13123                return false;
13124            }
13125            if (!ps.getInstalled(userId)) {
13126                // Can't block uninstall for an app that is not installed or enabled.
13127                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13128                return false;
13129            }
13130            ps.setBlockUninstall(blockUninstall, userId);
13131            mSettings.writePackageRestrictionsLPr(userId);
13132        }
13133        return true;
13134    }
13135
13136    @Override
13137    public boolean getBlockUninstallForUser(String packageName, int userId) {
13138        synchronized (mPackages) {
13139            PackageSetting ps = mSettings.mPackages.get(packageName);
13140            if (ps == null) {
13141                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13142                return false;
13143            }
13144            return ps.getBlockUninstall(userId);
13145        }
13146    }
13147
13148    /*
13149     * This method handles package deletion in general
13150     */
13151    private boolean deletePackageLI(String packageName, UserHandle user,
13152            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13153            int flags, PackageRemovedInfo outInfo,
13154            boolean writeSettings) {
13155        if (packageName == null) {
13156            Slog.w(TAG, "Attempt to delete null packageName.");
13157            return false;
13158        }
13159        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13160        PackageSetting ps;
13161        boolean dataOnly = false;
13162        int removeUser = -1;
13163        int appId = -1;
13164        synchronized (mPackages) {
13165            ps = mSettings.mPackages.get(packageName);
13166            if (ps == null) {
13167                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13168                return false;
13169            }
13170            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13171                    && user.getIdentifier() != UserHandle.USER_ALL) {
13172                // The caller is asking that the package only be deleted for a single
13173                // user.  To do this, we just mark its uninstalled state and delete
13174                // its data.  If this is a system app, we only allow this to happen if
13175                // they have set the special DELETE_SYSTEM_APP which requests different
13176                // semantics than normal for uninstalling system apps.
13177                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13178                final int userId = user.getIdentifier();
13179                ps.setUserState(userId,
13180                        COMPONENT_ENABLED_STATE_DEFAULT,
13181                        false, //installed
13182                        true,  //stopped
13183                        true,  //notLaunched
13184                        false, //hidden
13185                        null, null, null,
13186                        false, // blockUninstall
13187                        ps.readUserState(userId).domainVerificationStatus, 0);
13188                if (!isSystemApp(ps)) {
13189                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13190                        // Other user still have this package installed, so all
13191                        // we need to do is clear this user's data and save that
13192                        // it is uninstalled.
13193                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13194                        removeUser = user.getIdentifier();
13195                        appId = ps.appId;
13196                        scheduleWritePackageRestrictionsLocked(removeUser);
13197                    } else {
13198                        // We need to set it back to 'installed' so the uninstall
13199                        // broadcasts will be sent correctly.
13200                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13201                        ps.setInstalled(true, user.getIdentifier());
13202                    }
13203                } else {
13204                    // This is a system app, so we assume that the
13205                    // other users still have this package installed, so all
13206                    // we need to do is clear this user's data and save that
13207                    // it is uninstalled.
13208                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13209                    removeUser = user.getIdentifier();
13210                    appId = ps.appId;
13211                    scheduleWritePackageRestrictionsLocked(removeUser);
13212                }
13213            }
13214        }
13215
13216        if (removeUser >= 0) {
13217            // From above, we determined that we are deleting this only
13218            // for a single user.  Continue the work here.
13219            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13220            if (outInfo != null) {
13221                outInfo.removedPackage = packageName;
13222                outInfo.removedAppId = appId;
13223                outInfo.removedUsers = new int[] {removeUser};
13224            }
13225            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13226            removeKeystoreDataIfNeeded(removeUser, appId);
13227            schedulePackageCleaning(packageName, removeUser, false);
13228            synchronized (mPackages) {
13229                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13230                    scheduleWritePackageRestrictionsLocked(removeUser);
13231                }
13232                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13233            }
13234            return true;
13235        }
13236
13237        if (dataOnly) {
13238            // Delete application data first
13239            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13240            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13241            return true;
13242        }
13243
13244        boolean ret = false;
13245        if (isSystemApp(ps)) {
13246            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13247            // When an updated system application is deleted we delete the existing resources as well and
13248            // fall back to existing code in system partition
13249            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13250                    flags, outInfo, writeSettings);
13251        } else {
13252            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13253            // Kill application pre-emptively especially for apps on sd.
13254            killApplication(packageName, ps.appId, "uninstall pkg");
13255            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13256                    allUserHandles, perUserInstalled,
13257                    outInfo, writeSettings);
13258        }
13259
13260        return ret;
13261    }
13262
13263    private final class ClearStorageConnection implements ServiceConnection {
13264        IMediaContainerService mContainerService;
13265
13266        @Override
13267        public void onServiceConnected(ComponentName name, IBinder service) {
13268            synchronized (this) {
13269                mContainerService = IMediaContainerService.Stub.asInterface(service);
13270                notifyAll();
13271            }
13272        }
13273
13274        @Override
13275        public void onServiceDisconnected(ComponentName name) {
13276        }
13277    }
13278
13279    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13280        final boolean mounted;
13281        if (Environment.isExternalStorageEmulated()) {
13282            mounted = true;
13283        } else {
13284            final String status = Environment.getExternalStorageState();
13285
13286            mounted = status.equals(Environment.MEDIA_MOUNTED)
13287                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13288        }
13289
13290        if (!mounted) {
13291            return;
13292        }
13293
13294        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13295        int[] users;
13296        if (userId == UserHandle.USER_ALL) {
13297            users = sUserManager.getUserIds();
13298        } else {
13299            users = new int[] { userId };
13300        }
13301        final ClearStorageConnection conn = new ClearStorageConnection();
13302        if (mContext.bindServiceAsUser(
13303                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13304            try {
13305                for (int curUser : users) {
13306                    long timeout = SystemClock.uptimeMillis() + 5000;
13307                    synchronized (conn) {
13308                        long now = SystemClock.uptimeMillis();
13309                        while (conn.mContainerService == null && now < timeout) {
13310                            try {
13311                                conn.wait(timeout - now);
13312                            } catch (InterruptedException e) {
13313                            }
13314                        }
13315                    }
13316                    if (conn.mContainerService == null) {
13317                        return;
13318                    }
13319
13320                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13321                    clearDirectory(conn.mContainerService,
13322                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13323                    if (allData) {
13324                        clearDirectory(conn.mContainerService,
13325                                userEnv.buildExternalStorageAppDataDirs(packageName));
13326                        clearDirectory(conn.mContainerService,
13327                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13328                    }
13329                }
13330            } finally {
13331                mContext.unbindService(conn);
13332            }
13333        }
13334    }
13335
13336    @Override
13337    public void clearApplicationUserData(final String packageName,
13338            final IPackageDataObserver observer, final int userId) {
13339        mContext.enforceCallingOrSelfPermission(
13340                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13341        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13342        // Queue up an async operation since the package deletion may take a little while.
13343        mHandler.post(new Runnable() {
13344            public void run() {
13345                mHandler.removeCallbacks(this);
13346                final boolean succeeded;
13347                synchronized (mInstallLock) {
13348                    succeeded = clearApplicationUserDataLI(packageName, userId);
13349                }
13350                clearExternalStorageDataSync(packageName, userId, true);
13351                if (succeeded) {
13352                    // invoke DeviceStorageMonitor's update method to clear any notifications
13353                    DeviceStorageMonitorInternal
13354                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13355                    if (dsm != null) {
13356                        dsm.checkMemory();
13357                    }
13358                }
13359                if(observer != null) {
13360                    try {
13361                        observer.onRemoveCompleted(packageName, succeeded);
13362                    } catch (RemoteException e) {
13363                        Log.i(TAG, "Observer no longer exists.");
13364                    }
13365                } //end if observer
13366            } //end run
13367        });
13368    }
13369
13370    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13371        if (packageName == null) {
13372            Slog.w(TAG, "Attempt to delete null packageName.");
13373            return false;
13374        }
13375
13376        // Try finding details about the requested package
13377        PackageParser.Package pkg;
13378        synchronized (mPackages) {
13379            pkg = mPackages.get(packageName);
13380            if (pkg == null) {
13381                final PackageSetting ps = mSettings.mPackages.get(packageName);
13382                if (ps != null) {
13383                    pkg = ps.pkg;
13384                }
13385            }
13386
13387            if (pkg == null) {
13388                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13389                return false;
13390            }
13391
13392            PackageSetting ps = (PackageSetting) pkg.mExtras;
13393            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13394        }
13395
13396        // Always delete data directories for package, even if we found no other
13397        // record of app. This helps users recover from UID mismatches without
13398        // resorting to a full data wipe.
13399        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13400        if (retCode < 0) {
13401            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13402            return false;
13403        }
13404
13405        final int appId = pkg.applicationInfo.uid;
13406        removeKeystoreDataIfNeeded(userId, appId);
13407
13408        // Create a native library symlink only if we have native libraries
13409        // and if the native libraries are 32 bit libraries. We do not provide
13410        // this symlink for 64 bit libraries.
13411        if (pkg.applicationInfo.primaryCpuAbi != null &&
13412                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13413            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13414            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13415                    nativeLibPath, userId) < 0) {
13416                Slog.w(TAG, "Failed linking native library dir");
13417                return false;
13418            }
13419        }
13420
13421        return true;
13422    }
13423
13424    /**
13425     * Reverts user permission state changes (permissions and flags) in
13426     * all packages for a given user.
13427     *
13428     * @param userId The device user for which to do a reset.
13429     */
13430    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13431        final int packageCount = mPackages.size();
13432        for (int i = 0; i < packageCount; i++) {
13433            PackageParser.Package pkg = mPackages.valueAt(i);
13434            PackageSetting ps = (PackageSetting) pkg.mExtras;
13435            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13436        }
13437    }
13438
13439    /**
13440     * Reverts user permission state changes (permissions and flags).
13441     *
13442     * @param ps The package for which to reset.
13443     * @param userId The device user for which to do a reset.
13444     */
13445    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13446            final PackageSetting ps, final int userId) {
13447        if (ps.pkg == null) {
13448            return;
13449        }
13450
13451        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13452                | FLAG_PERMISSION_USER_FIXED
13453                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13454
13455        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13456                | FLAG_PERMISSION_POLICY_FIXED;
13457
13458        boolean writeInstallPermissions = false;
13459        boolean writeRuntimePermissions = false;
13460
13461        final int permissionCount = ps.pkg.requestedPermissions.size();
13462        for (int i = 0; i < permissionCount; i++) {
13463            String permission = ps.pkg.requestedPermissions.get(i);
13464
13465            BasePermission bp = mSettings.mPermissions.get(permission);
13466            if (bp == null) {
13467                continue;
13468            }
13469
13470            // If shared user we just reset the state to which only this app contributed.
13471            if (ps.sharedUser != null) {
13472                boolean used = false;
13473                final int packageCount = ps.sharedUser.packages.size();
13474                for (int j = 0; j < packageCount; j++) {
13475                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13476                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13477                            && pkg.pkg.requestedPermissions.contains(permission)) {
13478                        used = true;
13479                        break;
13480                    }
13481                }
13482                if (used) {
13483                    continue;
13484                }
13485            }
13486
13487            PermissionsState permissionsState = ps.getPermissionsState();
13488
13489            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13490
13491            // Always clear the user settable flags.
13492            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13493                    bp.name) != null;
13494            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13495                if (hasInstallState) {
13496                    writeInstallPermissions = true;
13497                } else {
13498                    writeRuntimePermissions = true;
13499                }
13500            }
13501
13502            // Below is only runtime permission handling.
13503            if (!bp.isRuntime()) {
13504                continue;
13505            }
13506
13507            // Never clobber system or policy.
13508            if ((oldFlags & policyOrSystemFlags) != 0) {
13509                continue;
13510            }
13511
13512            // If this permission was granted by default, make sure it is.
13513            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13514                if (permissionsState.grantRuntimePermission(bp, userId)
13515                        != PERMISSION_OPERATION_FAILURE) {
13516                    writeRuntimePermissions = true;
13517                }
13518            } else {
13519                // Otherwise, reset the permission.
13520                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13521                switch (revokeResult) {
13522                    case PERMISSION_OPERATION_SUCCESS: {
13523                        writeRuntimePermissions = true;
13524                    } break;
13525
13526                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13527                        writeRuntimePermissions = true;
13528                        final int appId = ps.appId;
13529                        mHandler.post(new Runnable() {
13530                            @Override
13531                            public void run() {
13532                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13533                            }
13534                        });
13535                    } break;
13536                }
13537            }
13538        }
13539
13540        // Synchronously write as we are taking permissions away.
13541        if (writeRuntimePermissions) {
13542            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13543        }
13544
13545        // Synchronously write as we are taking permissions away.
13546        if (writeInstallPermissions) {
13547            mSettings.writeLPr();
13548        }
13549    }
13550
13551    /**
13552     * Remove entries from the keystore daemon. Will only remove it if the
13553     * {@code appId} is valid.
13554     */
13555    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13556        if (appId < 0) {
13557            return;
13558        }
13559
13560        final KeyStore keyStore = KeyStore.getInstance();
13561        if (keyStore != null) {
13562            if (userId == UserHandle.USER_ALL) {
13563                for (final int individual : sUserManager.getUserIds()) {
13564                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13565                }
13566            } else {
13567                keyStore.clearUid(UserHandle.getUid(userId, appId));
13568            }
13569        } else {
13570            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13571        }
13572    }
13573
13574    @Override
13575    public void deleteApplicationCacheFiles(final String packageName,
13576            final IPackageDataObserver observer) {
13577        mContext.enforceCallingOrSelfPermission(
13578                android.Manifest.permission.DELETE_CACHE_FILES, null);
13579        // Queue up an async operation since the package deletion may take a little while.
13580        final int userId = UserHandle.getCallingUserId();
13581        mHandler.post(new Runnable() {
13582            public void run() {
13583                mHandler.removeCallbacks(this);
13584                final boolean succeded;
13585                synchronized (mInstallLock) {
13586                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13587                }
13588                clearExternalStorageDataSync(packageName, userId, false);
13589                if (observer != null) {
13590                    try {
13591                        observer.onRemoveCompleted(packageName, succeded);
13592                    } catch (RemoteException e) {
13593                        Log.i(TAG, "Observer no longer exists.");
13594                    }
13595                } //end if observer
13596            } //end run
13597        });
13598    }
13599
13600    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13601        if (packageName == null) {
13602            Slog.w(TAG, "Attempt to delete null packageName.");
13603            return false;
13604        }
13605        PackageParser.Package p;
13606        synchronized (mPackages) {
13607            p = mPackages.get(packageName);
13608        }
13609        if (p == null) {
13610            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13611            return false;
13612        }
13613        final ApplicationInfo applicationInfo = p.applicationInfo;
13614        if (applicationInfo == null) {
13615            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13616            return false;
13617        }
13618        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13619        if (retCode < 0) {
13620            Slog.w(TAG, "Couldn't remove cache files for package: "
13621                       + packageName + " u" + userId);
13622            return false;
13623        }
13624        return true;
13625    }
13626
13627    @Override
13628    public void getPackageSizeInfo(final String packageName, int userHandle,
13629            final IPackageStatsObserver observer) {
13630        mContext.enforceCallingOrSelfPermission(
13631                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13632        if (packageName == null) {
13633            throw new IllegalArgumentException("Attempt to get size of null packageName");
13634        }
13635
13636        PackageStats stats = new PackageStats(packageName, userHandle);
13637
13638        /*
13639         * Queue up an async operation since the package measurement may take a
13640         * little while.
13641         */
13642        Message msg = mHandler.obtainMessage(INIT_COPY);
13643        msg.obj = new MeasureParams(stats, observer);
13644        mHandler.sendMessage(msg);
13645    }
13646
13647    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13648            PackageStats pStats) {
13649        if (packageName == null) {
13650            Slog.w(TAG, "Attempt to get size of null packageName.");
13651            return false;
13652        }
13653        PackageParser.Package p;
13654        boolean dataOnly = false;
13655        String libDirRoot = null;
13656        String asecPath = null;
13657        PackageSetting ps = null;
13658        synchronized (mPackages) {
13659            p = mPackages.get(packageName);
13660            ps = mSettings.mPackages.get(packageName);
13661            if(p == null) {
13662                dataOnly = true;
13663                if((ps == null) || (ps.pkg == null)) {
13664                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13665                    return false;
13666                }
13667                p = ps.pkg;
13668            }
13669            if (ps != null) {
13670                libDirRoot = ps.legacyNativeLibraryPathString;
13671            }
13672            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
13673                final long token = Binder.clearCallingIdentity();
13674                try {
13675                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13676                    if (secureContainerId != null) {
13677                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13678                    }
13679                } finally {
13680                    Binder.restoreCallingIdentity(token);
13681                }
13682            }
13683        }
13684        String publicSrcDir = null;
13685        if(!dataOnly) {
13686            final ApplicationInfo applicationInfo = p.applicationInfo;
13687            if (applicationInfo == null) {
13688                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13689                return false;
13690            }
13691            if (p.isForwardLocked()) {
13692                publicSrcDir = applicationInfo.getBaseResourcePath();
13693            }
13694        }
13695        // TODO: extend to measure size of split APKs
13696        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13697        // not just the first level.
13698        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13699        // just the primary.
13700        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13701
13702        String apkPath;
13703        File packageDir = new File(p.codePath);
13704
13705        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13706            apkPath = packageDir.getAbsolutePath();
13707            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13708            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13709                libDirRoot = null;
13710            }
13711        } else {
13712            apkPath = p.baseCodePath;
13713        }
13714
13715        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13716                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13717        if (res < 0) {
13718            return false;
13719        }
13720
13721        // Fix-up for forward-locked applications in ASEC containers.
13722        if (!isExternal(p)) {
13723            pStats.codeSize += pStats.externalCodeSize;
13724            pStats.externalCodeSize = 0L;
13725        }
13726
13727        return true;
13728    }
13729
13730
13731    @Override
13732    public void addPackageToPreferred(String packageName) {
13733        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13734    }
13735
13736    @Override
13737    public void removePackageFromPreferred(String packageName) {
13738        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13739    }
13740
13741    @Override
13742    public List<PackageInfo> getPreferredPackages(int flags) {
13743        return new ArrayList<PackageInfo>();
13744    }
13745
13746    private int getUidTargetSdkVersionLockedLPr(int uid) {
13747        Object obj = mSettings.getUserIdLPr(uid);
13748        if (obj instanceof SharedUserSetting) {
13749            final SharedUserSetting sus = (SharedUserSetting) obj;
13750            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13751            final Iterator<PackageSetting> it = sus.packages.iterator();
13752            while (it.hasNext()) {
13753                final PackageSetting ps = it.next();
13754                if (ps.pkg != null) {
13755                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13756                    if (v < vers) vers = v;
13757                }
13758            }
13759            return vers;
13760        } else if (obj instanceof PackageSetting) {
13761            final PackageSetting ps = (PackageSetting) obj;
13762            if (ps.pkg != null) {
13763                return ps.pkg.applicationInfo.targetSdkVersion;
13764            }
13765        }
13766        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13767    }
13768
13769    @Override
13770    public void addPreferredActivity(IntentFilter filter, int match,
13771            ComponentName[] set, ComponentName activity, int userId) {
13772        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13773                "Adding preferred");
13774    }
13775
13776    private void addPreferredActivityInternal(IntentFilter filter, int match,
13777            ComponentName[] set, ComponentName activity, boolean always, int userId,
13778            String opname) {
13779        // writer
13780        int callingUid = Binder.getCallingUid();
13781        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13782        if (filter.countActions() == 0) {
13783            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13784            return;
13785        }
13786        synchronized (mPackages) {
13787            if (mContext.checkCallingOrSelfPermission(
13788                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13789                    != PackageManager.PERMISSION_GRANTED) {
13790                if (getUidTargetSdkVersionLockedLPr(callingUid)
13791                        < Build.VERSION_CODES.FROYO) {
13792                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13793                            + callingUid);
13794                    return;
13795                }
13796                mContext.enforceCallingOrSelfPermission(
13797                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13798            }
13799
13800            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13801            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13802                    + userId + ":");
13803            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13804            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13805            scheduleWritePackageRestrictionsLocked(userId);
13806        }
13807    }
13808
13809    @Override
13810    public void replacePreferredActivity(IntentFilter filter, int match,
13811            ComponentName[] set, ComponentName activity, int userId) {
13812        if (filter.countActions() != 1) {
13813            throw new IllegalArgumentException(
13814                    "replacePreferredActivity expects filter to have only 1 action.");
13815        }
13816        if (filter.countDataAuthorities() != 0
13817                || filter.countDataPaths() != 0
13818                || filter.countDataSchemes() > 1
13819                || filter.countDataTypes() != 0) {
13820            throw new IllegalArgumentException(
13821                    "replacePreferredActivity expects filter to have no data authorities, " +
13822                    "paths, or types; and at most one scheme.");
13823        }
13824
13825        final int callingUid = Binder.getCallingUid();
13826        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13827        synchronized (mPackages) {
13828            if (mContext.checkCallingOrSelfPermission(
13829                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13830                    != PackageManager.PERMISSION_GRANTED) {
13831                if (getUidTargetSdkVersionLockedLPr(callingUid)
13832                        < Build.VERSION_CODES.FROYO) {
13833                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13834                            + Binder.getCallingUid());
13835                    return;
13836                }
13837                mContext.enforceCallingOrSelfPermission(
13838                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13839            }
13840
13841            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13842            if (pir != null) {
13843                // Get all of the existing entries that exactly match this filter.
13844                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13845                if (existing != null && existing.size() == 1) {
13846                    PreferredActivity cur = existing.get(0);
13847                    if (DEBUG_PREFERRED) {
13848                        Slog.i(TAG, "Checking replace of preferred:");
13849                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13850                        if (!cur.mPref.mAlways) {
13851                            Slog.i(TAG, "  -- CUR; not mAlways!");
13852                        } else {
13853                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13854                            Slog.i(TAG, "  -- CUR: mSet="
13855                                    + Arrays.toString(cur.mPref.mSetComponents));
13856                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13857                            Slog.i(TAG, "  -- NEW: mMatch="
13858                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13859                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13860                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13861                        }
13862                    }
13863                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13864                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13865                            && cur.mPref.sameSet(set)) {
13866                        // Setting the preferred activity to what it happens to be already
13867                        if (DEBUG_PREFERRED) {
13868                            Slog.i(TAG, "Replacing with same preferred activity "
13869                                    + cur.mPref.mShortComponent + " for user "
13870                                    + userId + ":");
13871                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13872                        }
13873                        return;
13874                    }
13875                }
13876
13877                if (existing != null) {
13878                    if (DEBUG_PREFERRED) {
13879                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13880                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13881                    }
13882                    for (int i = 0; i < existing.size(); i++) {
13883                        PreferredActivity pa = existing.get(i);
13884                        if (DEBUG_PREFERRED) {
13885                            Slog.i(TAG, "Removing existing preferred activity "
13886                                    + pa.mPref.mComponent + ":");
13887                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13888                        }
13889                        pir.removeFilter(pa);
13890                    }
13891                }
13892            }
13893            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13894                    "Replacing preferred");
13895        }
13896    }
13897
13898    @Override
13899    public void clearPackagePreferredActivities(String packageName) {
13900        final int uid = Binder.getCallingUid();
13901        // writer
13902        synchronized (mPackages) {
13903            PackageParser.Package pkg = mPackages.get(packageName);
13904            if (pkg == null || pkg.applicationInfo.uid != uid) {
13905                if (mContext.checkCallingOrSelfPermission(
13906                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13907                        != PackageManager.PERMISSION_GRANTED) {
13908                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13909                            < Build.VERSION_CODES.FROYO) {
13910                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13911                                + Binder.getCallingUid());
13912                        return;
13913                    }
13914                    mContext.enforceCallingOrSelfPermission(
13915                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13916                }
13917            }
13918
13919            int user = UserHandle.getCallingUserId();
13920            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13921                scheduleWritePackageRestrictionsLocked(user);
13922            }
13923        }
13924    }
13925
13926    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13927    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13928        ArrayList<PreferredActivity> removed = null;
13929        boolean changed = false;
13930        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13931            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13932            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13933            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13934                continue;
13935            }
13936            Iterator<PreferredActivity> it = pir.filterIterator();
13937            while (it.hasNext()) {
13938                PreferredActivity pa = it.next();
13939                // Mark entry for removal only if it matches the package name
13940                // and the entry is of type "always".
13941                if (packageName == null ||
13942                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13943                                && pa.mPref.mAlways)) {
13944                    if (removed == null) {
13945                        removed = new ArrayList<PreferredActivity>();
13946                    }
13947                    removed.add(pa);
13948                }
13949            }
13950            if (removed != null) {
13951                for (int j=0; j<removed.size(); j++) {
13952                    PreferredActivity pa = removed.get(j);
13953                    pir.removeFilter(pa);
13954                }
13955                changed = true;
13956            }
13957        }
13958        return changed;
13959    }
13960
13961    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13962    private void clearIntentFilterVerificationsLPw(int userId) {
13963        final int packageCount = mPackages.size();
13964        for (int i = 0; i < packageCount; i++) {
13965            PackageParser.Package pkg = mPackages.valueAt(i);
13966            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13967        }
13968    }
13969
13970    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13971    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13972        if (userId == UserHandle.USER_ALL) {
13973            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13974                    sUserManager.getUserIds())) {
13975                for (int oneUserId : sUserManager.getUserIds()) {
13976                    scheduleWritePackageRestrictionsLocked(oneUserId);
13977                }
13978            }
13979        } else {
13980            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13981                scheduleWritePackageRestrictionsLocked(userId);
13982            }
13983        }
13984    }
13985
13986    void clearDefaultBrowserIfNeeded(String packageName) {
13987        for (int oneUserId : sUserManager.getUserIds()) {
13988            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13989            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13990            if (packageName.equals(defaultBrowserPackageName)) {
13991                setDefaultBrowserPackageName(null, oneUserId);
13992            }
13993        }
13994    }
13995
13996    @Override
13997    public void resetApplicationPreferences(int userId) {
13998        mContext.enforceCallingOrSelfPermission(
13999                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14000        // writer
14001        synchronized (mPackages) {
14002            final long identity = Binder.clearCallingIdentity();
14003            try {
14004                clearPackagePreferredActivitiesLPw(null, userId);
14005                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14006                // TODO: We have to reset the default SMS and Phone. This requires
14007                // significant refactoring to keep all default apps in the package
14008                // manager (cleaner but more work) or have the services provide
14009                // callbacks to the package manager to request a default app reset.
14010                applyFactoryDefaultBrowserLPw(userId);
14011                clearIntentFilterVerificationsLPw(userId);
14012                primeDomainVerificationsLPw(userId);
14013                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14014                scheduleWritePackageRestrictionsLocked(userId);
14015            } finally {
14016                Binder.restoreCallingIdentity(identity);
14017            }
14018        }
14019    }
14020
14021    @Override
14022    public int getPreferredActivities(List<IntentFilter> outFilters,
14023            List<ComponentName> outActivities, String packageName) {
14024
14025        int num = 0;
14026        final int userId = UserHandle.getCallingUserId();
14027        // reader
14028        synchronized (mPackages) {
14029            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14030            if (pir != null) {
14031                final Iterator<PreferredActivity> it = pir.filterIterator();
14032                while (it.hasNext()) {
14033                    final PreferredActivity pa = it.next();
14034                    if (packageName == null
14035                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14036                                    && pa.mPref.mAlways)) {
14037                        if (outFilters != null) {
14038                            outFilters.add(new IntentFilter(pa));
14039                        }
14040                        if (outActivities != null) {
14041                            outActivities.add(pa.mPref.mComponent);
14042                        }
14043                    }
14044                }
14045            }
14046        }
14047
14048        return num;
14049    }
14050
14051    @Override
14052    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14053            int userId) {
14054        int callingUid = Binder.getCallingUid();
14055        if (callingUid != Process.SYSTEM_UID) {
14056            throw new SecurityException(
14057                    "addPersistentPreferredActivity can only be run by the system");
14058        }
14059        if (filter.countActions() == 0) {
14060            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14061            return;
14062        }
14063        synchronized (mPackages) {
14064            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14065                    " :");
14066            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14067            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14068                    new PersistentPreferredActivity(filter, activity));
14069            scheduleWritePackageRestrictionsLocked(userId);
14070        }
14071    }
14072
14073    @Override
14074    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14075        int callingUid = Binder.getCallingUid();
14076        if (callingUid != Process.SYSTEM_UID) {
14077            throw new SecurityException(
14078                    "clearPackagePersistentPreferredActivities can only be run by the system");
14079        }
14080        ArrayList<PersistentPreferredActivity> removed = null;
14081        boolean changed = false;
14082        synchronized (mPackages) {
14083            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14084                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14085                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14086                        .valueAt(i);
14087                if (userId != thisUserId) {
14088                    continue;
14089                }
14090                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14091                while (it.hasNext()) {
14092                    PersistentPreferredActivity ppa = it.next();
14093                    // Mark entry for removal only if it matches the package name.
14094                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14095                        if (removed == null) {
14096                            removed = new ArrayList<PersistentPreferredActivity>();
14097                        }
14098                        removed.add(ppa);
14099                    }
14100                }
14101                if (removed != null) {
14102                    for (int j=0; j<removed.size(); j++) {
14103                        PersistentPreferredActivity ppa = removed.get(j);
14104                        ppir.removeFilter(ppa);
14105                    }
14106                    changed = true;
14107                }
14108            }
14109
14110            if (changed) {
14111                scheduleWritePackageRestrictionsLocked(userId);
14112            }
14113        }
14114    }
14115
14116    /**
14117     * Common machinery for picking apart a restored XML blob and passing
14118     * it to a caller-supplied functor to be applied to the running system.
14119     */
14120    private void restoreFromXml(XmlPullParser parser, int userId,
14121            String expectedStartTag, BlobXmlRestorer functor)
14122            throws IOException, XmlPullParserException {
14123        int type;
14124        while ((type = parser.next()) != XmlPullParser.START_TAG
14125                && type != XmlPullParser.END_DOCUMENT) {
14126        }
14127        if (type != XmlPullParser.START_TAG) {
14128            // oops didn't find a start tag?!
14129            if (DEBUG_BACKUP) {
14130                Slog.e(TAG, "Didn't find start tag during restore");
14131            }
14132            return;
14133        }
14134
14135        // this is supposed to be TAG_PREFERRED_BACKUP
14136        if (!expectedStartTag.equals(parser.getName())) {
14137            if (DEBUG_BACKUP) {
14138                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14139            }
14140            return;
14141        }
14142
14143        // skip interfering stuff, then we're aligned with the backing implementation
14144        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14145        functor.apply(parser, userId);
14146    }
14147
14148    private interface BlobXmlRestorer {
14149        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14150    }
14151
14152    /**
14153     * Non-Binder method, support for the backup/restore mechanism: write the
14154     * full set of preferred activities in its canonical XML format.  Returns the
14155     * XML output as a byte array, or null if there is none.
14156     */
14157    @Override
14158    public byte[] getPreferredActivityBackup(int userId) {
14159        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14160            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14161        }
14162
14163        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14164        try {
14165            final XmlSerializer serializer = new FastXmlSerializer();
14166            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14167            serializer.startDocument(null, true);
14168            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14169
14170            synchronized (mPackages) {
14171                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14172            }
14173
14174            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14175            serializer.endDocument();
14176            serializer.flush();
14177        } catch (Exception e) {
14178            if (DEBUG_BACKUP) {
14179                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14180            }
14181            return null;
14182        }
14183
14184        return dataStream.toByteArray();
14185    }
14186
14187    @Override
14188    public void restorePreferredActivities(byte[] backup, int userId) {
14189        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14190            throw new SecurityException("Only the system may call restorePreferredActivities()");
14191        }
14192
14193        try {
14194            final XmlPullParser parser = Xml.newPullParser();
14195            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14196            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14197                    new BlobXmlRestorer() {
14198                        @Override
14199                        public void apply(XmlPullParser parser, int userId)
14200                                throws XmlPullParserException, IOException {
14201                            synchronized (mPackages) {
14202                                mSettings.readPreferredActivitiesLPw(parser, userId);
14203                            }
14204                        }
14205                    } );
14206        } catch (Exception e) {
14207            if (DEBUG_BACKUP) {
14208                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14209            }
14210        }
14211    }
14212
14213    /**
14214     * Non-Binder method, support for the backup/restore mechanism: write the
14215     * default browser (etc) settings in its canonical XML format.  Returns the default
14216     * browser XML representation as a byte array, or null if there is none.
14217     */
14218    @Override
14219    public byte[] getDefaultAppsBackup(int userId) {
14220        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14221            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14222        }
14223
14224        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14225        try {
14226            final XmlSerializer serializer = new FastXmlSerializer();
14227            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14228            serializer.startDocument(null, true);
14229            serializer.startTag(null, TAG_DEFAULT_APPS);
14230
14231            synchronized (mPackages) {
14232                mSettings.writeDefaultAppsLPr(serializer, userId);
14233            }
14234
14235            serializer.endTag(null, TAG_DEFAULT_APPS);
14236            serializer.endDocument();
14237            serializer.flush();
14238        } catch (Exception e) {
14239            if (DEBUG_BACKUP) {
14240                Slog.e(TAG, "Unable to write default apps for backup", e);
14241            }
14242            return null;
14243        }
14244
14245        return dataStream.toByteArray();
14246    }
14247
14248    @Override
14249    public void restoreDefaultApps(byte[] backup, int userId) {
14250        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14251            throw new SecurityException("Only the system may call restoreDefaultApps()");
14252        }
14253
14254        try {
14255            final XmlPullParser parser = Xml.newPullParser();
14256            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14257            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14258                    new BlobXmlRestorer() {
14259                        @Override
14260                        public void apply(XmlPullParser parser, int userId)
14261                                throws XmlPullParserException, IOException {
14262                            synchronized (mPackages) {
14263                                mSettings.readDefaultAppsLPw(parser, userId);
14264                            }
14265                        }
14266                    } );
14267        } catch (Exception e) {
14268            if (DEBUG_BACKUP) {
14269                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14270            }
14271        }
14272    }
14273
14274    @Override
14275    public byte[] getIntentFilterVerificationBackup(int userId) {
14276        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14277            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14278        }
14279
14280        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14281        try {
14282            final XmlSerializer serializer = new FastXmlSerializer();
14283            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14284            serializer.startDocument(null, true);
14285            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14286
14287            synchronized (mPackages) {
14288                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14289            }
14290
14291            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14292            serializer.endDocument();
14293            serializer.flush();
14294        } catch (Exception e) {
14295            if (DEBUG_BACKUP) {
14296                Slog.e(TAG, "Unable to write default apps for backup", e);
14297            }
14298            return null;
14299        }
14300
14301        return dataStream.toByteArray();
14302    }
14303
14304    @Override
14305    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14306        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14307            throw new SecurityException("Only the system may call restorePreferredActivities()");
14308        }
14309
14310        try {
14311            final XmlPullParser parser = Xml.newPullParser();
14312            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14313            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14314                    new BlobXmlRestorer() {
14315                        @Override
14316                        public void apply(XmlPullParser parser, int userId)
14317                                throws XmlPullParserException, IOException {
14318                            synchronized (mPackages) {
14319                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14320                                mSettings.writeLPr();
14321                            }
14322                        }
14323                    } );
14324        } catch (Exception e) {
14325            if (DEBUG_BACKUP) {
14326                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14327            }
14328        }
14329    }
14330
14331    @Override
14332    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14333            int sourceUserId, int targetUserId, int flags) {
14334        mContext.enforceCallingOrSelfPermission(
14335                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14336        int callingUid = Binder.getCallingUid();
14337        enforceOwnerRights(ownerPackage, callingUid);
14338        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14339        if (intentFilter.countActions() == 0) {
14340            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14341            return;
14342        }
14343        synchronized (mPackages) {
14344            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14345                    ownerPackage, targetUserId, flags);
14346            CrossProfileIntentResolver resolver =
14347                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14348            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14349            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14350            if (existing != null) {
14351                int size = existing.size();
14352                for (int i = 0; i < size; i++) {
14353                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14354                        return;
14355                    }
14356                }
14357            }
14358            resolver.addFilter(newFilter);
14359            scheduleWritePackageRestrictionsLocked(sourceUserId);
14360        }
14361    }
14362
14363    @Override
14364    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14365        mContext.enforceCallingOrSelfPermission(
14366                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14367        int callingUid = Binder.getCallingUid();
14368        enforceOwnerRights(ownerPackage, callingUid);
14369        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14370        synchronized (mPackages) {
14371            CrossProfileIntentResolver resolver =
14372                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14373            ArraySet<CrossProfileIntentFilter> set =
14374                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14375            for (CrossProfileIntentFilter filter : set) {
14376                if (filter.getOwnerPackage().equals(ownerPackage)) {
14377                    resolver.removeFilter(filter);
14378                }
14379            }
14380            scheduleWritePackageRestrictionsLocked(sourceUserId);
14381        }
14382    }
14383
14384    // Enforcing that callingUid is owning pkg on userId
14385    private void enforceOwnerRights(String pkg, int callingUid) {
14386        // The system owns everything.
14387        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14388            return;
14389        }
14390        int callingUserId = UserHandle.getUserId(callingUid);
14391        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14392        if (pi == null) {
14393            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14394                    + callingUserId);
14395        }
14396        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14397            throw new SecurityException("Calling uid " + callingUid
14398                    + " does not own package " + pkg);
14399        }
14400    }
14401
14402    @Override
14403    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14404        Intent intent = new Intent(Intent.ACTION_MAIN);
14405        intent.addCategory(Intent.CATEGORY_HOME);
14406
14407        final int callingUserId = UserHandle.getCallingUserId();
14408        List<ResolveInfo> list = queryIntentActivities(intent, null,
14409                PackageManager.GET_META_DATA, callingUserId);
14410        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14411                true, false, false, callingUserId);
14412
14413        allHomeCandidates.clear();
14414        if (list != null) {
14415            for (ResolveInfo ri : list) {
14416                allHomeCandidates.add(ri);
14417            }
14418        }
14419        return (preferred == null || preferred.activityInfo == null)
14420                ? null
14421                : new ComponentName(preferred.activityInfo.packageName,
14422                        preferred.activityInfo.name);
14423    }
14424
14425    @Override
14426    public void setApplicationEnabledSetting(String appPackageName,
14427            int newState, int flags, int userId, String callingPackage) {
14428        if (!sUserManager.exists(userId)) return;
14429        if (callingPackage == null) {
14430            callingPackage = Integer.toString(Binder.getCallingUid());
14431        }
14432        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14433    }
14434
14435    @Override
14436    public void setComponentEnabledSetting(ComponentName componentName,
14437            int newState, int flags, int userId) {
14438        if (!sUserManager.exists(userId)) return;
14439        setEnabledSetting(componentName.getPackageName(),
14440                componentName.getClassName(), newState, flags, userId, null);
14441    }
14442
14443    private void setEnabledSetting(final String packageName, String className, int newState,
14444            final int flags, int userId, String callingPackage) {
14445        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14446              || newState == COMPONENT_ENABLED_STATE_ENABLED
14447              || newState == COMPONENT_ENABLED_STATE_DISABLED
14448              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14449              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14450            throw new IllegalArgumentException("Invalid new component state: "
14451                    + newState);
14452        }
14453        PackageSetting pkgSetting;
14454        final int uid = Binder.getCallingUid();
14455        final int permission = mContext.checkCallingOrSelfPermission(
14456                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14457        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14458        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14459        boolean sendNow = false;
14460        boolean isApp = (className == null);
14461        String componentName = isApp ? packageName : className;
14462        int packageUid = -1;
14463        ArrayList<String> components;
14464
14465        // writer
14466        synchronized (mPackages) {
14467            pkgSetting = mSettings.mPackages.get(packageName);
14468            if (pkgSetting == null) {
14469                if (className == null) {
14470                    throw new IllegalArgumentException(
14471                            "Unknown package: " + packageName);
14472                }
14473                throw new IllegalArgumentException(
14474                        "Unknown component: " + packageName
14475                        + "/" + className);
14476            }
14477            // Allow root and verify that userId is not being specified by a different user
14478            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14479                throw new SecurityException(
14480                        "Permission Denial: attempt to change component state from pid="
14481                        + Binder.getCallingPid()
14482                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14483            }
14484            if (className == null) {
14485                // We're dealing with an application/package level state change
14486                if (pkgSetting.getEnabled(userId) == newState) {
14487                    // Nothing to do
14488                    return;
14489                }
14490                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14491                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14492                    // Don't care about who enables an app.
14493                    callingPackage = null;
14494                }
14495                pkgSetting.setEnabled(newState, userId, callingPackage);
14496                // pkgSetting.pkg.mSetEnabled = newState;
14497            } else {
14498                // We're dealing with a component level state change
14499                // First, verify that this is a valid class name.
14500                PackageParser.Package pkg = pkgSetting.pkg;
14501                if (pkg == null || !pkg.hasComponentClassName(className)) {
14502                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14503                        throw new IllegalArgumentException("Component class " + className
14504                                + " does not exist in " + packageName);
14505                    } else {
14506                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14507                                + className + " does not exist in " + packageName);
14508                    }
14509                }
14510                switch (newState) {
14511                case COMPONENT_ENABLED_STATE_ENABLED:
14512                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14513                        return;
14514                    }
14515                    break;
14516                case COMPONENT_ENABLED_STATE_DISABLED:
14517                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14518                        return;
14519                    }
14520                    break;
14521                case COMPONENT_ENABLED_STATE_DEFAULT:
14522                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14523                        return;
14524                    }
14525                    break;
14526                default:
14527                    Slog.e(TAG, "Invalid new component state: " + newState);
14528                    return;
14529                }
14530            }
14531            scheduleWritePackageRestrictionsLocked(userId);
14532            components = mPendingBroadcasts.get(userId, packageName);
14533            final boolean newPackage = components == null;
14534            if (newPackage) {
14535                components = new ArrayList<String>();
14536            }
14537            if (!components.contains(componentName)) {
14538                components.add(componentName);
14539            }
14540            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14541                sendNow = true;
14542                // Purge entry from pending broadcast list if another one exists already
14543                // since we are sending one right away.
14544                mPendingBroadcasts.remove(userId, packageName);
14545            } else {
14546                if (newPackage) {
14547                    mPendingBroadcasts.put(userId, packageName, components);
14548                }
14549                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14550                    // Schedule a message
14551                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14552                }
14553            }
14554        }
14555
14556        long callingId = Binder.clearCallingIdentity();
14557        try {
14558            if (sendNow) {
14559                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14560                sendPackageChangedBroadcast(packageName,
14561                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14562            }
14563        } finally {
14564            Binder.restoreCallingIdentity(callingId);
14565        }
14566    }
14567
14568    private void sendPackageChangedBroadcast(String packageName,
14569            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14570        if (DEBUG_INSTALL)
14571            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14572                    + componentNames);
14573        Bundle extras = new Bundle(4);
14574        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14575        String nameList[] = new String[componentNames.size()];
14576        componentNames.toArray(nameList);
14577        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14578        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14579        extras.putInt(Intent.EXTRA_UID, packageUid);
14580        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14581                new int[] {UserHandle.getUserId(packageUid)});
14582    }
14583
14584    @Override
14585    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14586        if (!sUserManager.exists(userId)) return;
14587        final int uid = Binder.getCallingUid();
14588        final int permission = mContext.checkCallingOrSelfPermission(
14589                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14590        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14591        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14592        // writer
14593        synchronized (mPackages) {
14594            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14595                    allowedByPermission, uid, userId)) {
14596                scheduleWritePackageRestrictionsLocked(userId);
14597            }
14598        }
14599    }
14600
14601    @Override
14602    public String getInstallerPackageName(String packageName) {
14603        // reader
14604        synchronized (mPackages) {
14605            return mSettings.getInstallerPackageNameLPr(packageName);
14606        }
14607    }
14608
14609    @Override
14610    public int getApplicationEnabledSetting(String packageName, int userId) {
14611        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14612        int uid = Binder.getCallingUid();
14613        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14614        // reader
14615        synchronized (mPackages) {
14616            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14617        }
14618    }
14619
14620    @Override
14621    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14622        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14623        int uid = Binder.getCallingUid();
14624        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14625        // reader
14626        synchronized (mPackages) {
14627            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14628        }
14629    }
14630
14631    @Override
14632    public void enterSafeMode() {
14633        enforceSystemOrRoot("Only the system can request entering safe mode");
14634
14635        if (!mSystemReady) {
14636            mSafeMode = true;
14637        }
14638    }
14639
14640    @Override
14641    public void systemReady() {
14642        mSystemReady = true;
14643
14644        // Read the compatibilty setting when the system is ready.
14645        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14646                mContext.getContentResolver(),
14647                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14648        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14649        if (DEBUG_SETTINGS) {
14650            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14651        }
14652
14653        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14654
14655        synchronized (mPackages) {
14656            // Verify that all of the preferred activity components actually
14657            // exist.  It is possible for applications to be updated and at
14658            // that point remove a previously declared activity component that
14659            // had been set as a preferred activity.  We try to clean this up
14660            // the next time we encounter that preferred activity, but it is
14661            // possible for the user flow to never be able to return to that
14662            // situation so here we do a sanity check to make sure we haven't
14663            // left any junk around.
14664            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14665            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14666                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14667                removed.clear();
14668                for (PreferredActivity pa : pir.filterSet()) {
14669                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14670                        removed.add(pa);
14671                    }
14672                }
14673                if (removed.size() > 0) {
14674                    for (int r=0; r<removed.size(); r++) {
14675                        PreferredActivity pa = removed.get(r);
14676                        Slog.w(TAG, "Removing dangling preferred activity: "
14677                                + pa.mPref.mComponent);
14678                        pir.removeFilter(pa);
14679                    }
14680                    mSettings.writePackageRestrictionsLPr(
14681                            mSettings.mPreferredActivities.keyAt(i));
14682                }
14683            }
14684
14685            for (int userId : UserManagerService.getInstance().getUserIds()) {
14686                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14687                    grantPermissionsUserIds = ArrayUtils.appendInt(
14688                            grantPermissionsUserIds, userId);
14689                }
14690            }
14691        }
14692        sUserManager.systemReady();
14693
14694        // If we upgraded grant all default permissions before kicking off.
14695        for (int userId : grantPermissionsUserIds) {
14696            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14697        }
14698
14699        // Kick off any messages waiting for system ready
14700        if (mPostSystemReadyMessages != null) {
14701            for (Message msg : mPostSystemReadyMessages) {
14702                msg.sendToTarget();
14703            }
14704            mPostSystemReadyMessages = null;
14705        }
14706
14707        // Watch for external volumes that come and go over time
14708        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14709        storage.registerListener(mStorageListener);
14710
14711        mInstallerService.systemReady();
14712        mPackageDexOptimizer.systemReady();
14713
14714        MountServiceInternal mountServiceInternal = LocalServices.getService(
14715                MountServiceInternal.class);
14716        mountServiceInternal.addExternalStoragePolicy(
14717                new MountServiceInternal.ExternalStorageMountPolicy() {
14718            @Override
14719            public int getMountMode(int uid, String packageName) {
14720                if (Process.isIsolated(uid)) {
14721                    return Zygote.MOUNT_EXTERNAL_NONE;
14722                }
14723                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14724                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14725                }
14726                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14727                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14728                }
14729                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14730                    return Zygote.MOUNT_EXTERNAL_READ;
14731                }
14732                return Zygote.MOUNT_EXTERNAL_WRITE;
14733            }
14734
14735            @Override
14736            public boolean hasExternalStorage(int uid, String packageName) {
14737                return true;
14738            }
14739        });
14740    }
14741
14742    @Override
14743    public boolean isSafeMode() {
14744        return mSafeMode;
14745    }
14746
14747    @Override
14748    public boolean hasSystemUidErrors() {
14749        return mHasSystemUidErrors;
14750    }
14751
14752    static String arrayToString(int[] array) {
14753        StringBuffer buf = new StringBuffer(128);
14754        buf.append('[');
14755        if (array != null) {
14756            for (int i=0; i<array.length; i++) {
14757                if (i > 0) buf.append(", ");
14758                buf.append(array[i]);
14759            }
14760        }
14761        buf.append(']');
14762        return buf.toString();
14763    }
14764
14765    static class DumpState {
14766        public static final int DUMP_LIBS = 1 << 0;
14767        public static final int DUMP_FEATURES = 1 << 1;
14768        public static final int DUMP_RESOLVERS = 1 << 2;
14769        public static final int DUMP_PERMISSIONS = 1 << 3;
14770        public static final int DUMP_PACKAGES = 1 << 4;
14771        public static final int DUMP_SHARED_USERS = 1 << 5;
14772        public static final int DUMP_MESSAGES = 1 << 6;
14773        public static final int DUMP_PROVIDERS = 1 << 7;
14774        public static final int DUMP_VERIFIERS = 1 << 8;
14775        public static final int DUMP_PREFERRED = 1 << 9;
14776        public static final int DUMP_PREFERRED_XML = 1 << 10;
14777        public static final int DUMP_KEYSETS = 1 << 11;
14778        public static final int DUMP_VERSION = 1 << 12;
14779        public static final int DUMP_INSTALLS = 1 << 13;
14780        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14781        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14782
14783        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14784
14785        private int mTypes;
14786
14787        private int mOptions;
14788
14789        private boolean mTitlePrinted;
14790
14791        private SharedUserSetting mSharedUser;
14792
14793        public boolean isDumping(int type) {
14794            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14795                return true;
14796            }
14797
14798            return (mTypes & type) != 0;
14799        }
14800
14801        public void setDump(int type) {
14802            mTypes |= type;
14803        }
14804
14805        public boolean isOptionEnabled(int option) {
14806            return (mOptions & option) != 0;
14807        }
14808
14809        public void setOptionEnabled(int option) {
14810            mOptions |= option;
14811        }
14812
14813        public boolean onTitlePrinted() {
14814            final boolean printed = mTitlePrinted;
14815            mTitlePrinted = true;
14816            return printed;
14817        }
14818
14819        public boolean getTitlePrinted() {
14820            return mTitlePrinted;
14821        }
14822
14823        public void setTitlePrinted(boolean enabled) {
14824            mTitlePrinted = enabled;
14825        }
14826
14827        public SharedUserSetting getSharedUser() {
14828            return mSharedUser;
14829        }
14830
14831        public void setSharedUser(SharedUserSetting user) {
14832            mSharedUser = user;
14833        }
14834    }
14835
14836    @Override
14837    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14838        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14839                != PackageManager.PERMISSION_GRANTED) {
14840            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14841                    + Binder.getCallingPid()
14842                    + ", uid=" + Binder.getCallingUid()
14843                    + " without permission "
14844                    + android.Manifest.permission.DUMP);
14845            return;
14846        }
14847
14848        DumpState dumpState = new DumpState();
14849        boolean fullPreferred = false;
14850        boolean checkin = false;
14851
14852        String packageName = null;
14853        ArraySet<String> permissionNames = null;
14854
14855        int opti = 0;
14856        while (opti < args.length) {
14857            String opt = args[opti];
14858            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14859                break;
14860            }
14861            opti++;
14862
14863            if ("-a".equals(opt)) {
14864                // Right now we only know how to print all.
14865            } else if ("-h".equals(opt)) {
14866                pw.println("Package manager dump options:");
14867                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14868                pw.println("    --checkin: dump for a checkin");
14869                pw.println("    -f: print details of intent filters");
14870                pw.println("    -h: print this help");
14871                pw.println("  cmd may be one of:");
14872                pw.println("    l[ibraries]: list known shared libraries");
14873                pw.println("    f[ibraries]: list device features");
14874                pw.println("    k[eysets]: print known keysets");
14875                pw.println("    r[esolvers]: dump intent resolvers");
14876                pw.println("    perm[issions]: dump permissions");
14877                pw.println("    permission [name ...]: dump declaration and use of given permission");
14878                pw.println("    pref[erred]: print preferred package settings");
14879                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14880                pw.println("    prov[iders]: dump content providers");
14881                pw.println("    p[ackages]: dump installed packages");
14882                pw.println("    s[hared-users]: dump shared user IDs");
14883                pw.println("    m[essages]: print collected runtime messages");
14884                pw.println("    v[erifiers]: print package verifier info");
14885                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14886                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14887                pw.println("    version: print database version info");
14888                pw.println("    write: write current settings now");
14889                pw.println("    installs: details about install sessions");
14890                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14891                pw.println("    <package.name>: info about given package");
14892                return;
14893            } else if ("--checkin".equals(opt)) {
14894                checkin = true;
14895            } else if ("-f".equals(opt)) {
14896                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14897            } else {
14898                pw.println("Unknown argument: " + opt + "; use -h for help");
14899            }
14900        }
14901
14902        // Is the caller requesting to dump a particular piece of data?
14903        if (opti < args.length) {
14904            String cmd = args[opti];
14905            opti++;
14906            // Is this a package name?
14907            if ("android".equals(cmd) || cmd.contains(".")) {
14908                packageName = cmd;
14909                // When dumping a single package, we always dump all of its
14910                // filter information since the amount of data will be reasonable.
14911                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14912            } else if ("check-permission".equals(cmd)) {
14913                if (opti >= args.length) {
14914                    pw.println("Error: check-permission missing permission argument");
14915                    return;
14916                }
14917                String perm = args[opti];
14918                opti++;
14919                if (opti >= args.length) {
14920                    pw.println("Error: check-permission missing package argument");
14921                    return;
14922                }
14923                String pkg = args[opti];
14924                opti++;
14925                int user = UserHandle.getUserId(Binder.getCallingUid());
14926                if (opti < args.length) {
14927                    try {
14928                        user = Integer.parseInt(args[opti]);
14929                    } catch (NumberFormatException e) {
14930                        pw.println("Error: check-permission user argument is not a number: "
14931                                + args[opti]);
14932                        return;
14933                    }
14934                }
14935                pw.println(checkPermission(perm, pkg, user));
14936                return;
14937            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14938                dumpState.setDump(DumpState.DUMP_LIBS);
14939            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14940                dumpState.setDump(DumpState.DUMP_FEATURES);
14941            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14942                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14943            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14944                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14945            } else if ("permission".equals(cmd)) {
14946                if (opti >= args.length) {
14947                    pw.println("Error: permission requires permission name");
14948                    return;
14949                }
14950                permissionNames = new ArraySet<>();
14951                while (opti < args.length) {
14952                    permissionNames.add(args[opti]);
14953                    opti++;
14954                }
14955                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14956                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14957            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14958                dumpState.setDump(DumpState.DUMP_PREFERRED);
14959            } else if ("preferred-xml".equals(cmd)) {
14960                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14961                if (opti < args.length && "--full".equals(args[opti])) {
14962                    fullPreferred = true;
14963                    opti++;
14964                }
14965            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14966                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14967            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14968                dumpState.setDump(DumpState.DUMP_PACKAGES);
14969            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14970                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14971            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14972                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14973            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14974                dumpState.setDump(DumpState.DUMP_MESSAGES);
14975            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14976                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14977            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14978                    || "intent-filter-verifiers".equals(cmd)) {
14979                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14980            } else if ("version".equals(cmd)) {
14981                dumpState.setDump(DumpState.DUMP_VERSION);
14982            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14983                dumpState.setDump(DumpState.DUMP_KEYSETS);
14984            } else if ("installs".equals(cmd)) {
14985                dumpState.setDump(DumpState.DUMP_INSTALLS);
14986            } else if ("write".equals(cmd)) {
14987                synchronized (mPackages) {
14988                    mSettings.writeLPr();
14989                    pw.println("Settings written.");
14990                    return;
14991                }
14992            }
14993        }
14994
14995        if (checkin) {
14996            pw.println("vers,1");
14997        }
14998
14999        // reader
15000        synchronized (mPackages) {
15001            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15002                if (!checkin) {
15003                    if (dumpState.onTitlePrinted())
15004                        pw.println();
15005                    pw.println("Database versions:");
15006                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15007                }
15008            }
15009
15010            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15011                if (!checkin) {
15012                    if (dumpState.onTitlePrinted())
15013                        pw.println();
15014                    pw.println("Verifiers:");
15015                    pw.print("  Required: ");
15016                    pw.print(mRequiredVerifierPackage);
15017                    pw.print(" (uid=");
15018                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15019                    pw.println(")");
15020                } else if (mRequiredVerifierPackage != null) {
15021                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15022                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15023                }
15024            }
15025
15026            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15027                    packageName == null) {
15028                if (mIntentFilterVerifierComponent != null) {
15029                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15030                    if (!checkin) {
15031                        if (dumpState.onTitlePrinted())
15032                            pw.println();
15033                        pw.println("Intent Filter Verifier:");
15034                        pw.print("  Using: ");
15035                        pw.print(verifierPackageName);
15036                        pw.print(" (uid=");
15037                        pw.print(getPackageUid(verifierPackageName, 0));
15038                        pw.println(")");
15039                    } else if (verifierPackageName != null) {
15040                        pw.print("ifv,"); pw.print(verifierPackageName);
15041                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15042                    }
15043                } else {
15044                    pw.println();
15045                    pw.println("No Intent Filter Verifier available!");
15046                }
15047            }
15048
15049            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15050                boolean printedHeader = false;
15051                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15052                while (it.hasNext()) {
15053                    String name = it.next();
15054                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15055                    if (!checkin) {
15056                        if (!printedHeader) {
15057                            if (dumpState.onTitlePrinted())
15058                                pw.println();
15059                            pw.println("Libraries:");
15060                            printedHeader = true;
15061                        }
15062                        pw.print("  ");
15063                    } else {
15064                        pw.print("lib,");
15065                    }
15066                    pw.print(name);
15067                    if (!checkin) {
15068                        pw.print(" -> ");
15069                    }
15070                    if (ent.path != null) {
15071                        if (!checkin) {
15072                            pw.print("(jar) ");
15073                            pw.print(ent.path);
15074                        } else {
15075                            pw.print(",jar,");
15076                            pw.print(ent.path);
15077                        }
15078                    } else {
15079                        if (!checkin) {
15080                            pw.print("(apk) ");
15081                            pw.print(ent.apk);
15082                        } else {
15083                            pw.print(",apk,");
15084                            pw.print(ent.apk);
15085                        }
15086                    }
15087                    pw.println();
15088                }
15089            }
15090
15091            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15092                if (dumpState.onTitlePrinted())
15093                    pw.println();
15094                if (!checkin) {
15095                    pw.println("Features:");
15096                }
15097                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15098                while (it.hasNext()) {
15099                    String name = it.next();
15100                    if (!checkin) {
15101                        pw.print("  ");
15102                    } else {
15103                        pw.print("feat,");
15104                    }
15105                    pw.println(name);
15106                }
15107            }
15108
15109            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15110                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15111                        : "Activity Resolver Table:", "  ", packageName,
15112                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15113                    dumpState.setTitlePrinted(true);
15114                }
15115                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15116                        : "Receiver Resolver Table:", "  ", packageName,
15117                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15118                    dumpState.setTitlePrinted(true);
15119                }
15120                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15121                        : "Service Resolver Table:", "  ", packageName,
15122                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15123                    dumpState.setTitlePrinted(true);
15124                }
15125                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15126                        : "Provider Resolver Table:", "  ", packageName,
15127                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15128                    dumpState.setTitlePrinted(true);
15129                }
15130            }
15131
15132            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15133                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15134                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15135                    int user = mSettings.mPreferredActivities.keyAt(i);
15136                    if (pir.dump(pw,
15137                            dumpState.getTitlePrinted()
15138                                ? "\nPreferred Activities User " + user + ":"
15139                                : "Preferred Activities User " + user + ":", "  ",
15140                            packageName, true, false)) {
15141                        dumpState.setTitlePrinted(true);
15142                    }
15143                }
15144            }
15145
15146            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15147                pw.flush();
15148                FileOutputStream fout = new FileOutputStream(fd);
15149                BufferedOutputStream str = new BufferedOutputStream(fout);
15150                XmlSerializer serializer = new FastXmlSerializer();
15151                try {
15152                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15153                    serializer.startDocument(null, true);
15154                    serializer.setFeature(
15155                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15156                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15157                    serializer.endDocument();
15158                    serializer.flush();
15159                } catch (IllegalArgumentException e) {
15160                    pw.println("Failed writing: " + e);
15161                } catch (IllegalStateException e) {
15162                    pw.println("Failed writing: " + e);
15163                } catch (IOException e) {
15164                    pw.println("Failed writing: " + e);
15165                }
15166            }
15167
15168            if (!checkin
15169                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15170                    && packageName == null) {
15171                pw.println();
15172                int count = mSettings.mPackages.size();
15173                if (count == 0) {
15174                    pw.println("No applications!");
15175                    pw.println();
15176                } else {
15177                    final String prefix = "  ";
15178                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15179                    if (allPackageSettings.size() == 0) {
15180                        pw.println("No domain preferred apps!");
15181                        pw.println();
15182                    } else {
15183                        pw.println("App verification status:");
15184                        pw.println();
15185                        count = 0;
15186                        for (PackageSetting ps : allPackageSettings) {
15187                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15188                            if (ivi == null || ivi.getPackageName() == null) continue;
15189                            pw.println(prefix + "Package: " + ivi.getPackageName());
15190                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15191                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15192                            pw.println();
15193                            count++;
15194                        }
15195                        if (count == 0) {
15196                            pw.println(prefix + "No app verification established.");
15197                            pw.println();
15198                        }
15199                        for (int userId : sUserManager.getUserIds()) {
15200                            pw.println("App linkages for user " + userId + ":");
15201                            pw.println();
15202                            count = 0;
15203                            for (PackageSetting ps : allPackageSettings) {
15204                                final long status = ps.getDomainVerificationStatusForUser(userId);
15205                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15206                                    continue;
15207                                }
15208                                pw.println(prefix + "Package: " + ps.name);
15209                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15210                                String statusStr = IntentFilterVerificationInfo.
15211                                        getStatusStringFromValue(status);
15212                                pw.println(prefix + "Status:  " + statusStr);
15213                                pw.println();
15214                                count++;
15215                            }
15216                            if (count == 0) {
15217                                pw.println(prefix + "No configured app linkages.");
15218                                pw.println();
15219                            }
15220                        }
15221                    }
15222                }
15223            }
15224
15225            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15226                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15227                if (packageName == null && permissionNames == null) {
15228                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15229                        if (iperm == 0) {
15230                            if (dumpState.onTitlePrinted())
15231                                pw.println();
15232                            pw.println("AppOp Permissions:");
15233                        }
15234                        pw.print("  AppOp Permission ");
15235                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15236                        pw.println(":");
15237                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15238                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15239                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15240                        }
15241                    }
15242                }
15243            }
15244
15245            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15246                boolean printedSomething = false;
15247                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15248                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15249                        continue;
15250                    }
15251                    if (!printedSomething) {
15252                        if (dumpState.onTitlePrinted())
15253                            pw.println();
15254                        pw.println("Registered ContentProviders:");
15255                        printedSomething = true;
15256                    }
15257                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15258                    pw.print("    "); pw.println(p.toString());
15259                }
15260                printedSomething = false;
15261                for (Map.Entry<String, PackageParser.Provider> entry :
15262                        mProvidersByAuthority.entrySet()) {
15263                    PackageParser.Provider p = entry.getValue();
15264                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15265                        continue;
15266                    }
15267                    if (!printedSomething) {
15268                        if (dumpState.onTitlePrinted())
15269                            pw.println();
15270                        pw.println("ContentProvider Authorities:");
15271                        printedSomething = true;
15272                    }
15273                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15274                    pw.print("    "); pw.println(p.toString());
15275                    if (p.info != null && p.info.applicationInfo != null) {
15276                        final String appInfo = p.info.applicationInfo.toString();
15277                        pw.print("      applicationInfo="); pw.println(appInfo);
15278                    }
15279                }
15280            }
15281
15282            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15283                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15284            }
15285
15286            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15287                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15288            }
15289
15290            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15291                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15292            }
15293
15294            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15295                // XXX should handle packageName != null by dumping only install data that
15296                // the given package is involved with.
15297                if (dumpState.onTitlePrinted()) pw.println();
15298                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15299            }
15300
15301            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15302                if (dumpState.onTitlePrinted()) pw.println();
15303                mSettings.dumpReadMessagesLPr(pw, dumpState);
15304
15305                pw.println();
15306                pw.println("Package warning messages:");
15307                BufferedReader in = null;
15308                String line = null;
15309                try {
15310                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15311                    while ((line = in.readLine()) != null) {
15312                        if (line.contains("ignored: updated version")) continue;
15313                        pw.println(line);
15314                    }
15315                } catch (IOException ignored) {
15316                } finally {
15317                    IoUtils.closeQuietly(in);
15318                }
15319            }
15320
15321            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15322                BufferedReader in = null;
15323                String line = null;
15324                try {
15325                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15326                    while ((line = in.readLine()) != null) {
15327                        if (line.contains("ignored: updated version")) continue;
15328                        pw.print("msg,");
15329                        pw.println(line);
15330                    }
15331                } catch (IOException ignored) {
15332                } finally {
15333                    IoUtils.closeQuietly(in);
15334                }
15335            }
15336        }
15337    }
15338
15339    private String dumpDomainString(String packageName) {
15340        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15341        List<IntentFilter> filters = getAllIntentFilters(packageName);
15342
15343        ArraySet<String> result = new ArraySet<>();
15344        if (iviList.size() > 0) {
15345            for (IntentFilterVerificationInfo ivi : iviList) {
15346                for (String host : ivi.getDomains()) {
15347                    result.add(host);
15348                }
15349            }
15350        }
15351        if (filters != null && filters.size() > 0) {
15352            for (IntentFilter filter : filters) {
15353                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15354                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15355                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15356                    result.addAll(filter.getHostsList());
15357                }
15358            }
15359        }
15360
15361        StringBuilder sb = new StringBuilder(result.size() * 16);
15362        for (String domain : result) {
15363            if (sb.length() > 0) sb.append(" ");
15364            sb.append(domain);
15365        }
15366        return sb.toString();
15367    }
15368
15369    // ------- apps on sdcard specific code -------
15370    static final boolean DEBUG_SD_INSTALL = false;
15371
15372    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15373
15374    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15375
15376    private boolean mMediaMounted = false;
15377
15378    static String getEncryptKey() {
15379        try {
15380            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15381                    SD_ENCRYPTION_KEYSTORE_NAME);
15382            if (sdEncKey == null) {
15383                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15384                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15385                if (sdEncKey == null) {
15386                    Slog.e(TAG, "Failed to create encryption keys");
15387                    return null;
15388                }
15389            }
15390            return sdEncKey;
15391        } catch (NoSuchAlgorithmException nsae) {
15392            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15393            return null;
15394        } catch (IOException ioe) {
15395            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15396            return null;
15397        }
15398    }
15399
15400    /*
15401     * Update media status on PackageManager.
15402     */
15403    @Override
15404    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15405        int callingUid = Binder.getCallingUid();
15406        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15407            throw new SecurityException("Media status can only be updated by the system");
15408        }
15409        // reader; this apparently protects mMediaMounted, but should probably
15410        // be a different lock in that case.
15411        synchronized (mPackages) {
15412            Log.i(TAG, "Updating external media status from "
15413                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15414                    + (mediaStatus ? "mounted" : "unmounted"));
15415            if (DEBUG_SD_INSTALL)
15416                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15417                        + ", mMediaMounted=" + mMediaMounted);
15418            if (mediaStatus == mMediaMounted) {
15419                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15420                        : 0, -1);
15421                mHandler.sendMessage(msg);
15422                return;
15423            }
15424            mMediaMounted = mediaStatus;
15425        }
15426        // Queue up an async operation since the package installation may take a
15427        // little while.
15428        mHandler.post(new Runnable() {
15429            public void run() {
15430                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15431            }
15432        });
15433    }
15434
15435    /**
15436     * Called by MountService when the initial ASECs to scan are available.
15437     * Should block until all the ASEC containers are finished being scanned.
15438     */
15439    public void scanAvailableAsecs() {
15440        updateExternalMediaStatusInner(true, false, false);
15441        if (mShouldRestoreconData) {
15442            SELinuxMMAC.setRestoreconDone();
15443            mShouldRestoreconData = false;
15444        }
15445    }
15446
15447    /*
15448     * Collect information of applications on external media, map them against
15449     * existing containers and update information based on current mount status.
15450     * Please note that we always have to report status if reportStatus has been
15451     * set to true especially when unloading packages.
15452     */
15453    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15454            boolean externalStorage) {
15455        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15456        int[] uidArr = EmptyArray.INT;
15457
15458        final String[] list = PackageHelper.getSecureContainerList();
15459        if (ArrayUtils.isEmpty(list)) {
15460            Log.i(TAG, "No secure containers found");
15461        } else {
15462            // Process list of secure containers and categorize them
15463            // as active or stale based on their package internal state.
15464
15465            // reader
15466            synchronized (mPackages) {
15467                for (String cid : list) {
15468                    // Leave stages untouched for now; installer service owns them
15469                    if (PackageInstallerService.isStageName(cid)) continue;
15470
15471                    if (DEBUG_SD_INSTALL)
15472                        Log.i(TAG, "Processing container " + cid);
15473                    String pkgName = getAsecPackageName(cid);
15474                    if (pkgName == null) {
15475                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15476                        continue;
15477                    }
15478                    if (DEBUG_SD_INSTALL)
15479                        Log.i(TAG, "Looking for pkg : " + pkgName);
15480
15481                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15482                    if (ps == null) {
15483                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15484                        continue;
15485                    }
15486
15487                    /*
15488                     * Skip packages that are not external if we're unmounting
15489                     * external storage.
15490                     */
15491                    if (externalStorage && !isMounted && !isExternal(ps)) {
15492                        continue;
15493                    }
15494
15495                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15496                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15497                    // The package status is changed only if the code path
15498                    // matches between settings and the container id.
15499                    if (ps.codePathString != null
15500                            && ps.codePathString.startsWith(args.getCodePath())) {
15501                        if (DEBUG_SD_INSTALL) {
15502                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15503                                    + " at code path: " + ps.codePathString);
15504                        }
15505
15506                        // We do have a valid package installed on sdcard
15507                        processCids.put(args, ps.codePathString);
15508                        final int uid = ps.appId;
15509                        if (uid != -1) {
15510                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15511                        }
15512                    } else {
15513                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15514                                + ps.codePathString);
15515                    }
15516                }
15517            }
15518
15519            Arrays.sort(uidArr);
15520        }
15521
15522        // Process packages with valid entries.
15523        if (isMounted) {
15524            if (DEBUG_SD_INSTALL)
15525                Log.i(TAG, "Loading packages");
15526            loadMediaPackages(processCids, uidArr, externalStorage);
15527            startCleaningPackages();
15528            mInstallerService.onSecureContainersAvailable();
15529        } else {
15530            if (DEBUG_SD_INSTALL)
15531                Log.i(TAG, "Unloading packages");
15532            unloadMediaPackages(processCids, uidArr, reportStatus);
15533        }
15534    }
15535
15536    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15537            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15538        final int size = infos.size();
15539        final String[] packageNames = new String[size];
15540        final int[] packageUids = new int[size];
15541        for (int i = 0; i < size; i++) {
15542            final ApplicationInfo info = infos.get(i);
15543            packageNames[i] = info.packageName;
15544            packageUids[i] = info.uid;
15545        }
15546        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15547                finishedReceiver);
15548    }
15549
15550    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15551            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15552        sendResourcesChangedBroadcast(mediaStatus, replacing,
15553                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15554    }
15555
15556    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15557            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15558        int size = pkgList.length;
15559        if (size > 0) {
15560            // Send broadcasts here
15561            Bundle extras = new Bundle();
15562            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15563            if (uidArr != null) {
15564                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15565            }
15566            if (replacing) {
15567                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15568            }
15569            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15570                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15571            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15572        }
15573    }
15574
15575   /*
15576     * Look at potentially valid container ids from processCids If package
15577     * information doesn't match the one on record or package scanning fails,
15578     * the cid is added to list of removeCids. We currently don't delete stale
15579     * containers.
15580     */
15581    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15582            boolean externalStorage) {
15583        ArrayList<String> pkgList = new ArrayList<String>();
15584        Set<AsecInstallArgs> keys = processCids.keySet();
15585
15586        for (AsecInstallArgs args : keys) {
15587            String codePath = processCids.get(args);
15588            if (DEBUG_SD_INSTALL)
15589                Log.i(TAG, "Loading container : " + args.cid);
15590            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15591            try {
15592                // Make sure there are no container errors first.
15593                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15594                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15595                            + " when installing from sdcard");
15596                    continue;
15597                }
15598                // Check code path here.
15599                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15600                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15601                            + " does not match one in settings " + codePath);
15602                    continue;
15603                }
15604                // Parse package
15605                int parseFlags = mDefParseFlags;
15606                if (args.isExternalAsec()) {
15607                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15608                }
15609                if (args.isFwdLocked()) {
15610                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15611                }
15612
15613                synchronized (mInstallLock) {
15614                    PackageParser.Package pkg = null;
15615                    try {
15616                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15617                    } catch (PackageManagerException e) {
15618                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15619                    }
15620                    // Scan the package
15621                    if (pkg != null) {
15622                        /*
15623                         * TODO why is the lock being held? doPostInstall is
15624                         * called in other places without the lock. This needs
15625                         * to be straightened out.
15626                         */
15627                        // writer
15628                        synchronized (mPackages) {
15629                            retCode = PackageManager.INSTALL_SUCCEEDED;
15630                            pkgList.add(pkg.packageName);
15631                            // Post process args
15632                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15633                                    pkg.applicationInfo.uid);
15634                        }
15635                    } else {
15636                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15637                    }
15638                }
15639
15640            } finally {
15641                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15642                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15643                }
15644            }
15645        }
15646        // writer
15647        synchronized (mPackages) {
15648            // If the platform SDK has changed since the last time we booted,
15649            // we need to re-grant app permission to catch any new ones that
15650            // appear. This is really a hack, and means that apps can in some
15651            // cases get permissions that the user didn't initially explicitly
15652            // allow... it would be nice to have some better way to handle
15653            // this situation.
15654            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
15655                    : mSettings.getInternalVersion();
15656            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
15657                    : StorageManager.UUID_PRIVATE_INTERNAL;
15658
15659            int updateFlags = UPDATE_PERMISSIONS_ALL;
15660            if (ver.sdkVersion != mSdkVersion) {
15661                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15662                        + mSdkVersion + "; regranting permissions for external");
15663                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15664            }
15665            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
15666
15667            // Yay, everything is now upgraded
15668            ver.forceCurrent();
15669
15670            // can downgrade to reader
15671            // Persist settings
15672            mSettings.writeLPr();
15673        }
15674        // Send a broadcast to let everyone know we are done processing
15675        if (pkgList.size() > 0) {
15676            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15677        }
15678    }
15679
15680   /*
15681     * Utility method to unload a list of specified containers
15682     */
15683    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15684        // Just unmount all valid containers.
15685        for (AsecInstallArgs arg : cidArgs) {
15686            synchronized (mInstallLock) {
15687                arg.doPostDeleteLI(false);
15688           }
15689       }
15690   }
15691
15692    /*
15693     * Unload packages mounted on external media. This involves deleting package
15694     * data from internal structures, sending broadcasts about diabled packages,
15695     * gc'ing to free up references, unmounting all secure containers
15696     * corresponding to packages on external media, and posting a
15697     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15698     * that we always have to post this message if status has been requested no
15699     * matter what.
15700     */
15701    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15702            final boolean reportStatus) {
15703        if (DEBUG_SD_INSTALL)
15704            Log.i(TAG, "unloading media packages");
15705        ArrayList<String> pkgList = new ArrayList<String>();
15706        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15707        final Set<AsecInstallArgs> keys = processCids.keySet();
15708        for (AsecInstallArgs args : keys) {
15709            String pkgName = args.getPackageName();
15710            if (DEBUG_SD_INSTALL)
15711                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15712            // Delete package internally
15713            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15714            synchronized (mInstallLock) {
15715                boolean res = deletePackageLI(pkgName, null, false, null, null,
15716                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15717                if (res) {
15718                    pkgList.add(pkgName);
15719                } else {
15720                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15721                    failedList.add(args);
15722                }
15723            }
15724        }
15725
15726        // reader
15727        synchronized (mPackages) {
15728            // We didn't update the settings after removing each package;
15729            // write them now for all packages.
15730            mSettings.writeLPr();
15731        }
15732
15733        // We have to absolutely send UPDATED_MEDIA_STATUS only
15734        // after confirming that all the receivers processed the ordered
15735        // broadcast when packages get disabled, force a gc to clean things up.
15736        // and unload all the containers.
15737        if (pkgList.size() > 0) {
15738            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15739                    new IIntentReceiver.Stub() {
15740                public void performReceive(Intent intent, int resultCode, String data,
15741                        Bundle extras, boolean ordered, boolean sticky,
15742                        int sendingUser) throws RemoteException {
15743                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15744                            reportStatus ? 1 : 0, 1, keys);
15745                    mHandler.sendMessage(msg);
15746                }
15747            });
15748        } else {
15749            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15750                    keys);
15751            mHandler.sendMessage(msg);
15752        }
15753    }
15754
15755    private void loadPrivatePackages(final VolumeInfo vol) {
15756        mHandler.post(new Runnable() {
15757            @Override
15758            public void run() {
15759                loadPrivatePackagesInner(vol);
15760            }
15761        });
15762    }
15763
15764    private void loadPrivatePackagesInner(VolumeInfo vol) {
15765        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15766        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15767
15768        final VersionInfo ver;
15769        final List<PackageSetting> packages;
15770        synchronized (mPackages) {
15771            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15772            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15773        }
15774
15775        for (PackageSetting ps : packages) {
15776            synchronized (mInstallLock) {
15777                final PackageParser.Package pkg;
15778                try {
15779                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15780                    loaded.add(pkg.applicationInfo);
15781                } catch (PackageManagerException e) {
15782                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15783                }
15784
15785                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15786                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15787                }
15788            }
15789        }
15790
15791        synchronized (mPackages) {
15792            int updateFlags = UPDATE_PERMISSIONS_ALL;
15793            if (ver.sdkVersion != mSdkVersion) {
15794                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15795                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15796                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15797            }
15798            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
15799
15800            // Yay, everything is now upgraded
15801            ver.forceCurrent();
15802
15803            mSettings.writeLPr();
15804        }
15805
15806        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15807        sendResourcesChangedBroadcast(true, false, loaded, null);
15808    }
15809
15810    private void unloadPrivatePackages(final VolumeInfo vol) {
15811        mHandler.post(new Runnable() {
15812            @Override
15813            public void run() {
15814                unloadPrivatePackagesInner(vol);
15815            }
15816        });
15817    }
15818
15819    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15820        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15821        synchronized (mInstallLock) {
15822        synchronized (mPackages) {
15823            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15824            for (PackageSetting ps : packages) {
15825                if (ps.pkg == null) continue;
15826
15827                final ApplicationInfo info = ps.pkg.applicationInfo;
15828                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15829                if (deletePackageLI(ps.name, null, false, null, null,
15830                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15831                    unloaded.add(info);
15832                } else {
15833                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15834                }
15835            }
15836
15837            mSettings.writeLPr();
15838        }
15839        }
15840
15841        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15842        sendResourcesChangedBroadcast(false, false, unloaded, null);
15843    }
15844
15845    /**
15846     * Examine all users present on given mounted volume, and destroy data
15847     * belonging to users that are no longer valid, or whose user ID has been
15848     * recycled.
15849     */
15850    private void reconcileUsers(String volumeUuid) {
15851        final File[] files = FileUtils
15852                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15853        for (File file : files) {
15854            if (!file.isDirectory()) continue;
15855
15856            final int userId;
15857            final UserInfo info;
15858            try {
15859                userId = Integer.parseInt(file.getName());
15860                info = sUserManager.getUserInfo(userId);
15861            } catch (NumberFormatException e) {
15862                Slog.w(TAG, "Invalid user directory " + file);
15863                continue;
15864            }
15865
15866            boolean destroyUser = false;
15867            if (info == null) {
15868                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15869                        + " because no matching user was found");
15870                destroyUser = true;
15871            } else {
15872                try {
15873                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15874                } catch (IOException e) {
15875                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15876                            + " because we failed to enforce serial number: " + e);
15877                    destroyUser = true;
15878                }
15879            }
15880
15881            if (destroyUser) {
15882                synchronized (mInstallLock) {
15883                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15884                }
15885            }
15886        }
15887
15888        final UserManager um = mContext.getSystemService(UserManager.class);
15889        for (UserInfo user : um.getUsers()) {
15890            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15891            if (userDir.exists()) continue;
15892
15893            try {
15894                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15895                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15896            } catch (IOException e) {
15897                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15898            }
15899        }
15900    }
15901
15902    /**
15903     * Examine all apps present on given mounted volume, and destroy apps that
15904     * aren't expected, either due to uninstallation or reinstallation on
15905     * another volume.
15906     */
15907    private void reconcileApps(String volumeUuid) {
15908        final File[] files = FileUtils
15909                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15910        for (File file : files) {
15911            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15912                    && !PackageInstallerService.isStageName(file.getName());
15913            if (!isPackage) {
15914                // Ignore entries which are not packages
15915                continue;
15916            }
15917
15918            boolean destroyApp = false;
15919            String packageName = null;
15920            try {
15921                final PackageLite pkg = PackageParser.parsePackageLite(file,
15922                        PackageParser.PARSE_MUST_BE_APK);
15923                packageName = pkg.packageName;
15924
15925                synchronized (mPackages) {
15926                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15927                    if (ps == null) {
15928                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15929                                + volumeUuid + " because we found no install record");
15930                        destroyApp = true;
15931                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15932                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15933                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15934                        destroyApp = true;
15935                    }
15936                }
15937
15938            } catch (PackageParserException e) {
15939                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15940                destroyApp = true;
15941            }
15942
15943            if (destroyApp) {
15944                synchronized (mInstallLock) {
15945                    if (packageName != null) {
15946                        removeDataDirsLI(volumeUuid, packageName);
15947                    }
15948                    if (file.isDirectory()) {
15949                        mInstaller.rmPackageDir(file.getAbsolutePath());
15950                    } else {
15951                        file.delete();
15952                    }
15953                }
15954            }
15955        }
15956    }
15957
15958    private void unfreezePackage(String packageName) {
15959        synchronized (mPackages) {
15960            final PackageSetting ps = mSettings.mPackages.get(packageName);
15961            if (ps != null) {
15962                ps.frozen = false;
15963            }
15964        }
15965    }
15966
15967    @Override
15968    public int movePackage(final String packageName, final String volumeUuid) {
15969        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15970
15971        final int moveId = mNextMoveId.getAndIncrement();
15972        try {
15973            movePackageInternal(packageName, volumeUuid, moveId);
15974        } catch (PackageManagerException e) {
15975            Slog.w(TAG, "Failed to move " + packageName, e);
15976            mMoveCallbacks.notifyStatusChanged(moveId,
15977                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15978        }
15979        return moveId;
15980    }
15981
15982    private void movePackageInternal(final String packageName, final String volumeUuid,
15983            final int moveId) throws PackageManagerException {
15984        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15985        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15986        final PackageManager pm = mContext.getPackageManager();
15987
15988        final boolean currentAsec;
15989        final String currentVolumeUuid;
15990        final File codeFile;
15991        final String installerPackageName;
15992        final String packageAbiOverride;
15993        final int appId;
15994        final String seinfo;
15995        final String label;
15996
15997        // reader
15998        synchronized (mPackages) {
15999            final PackageParser.Package pkg = mPackages.get(packageName);
16000            final PackageSetting ps = mSettings.mPackages.get(packageName);
16001            if (pkg == null || ps == null) {
16002                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16003            }
16004
16005            if (pkg.applicationInfo.isSystemApp()) {
16006                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16007                        "Cannot move system application");
16008            }
16009
16010            if (pkg.applicationInfo.isExternalAsec()) {
16011                currentAsec = true;
16012                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16013            } else if (pkg.applicationInfo.isForwardLocked()) {
16014                currentAsec = true;
16015                currentVolumeUuid = "forward_locked";
16016            } else {
16017                currentAsec = false;
16018                currentVolumeUuid = ps.volumeUuid;
16019
16020                final File probe = new File(pkg.codePath);
16021                final File probeOat = new File(probe, "oat");
16022                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16023                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16024                            "Move only supported for modern cluster style installs");
16025                }
16026            }
16027
16028            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16029                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16030                        "Package already moved to " + volumeUuid);
16031            }
16032
16033            if (ps.frozen) {
16034                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16035                        "Failed to move already frozen package");
16036            }
16037            ps.frozen = true;
16038
16039            codeFile = new File(pkg.codePath);
16040            installerPackageName = ps.installerPackageName;
16041            packageAbiOverride = ps.cpuAbiOverrideString;
16042            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16043            seinfo = pkg.applicationInfo.seinfo;
16044            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16045        }
16046
16047        // Now that we're guarded by frozen state, kill app during move
16048        final long token = Binder.clearCallingIdentity();
16049        try {
16050            killApplication(packageName, appId, "move pkg");
16051        } finally {
16052            Binder.restoreCallingIdentity(token);
16053        }
16054
16055        final Bundle extras = new Bundle();
16056        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16057        extras.putString(Intent.EXTRA_TITLE, label);
16058        mMoveCallbacks.notifyCreated(moveId, extras);
16059
16060        int installFlags;
16061        final boolean moveCompleteApp;
16062        final File measurePath;
16063
16064        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16065            installFlags = INSTALL_INTERNAL;
16066            moveCompleteApp = !currentAsec;
16067            measurePath = Environment.getDataAppDirectory(volumeUuid);
16068        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16069            installFlags = INSTALL_EXTERNAL;
16070            moveCompleteApp = false;
16071            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16072        } else {
16073            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16074            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16075                    || !volume.isMountedWritable()) {
16076                unfreezePackage(packageName);
16077                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16078                        "Move location not mounted private volume");
16079            }
16080
16081            Preconditions.checkState(!currentAsec);
16082
16083            installFlags = INSTALL_INTERNAL;
16084            moveCompleteApp = true;
16085            measurePath = Environment.getDataAppDirectory(volumeUuid);
16086        }
16087
16088        final PackageStats stats = new PackageStats(null, -1);
16089        synchronized (mInstaller) {
16090            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16091                unfreezePackage(packageName);
16092                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16093                        "Failed to measure package size");
16094            }
16095        }
16096
16097        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16098                + stats.dataSize);
16099
16100        final long startFreeBytes = measurePath.getFreeSpace();
16101        final long sizeBytes;
16102        if (moveCompleteApp) {
16103            sizeBytes = stats.codeSize + stats.dataSize;
16104        } else {
16105            sizeBytes = stats.codeSize;
16106        }
16107
16108        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16109            unfreezePackage(packageName);
16110            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16111                    "Not enough free space to move");
16112        }
16113
16114        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16115
16116        final CountDownLatch installedLatch = new CountDownLatch(1);
16117        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16118            @Override
16119            public void onUserActionRequired(Intent intent) throws RemoteException {
16120                throw new IllegalStateException();
16121            }
16122
16123            @Override
16124            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16125                    Bundle extras) throws RemoteException {
16126                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16127                        + PackageManager.installStatusToString(returnCode, msg));
16128
16129                installedLatch.countDown();
16130
16131                // Regardless of success or failure of the move operation,
16132                // always unfreeze the package
16133                unfreezePackage(packageName);
16134
16135                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16136                switch (status) {
16137                    case PackageInstaller.STATUS_SUCCESS:
16138                        mMoveCallbacks.notifyStatusChanged(moveId,
16139                                PackageManager.MOVE_SUCCEEDED);
16140                        break;
16141                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16142                        mMoveCallbacks.notifyStatusChanged(moveId,
16143                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16144                        break;
16145                    default:
16146                        mMoveCallbacks.notifyStatusChanged(moveId,
16147                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16148                        break;
16149                }
16150            }
16151        };
16152
16153        final MoveInfo move;
16154        if (moveCompleteApp) {
16155            // Kick off a thread to report progress estimates
16156            new Thread() {
16157                @Override
16158                public void run() {
16159                    while (true) {
16160                        try {
16161                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16162                                break;
16163                            }
16164                        } catch (InterruptedException ignored) {
16165                        }
16166
16167                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16168                        final int progress = 10 + (int) MathUtils.constrain(
16169                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16170                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16171                    }
16172                }
16173            }.start();
16174
16175            final String dataAppName = codeFile.getName();
16176            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16177                    dataAppName, appId, seinfo);
16178        } else {
16179            move = null;
16180        }
16181
16182        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16183
16184        final Message msg = mHandler.obtainMessage(INIT_COPY);
16185        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16186        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16187                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16188        mHandler.sendMessage(msg);
16189    }
16190
16191    @Override
16192    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16193        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16194
16195        final int realMoveId = mNextMoveId.getAndIncrement();
16196        final Bundle extras = new Bundle();
16197        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16198        mMoveCallbacks.notifyCreated(realMoveId, extras);
16199
16200        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16201            @Override
16202            public void onCreated(int moveId, Bundle extras) {
16203                // Ignored
16204            }
16205
16206            @Override
16207            public void onStatusChanged(int moveId, int status, long estMillis) {
16208                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16209            }
16210        };
16211
16212        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16213        storage.setPrimaryStorageUuid(volumeUuid, callback);
16214        return realMoveId;
16215    }
16216
16217    @Override
16218    public int getMoveStatus(int moveId) {
16219        mContext.enforceCallingOrSelfPermission(
16220                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16221        return mMoveCallbacks.mLastStatus.get(moveId);
16222    }
16223
16224    @Override
16225    public void registerMoveCallback(IPackageMoveObserver callback) {
16226        mContext.enforceCallingOrSelfPermission(
16227                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16228        mMoveCallbacks.register(callback);
16229    }
16230
16231    @Override
16232    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16233        mContext.enforceCallingOrSelfPermission(
16234                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16235        mMoveCallbacks.unregister(callback);
16236    }
16237
16238    @Override
16239    public boolean setInstallLocation(int loc) {
16240        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16241                null);
16242        if (getInstallLocation() == loc) {
16243            return true;
16244        }
16245        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16246                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16247            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16248                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16249            return true;
16250        }
16251        return false;
16252   }
16253
16254    @Override
16255    public int getInstallLocation() {
16256        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16257                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16258                PackageHelper.APP_INSTALL_AUTO);
16259    }
16260
16261    /** Called by UserManagerService */
16262    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16263        mDirtyUsers.remove(userHandle);
16264        mSettings.removeUserLPw(userHandle);
16265        mPendingBroadcasts.remove(userHandle);
16266        if (mInstaller != null) {
16267            // Technically, we shouldn't be doing this with the package lock
16268            // held.  However, this is very rare, and there is already so much
16269            // other disk I/O going on, that we'll let it slide for now.
16270            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16271            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16272                final String volumeUuid = vol.getFsUuid();
16273                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16274                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16275            }
16276        }
16277        mUserNeedsBadging.delete(userHandle);
16278        removeUnusedPackagesLILPw(userManager, userHandle);
16279    }
16280
16281    /**
16282     * We're removing userHandle and would like to remove any downloaded packages
16283     * that are no longer in use by any other user.
16284     * @param userHandle the user being removed
16285     */
16286    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16287        final boolean DEBUG_CLEAN_APKS = false;
16288        int [] users = userManager.getUserIdsLPr();
16289        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16290        while (psit.hasNext()) {
16291            PackageSetting ps = psit.next();
16292            if (ps.pkg == null) {
16293                continue;
16294            }
16295            final String packageName = ps.pkg.packageName;
16296            // Skip over if system app
16297            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16298                continue;
16299            }
16300            if (DEBUG_CLEAN_APKS) {
16301                Slog.i(TAG, "Checking package " + packageName);
16302            }
16303            boolean keep = false;
16304            for (int i = 0; i < users.length; i++) {
16305                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16306                    keep = true;
16307                    if (DEBUG_CLEAN_APKS) {
16308                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16309                                + users[i]);
16310                    }
16311                    break;
16312                }
16313            }
16314            if (!keep) {
16315                if (DEBUG_CLEAN_APKS) {
16316                    Slog.i(TAG, "  Removing package " + packageName);
16317                }
16318                mHandler.post(new Runnable() {
16319                    public void run() {
16320                        deletePackageX(packageName, userHandle, 0);
16321                    } //end run
16322                });
16323            }
16324        }
16325    }
16326
16327    /** Called by UserManagerService */
16328    void createNewUserLILPw(int userHandle) {
16329        if (mInstaller != null) {
16330            mInstaller.createUserConfig(userHandle);
16331            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16332            applyFactoryDefaultBrowserLPw(userHandle);
16333            primeDomainVerificationsLPw(userHandle);
16334        }
16335    }
16336
16337    void newUserCreated(final int userHandle) {
16338        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16339    }
16340
16341    @Override
16342    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16343        mContext.enforceCallingOrSelfPermission(
16344                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16345                "Only package verification agents can read the verifier device identity");
16346
16347        synchronized (mPackages) {
16348            return mSettings.getVerifierDeviceIdentityLPw();
16349        }
16350    }
16351
16352    @Override
16353    public void setPermissionEnforced(String permission, boolean enforced) {
16354        // TODO: Now that we no longer change GID for storage, this should to away.
16355        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16356                "setPermissionEnforced");
16357        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16358            synchronized (mPackages) {
16359                if (mSettings.mReadExternalStorageEnforced == null
16360                        || mSettings.mReadExternalStorageEnforced != enforced) {
16361                    mSettings.mReadExternalStorageEnforced = enforced;
16362                    mSettings.writeLPr();
16363                }
16364            }
16365            // kill any non-foreground processes so we restart them and
16366            // grant/revoke the GID.
16367            final IActivityManager am = ActivityManagerNative.getDefault();
16368            if (am != null) {
16369                final long token = Binder.clearCallingIdentity();
16370                try {
16371                    am.killProcessesBelowForeground("setPermissionEnforcement");
16372                } catch (RemoteException e) {
16373                } finally {
16374                    Binder.restoreCallingIdentity(token);
16375                }
16376            }
16377        } else {
16378            throw new IllegalArgumentException("No selective enforcement for " + permission);
16379        }
16380    }
16381
16382    @Override
16383    @Deprecated
16384    public boolean isPermissionEnforced(String permission) {
16385        return true;
16386    }
16387
16388    @Override
16389    public boolean isStorageLow() {
16390        final long token = Binder.clearCallingIdentity();
16391        try {
16392            final DeviceStorageMonitorInternal
16393                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16394            if (dsm != null) {
16395                return dsm.isMemoryLow();
16396            } else {
16397                return false;
16398            }
16399        } finally {
16400            Binder.restoreCallingIdentity(token);
16401        }
16402    }
16403
16404    @Override
16405    public IPackageInstaller getPackageInstaller() {
16406        return mInstallerService;
16407    }
16408
16409    private boolean userNeedsBadging(int userId) {
16410        int index = mUserNeedsBadging.indexOfKey(userId);
16411        if (index < 0) {
16412            final UserInfo userInfo;
16413            final long token = Binder.clearCallingIdentity();
16414            try {
16415                userInfo = sUserManager.getUserInfo(userId);
16416            } finally {
16417                Binder.restoreCallingIdentity(token);
16418            }
16419            final boolean b;
16420            if (userInfo != null && userInfo.isManagedProfile()) {
16421                b = true;
16422            } else {
16423                b = false;
16424            }
16425            mUserNeedsBadging.put(userId, b);
16426            return b;
16427        }
16428        return mUserNeedsBadging.valueAt(index);
16429    }
16430
16431    @Override
16432    public KeySet getKeySetByAlias(String packageName, String alias) {
16433        if (packageName == null || alias == null) {
16434            return null;
16435        }
16436        synchronized(mPackages) {
16437            final PackageParser.Package pkg = mPackages.get(packageName);
16438            if (pkg == null) {
16439                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16440                throw new IllegalArgumentException("Unknown package: " + packageName);
16441            }
16442            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16443            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16444        }
16445    }
16446
16447    @Override
16448    public KeySet getSigningKeySet(String packageName) {
16449        if (packageName == null) {
16450            return null;
16451        }
16452        synchronized(mPackages) {
16453            final PackageParser.Package pkg = mPackages.get(packageName);
16454            if (pkg == null) {
16455                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16456                throw new IllegalArgumentException("Unknown package: " + packageName);
16457            }
16458            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16459                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16460                throw new SecurityException("May not access signing KeySet of other apps.");
16461            }
16462            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16463            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16464        }
16465    }
16466
16467    @Override
16468    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16469        if (packageName == null || ks == null) {
16470            return false;
16471        }
16472        synchronized(mPackages) {
16473            final PackageParser.Package pkg = mPackages.get(packageName);
16474            if (pkg == null) {
16475                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16476                throw new IllegalArgumentException("Unknown package: " + packageName);
16477            }
16478            IBinder ksh = ks.getToken();
16479            if (ksh instanceof KeySetHandle) {
16480                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16481                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16482            }
16483            return false;
16484        }
16485    }
16486
16487    @Override
16488    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16489        if (packageName == null || ks == null) {
16490            return false;
16491        }
16492        synchronized(mPackages) {
16493            final PackageParser.Package pkg = mPackages.get(packageName);
16494            if (pkg == null) {
16495                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16496                throw new IllegalArgumentException("Unknown package: " + packageName);
16497            }
16498            IBinder ksh = ks.getToken();
16499            if (ksh instanceof KeySetHandle) {
16500                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16501                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16502            }
16503            return false;
16504        }
16505    }
16506
16507    public void getUsageStatsIfNoPackageUsageInfo() {
16508        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16509            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16510            if (usm == null) {
16511                throw new IllegalStateException("UsageStatsManager must be initialized");
16512            }
16513            long now = System.currentTimeMillis();
16514            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16515            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16516                String packageName = entry.getKey();
16517                PackageParser.Package pkg = mPackages.get(packageName);
16518                if (pkg == null) {
16519                    continue;
16520                }
16521                UsageStats usage = entry.getValue();
16522                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16523                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16524            }
16525        }
16526    }
16527
16528    /**
16529     * Check and throw if the given before/after packages would be considered a
16530     * downgrade.
16531     */
16532    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16533            throws PackageManagerException {
16534        if (after.versionCode < before.mVersionCode) {
16535            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16536                    "Update version code " + after.versionCode + " is older than current "
16537                    + before.mVersionCode);
16538        } else if (after.versionCode == before.mVersionCode) {
16539            if (after.baseRevisionCode < before.baseRevisionCode) {
16540                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16541                        "Update base revision code " + after.baseRevisionCode
16542                        + " is older than current " + before.baseRevisionCode);
16543            }
16544
16545            if (!ArrayUtils.isEmpty(after.splitNames)) {
16546                for (int i = 0; i < after.splitNames.length; i++) {
16547                    final String splitName = after.splitNames[i];
16548                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16549                    if (j != -1) {
16550                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16551                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16552                                    "Update split " + splitName + " revision code "
16553                                    + after.splitRevisionCodes[i] + " is older than current "
16554                                    + before.splitRevisionCodes[j]);
16555                        }
16556                    }
16557                }
16558            }
16559        }
16560    }
16561
16562    private static class MoveCallbacks extends Handler {
16563        private static final int MSG_CREATED = 1;
16564        private static final int MSG_STATUS_CHANGED = 2;
16565
16566        private final RemoteCallbackList<IPackageMoveObserver>
16567                mCallbacks = new RemoteCallbackList<>();
16568
16569        private final SparseIntArray mLastStatus = new SparseIntArray();
16570
16571        public MoveCallbacks(Looper looper) {
16572            super(looper);
16573        }
16574
16575        public void register(IPackageMoveObserver callback) {
16576            mCallbacks.register(callback);
16577        }
16578
16579        public void unregister(IPackageMoveObserver callback) {
16580            mCallbacks.unregister(callback);
16581        }
16582
16583        @Override
16584        public void handleMessage(Message msg) {
16585            final SomeArgs args = (SomeArgs) msg.obj;
16586            final int n = mCallbacks.beginBroadcast();
16587            for (int i = 0; i < n; i++) {
16588                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16589                try {
16590                    invokeCallback(callback, msg.what, args);
16591                } catch (RemoteException ignored) {
16592                }
16593            }
16594            mCallbacks.finishBroadcast();
16595            args.recycle();
16596        }
16597
16598        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16599                throws RemoteException {
16600            switch (what) {
16601                case MSG_CREATED: {
16602                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16603                    break;
16604                }
16605                case MSG_STATUS_CHANGED: {
16606                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16607                    break;
16608                }
16609            }
16610        }
16611
16612        private void notifyCreated(int moveId, Bundle extras) {
16613            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16614
16615            final SomeArgs args = SomeArgs.obtain();
16616            args.argi1 = moveId;
16617            args.arg2 = extras;
16618            obtainMessage(MSG_CREATED, args).sendToTarget();
16619        }
16620
16621        private void notifyStatusChanged(int moveId, int status) {
16622            notifyStatusChanged(moveId, status, -1);
16623        }
16624
16625        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16626            Slog.v(TAG, "Move " + moveId + " status " + status);
16627
16628            final SomeArgs args = SomeArgs.obtain();
16629            args.argi1 = moveId;
16630            args.argi2 = status;
16631            args.arg3 = estMillis;
16632            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16633
16634            synchronized (mLastStatus) {
16635                mLastStatus.put(moveId, status);
16636            }
16637        }
16638    }
16639
16640    private final class OnPermissionChangeListeners extends Handler {
16641        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16642
16643        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16644                new RemoteCallbackList<>();
16645
16646        public OnPermissionChangeListeners(Looper looper) {
16647            super(looper);
16648        }
16649
16650        @Override
16651        public void handleMessage(Message msg) {
16652            switch (msg.what) {
16653                case MSG_ON_PERMISSIONS_CHANGED: {
16654                    final int uid = msg.arg1;
16655                    handleOnPermissionsChanged(uid);
16656                } break;
16657            }
16658        }
16659
16660        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16661            mPermissionListeners.register(listener);
16662
16663        }
16664
16665        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16666            mPermissionListeners.unregister(listener);
16667        }
16668
16669        public void onPermissionsChanged(int uid) {
16670            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16671                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16672            }
16673        }
16674
16675        private void handleOnPermissionsChanged(int uid) {
16676            final int count = mPermissionListeners.beginBroadcast();
16677            try {
16678                for (int i = 0; i < count; i++) {
16679                    IOnPermissionsChangeListener callback = mPermissionListeners
16680                            .getBroadcastItem(i);
16681                    try {
16682                        callback.onPermissionsChanged(uid);
16683                    } catch (RemoteException e) {
16684                        Log.e(TAG, "Permission listener is dead", e);
16685                    }
16686                }
16687            } finally {
16688                mPermissionListeners.finishBroadcast();
16689            }
16690        }
16691    }
16692
16693    private class PackageManagerInternalImpl extends PackageManagerInternal {
16694        @Override
16695        public void setLocationPackagesProvider(PackagesProvider provider) {
16696            synchronized (mPackages) {
16697                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16698            }
16699        }
16700
16701        @Override
16702        public void setImePackagesProvider(PackagesProvider provider) {
16703            synchronized (mPackages) {
16704                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16705            }
16706        }
16707
16708        @Override
16709        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16710            synchronized (mPackages) {
16711                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16712            }
16713        }
16714
16715        @Override
16716        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16717            synchronized (mPackages) {
16718                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16719            }
16720        }
16721
16722        @Override
16723        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16724            synchronized (mPackages) {
16725                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16726            }
16727        }
16728
16729        @Override
16730        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16731            synchronized (mPackages) {
16732                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16733            }
16734        }
16735
16736        @Override
16737        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16738            synchronized (mPackages) {
16739                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16740            }
16741        }
16742
16743        @Override
16744        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16745            synchronized (mPackages) {
16746                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16747                        packageName, userId);
16748            }
16749        }
16750
16751        @Override
16752        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16753            synchronized (mPackages) {
16754                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16755                        packageName, userId);
16756            }
16757        }
16758        @Override
16759        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16760            synchronized (mPackages) {
16761                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16762                        packageName, userId);
16763            }
16764        }
16765    }
16766
16767    @Override
16768    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16769        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16770        synchronized (mPackages) {
16771            final long identity = Binder.clearCallingIdentity();
16772            try {
16773                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16774                        packageNames, userId);
16775            } finally {
16776                Binder.restoreCallingIdentity(identity);
16777            }
16778        }
16779    }
16780
16781    private static void enforceSystemOrPhoneCaller(String tag) {
16782        int callingUid = Binder.getCallingUid();
16783        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16784            throw new SecurityException(
16785                    "Cannot call " + tag + " from UID " + callingUid);
16786        }
16787    }
16788}
16789