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        PermissionsState permissionsState = sb.getPermissionsState();
1717
1718        for (String permission : pkg.requestedPermissions) {
1719            BasePermission bp = mSettings.mPermissions.get(permission);
1720            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1721                    || ArrayUtils.contains(grantedPermissions, permission))) {
1722                permissionsState.grantRuntimePermission(bp, userId);
1723            }
1724        }
1725    }
1726
1727    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1728        Bundle extras = null;
1729        switch (res.returnCode) {
1730            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1731                extras = new Bundle();
1732                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1733                        res.origPermission);
1734                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1735                        res.origPackage);
1736                break;
1737            }
1738            case PackageManager.INSTALL_SUCCEEDED: {
1739                extras = new Bundle();
1740                extras.putBoolean(Intent.EXTRA_REPLACING,
1741                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1742                break;
1743            }
1744        }
1745        return extras;
1746    }
1747
1748    void scheduleWriteSettingsLocked() {
1749        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1750            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1751        }
1752    }
1753
1754    void scheduleWritePackageRestrictionsLocked(int userId) {
1755        if (!sUserManager.exists(userId)) return;
1756        mDirtyUsers.add(userId);
1757        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1758            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1759        }
1760    }
1761
1762    public static PackageManagerService main(Context context, Installer installer,
1763            boolean factoryTest, boolean onlyCore) {
1764        PackageManagerService m = new PackageManagerService(context, installer,
1765                factoryTest, onlyCore);
1766        ServiceManager.addService("package", m);
1767        return m;
1768    }
1769
1770    static String[] splitString(String str, char sep) {
1771        int count = 1;
1772        int i = 0;
1773        while ((i=str.indexOf(sep, i)) >= 0) {
1774            count++;
1775            i++;
1776        }
1777
1778        String[] res = new String[count];
1779        i=0;
1780        count = 0;
1781        int lastI=0;
1782        while ((i=str.indexOf(sep, i)) >= 0) {
1783            res[count] = str.substring(lastI, i);
1784            count++;
1785            i++;
1786            lastI = i;
1787        }
1788        res[count] = str.substring(lastI, str.length());
1789        return res;
1790    }
1791
1792    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1793        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1794                Context.DISPLAY_SERVICE);
1795        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1796    }
1797
1798    public PackageManagerService(Context context, Installer installer,
1799            boolean factoryTest, boolean onlyCore) {
1800        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1801                SystemClock.uptimeMillis());
1802
1803        if (mSdkVersion <= 0) {
1804            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1805        }
1806
1807        mContext = context;
1808        mFactoryTest = factoryTest;
1809        mOnlyCore = onlyCore;
1810        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1811        mMetrics = new DisplayMetrics();
1812        mSettings = new Settings(mPackages);
1813        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1814                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1815        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1816                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1817        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1818                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1819        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1820                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1821        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1822                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1823        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1824                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1825
1826        // TODO: add a property to control this?
1827        long dexOptLRUThresholdInMinutes;
1828        if (mLazyDexOpt) {
1829            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1830        } else {
1831            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1832        }
1833        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1834
1835        String separateProcesses = SystemProperties.get("debug.separate_processes");
1836        if (separateProcesses != null && separateProcesses.length() > 0) {
1837            if ("*".equals(separateProcesses)) {
1838                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1839                mSeparateProcesses = null;
1840                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1841            } else {
1842                mDefParseFlags = 0;
1843                mSeparateProcesses = separateProcesses.split(",");
1844                Slog.w(TAG, "Running with debug.separate_processes: "
1845                        + separateProcesses);
1846            }
1847        } else {
1848            mDefParseFlags = 0;
1849            mSeparateProcesses = null;
1850        }
1851
1852        mInstaller = installer;
1853        mPackageDexOptimizer = new PackageDexOptimizer(this);
1854        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1855
1856        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1857                FgThread.get().getLooper());
1858
1859        getDefaultDisplayMetrics(context, mMetrics);
1860
1861        SystemConfig systemConfig = SystemConfig.getInstance();
1862        mGlobalGids = systemConfig.getGlobalGids();
1863        mSystemPermissions = systemConfig.getSystemPermissions();
1864        mAvailableFeatures = systemConfig.getAvailableFeatures();
1865
1866        synchronized (mInstallLock) {
1867        // writer
1868        synchronized (mPackages) {
1869            mHandlerThread = new ServiceThread(TAG,
1870                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1871            mHandlerThread.start();
1872            mHandler = new PackageHandler(mHandlerThread.getLooper());
1873            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1874
1875            File dataDir = Environment.getDataDirectory();
1876            mAppDataDir = new File(dataDir, "data");
1877            mAppInstallDir = new File(dataDir, "app");
1878            mAppLib32InstallDir = new File(dataDir, "app-lib");
1879            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1880            mUserAppDataDir = new File(dataDir, "user");
1881            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1882
1883            sUserManager = new UserManagerService(context, this,
1884                    mInstallLock, mPackages);
1885
1886            // Propagate permission configuration in to package manager.
1887            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1888                    = systemConfig.getPermissions();
1889            for (int i=0; i<permConfig.size(); i++) {
1890                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1891                BasePermission bp = mSettings.mPermissions.get(perm.name);
1892                if (bp == null) {
1893                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1894                    mSettings.mPermissions.put(perm.name, bp);
1895                }
1896                if (perm.gids != null) {
1897                    bp.setGids(perm.gids, perm.perUser);
1898                }
1899            }
1900
1901            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1902            for (int i=0; i<libConfig.size(); i++) {
1903                mSharedLibraries.put(libConfig.keyAt(i),
1904                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1905            }
1906
1907            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1908
1909            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1910                    mSdkVersion, mOnlyCore);
1911
1912            String customResolverActivity = Resources.getSystem().getString(
1913                    R.string.config_customResolverActivity);
1914            if (TextUtils.isEmpty(customResolverActivity)) {
1915                customResolverActivity = null;
1916            } else {
1917                mCustomResolverComponentName = ComponentName.unflattenFromString(
1918                        customResolverActivity);
1919            }
1920
1921            long startTime = SystemClock.uptimeMillis();
1922
1923            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1924                    startTime);
1925
1926            // Set flag to monitor and not change apk file paths when
1927            // scanning install directories.
1928            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1929
1930            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1931
1932            /**
1933             * Add everything in the in the boot class path to the
1934             * list of process files because dexopt will have been run
1935             * if necessary during zygote startup.
1936             */
1937            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1938            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1939
1940            if (bootClassPath != null) {
1941                String[] bootClassPathElements = splitString(bootClassPath, ':');
1942                for (String element : bootClassPathElements) {
1943                    alreadyDexOpted.add(element);
1944                }
1945            } else {
1946                Slog.w(TAG, "No BOOTCLASSPATH found!");
1947            }
1948
1949            if (systemServerClassPath != null) {
1950                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1951                for (String element : systemServerClassPathElements) {
1952                    alreadyDexOpted.add(element);
1953                }
1954            } else {
1955                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1956            }
1957
1958            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1959            final String[] dexCodeInstructionSets =
1960                    getDexCodeInstructionSets(
1961                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1962
1963            /**
1964             * Ensure all external libraries have had dexopt run on them.
1965             */
1966            if (mSharedLibraries.size() > 0) {
1967                // NOTE: For now, we're compiling these system "shared libraries"
1968                // (and framework jars) into all available architectures. It's possible
1969                // to compile them only when we come across an app that uses them (there's
1970                // already logic for that in scanPackageLI) but that adds some complexity.
1971                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1972                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1973                        final String lib = libEntry.path;
1974                        if (lib == null) {
1975                            continue;
1976                        }
1977
1978                        try {
1979                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1980                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1981                                alreadyDexOpted.add(lib);
1982                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1983                            }
1984                        } catch (FileNotFoundException e) {
1985                            Slog.w(TAG, "Library not found: " + lib);
1986                        } catch (IOException e) {
1987                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1988                                    + e.getMessage());
1989                        }
1990                    }
1991                }
1992            }
1993
1994            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1995
1996            // Gross hack for now: we know this file doesn't contain any
1997            // code, so don't dexopt it to avoid the resulting log spew.
1998            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1999
2000            // Gross hack for now: we know this file is only part of
2001            // the boot class path for art, so don't dexopt it to
2002            // avoid the resulting log spew.
2003            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2004
2005            /**
2006             * There are a number of commands implemented in Java, which
2007             * we currently need to do the dexopt on so that they can be
2008             * run from a non-root shell.
2009             */
2010            String[] frameworkFiles = frameworkDir.list();
2011            if (frameworkFiles != null) {
2012                // TODO: We could compile these only for the most preferred ABI. We should
2013                // first double check that the dex files for these commands are not referenced
2014                // by other system apps.
2015                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2016                    for (int i=0; i<frameworkFiles.length; i++) {
2017                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2018                        String path = libPath.getPath();
2019                        // Skip the file if we already did it.
2020                        if (alreadyDexOpted.contains(path)) {
2021                            continue;
2022                        }
2023                        // Skip the file if it is not a type we want to dexopt.
2024                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2025                            continue;
2026                        }
2027                        try {
2028                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2029                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2030                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2031                            }
2032                        } catch (FileNotFoundException e) {
2033                            Slog.w(TAG, "Jar not found: " + path);
2034                        } catch (IOException e) {
2035                            Slog.w(TAG, "Exception reading jar: " + path, e);
2036                        }
2037                    }
2038                }
2039            }
2040
2041            final VersionInfo ver = mSettings.getInternalVersion();
2042            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2043            // when upgrading from pre-M, promote system app permissions from install to runtime
2044            mPromoteSystemApps =
2045                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2046
2047            // save off the names of pre-existing system packages prior to scanning; we don't
2048            // want to automatically grant runtime permissions for new system apps
2049            if (mPromoteSystemApps) {
2050                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2051                while (pkgSettingIter.hasNext()) {
2052                    PackageSetting ps = pkgSettingIter.next();
2053                    if (isSystemApp(ps)) {
2054                        mExistingSystemPackages.add(ps.name);
2055                    }
2056                }
2057            }
2058
2059            // Collect vendor overlay packages.
2060            // (Do this before scanning any apps.)
2061            // For security and version matching reason, only consider
2062            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2063            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2064            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2065                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2066
2067            // Find base frameworks (resource packages without code).
2068            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2069                    | PackageParser.PARSE_IS_SYSTEM_DIR
2070                    | PackageParser.PARSE_IS_PRIVILEGED,
2071                    scanFlags | SCAN_NO_DEX, 0);
2072
2073            // Collected privileged system packages.
2074            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2075            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2076                    | PackageParser.PARSE_IS_SYSTEM_DIR
2077                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2078
2079            // Collect ordinary system packages.
2080            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2081            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2082                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2083
2084            // Collect all vendor packages.
2085            File vendorAppDir = new File("/vendor/app");
2086            try {
2087                vendorAppDir = vendorAppDir.getCanonicalFile();
2088            } catch (IOException e) {
2089                // failed to look up canonical path, continue with original one
2090            }
2091            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2092                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2093
2094            // Collect all OEM packages.
2095            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2096            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2097                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2098
2099            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2100            mInstaller.moveFiles();
2101
2102            // Prune any system packages that no longer exist.
2103            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2104            if (!mOnlyCore) {
2105                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2106                while (psit.hasNext()) {
2107                    PackageSetting ps = psit.next();
2108
2109                    /*
2110                     * If this is not a system app, it can't be a
2111                     * disable system app.
2112                     */
2113                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2114                        continue;
2115                    }
2116
2117                    /*
2118                     * If the package is scanned, it's not erased.
2119                     */
2120                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2121                    if (scannedPkg != null) {
2122                        /*
2123                         * If the system app is both scanned and in the
2124                         * disabled packages list, then it must have been
2125                         * added via OTA. Remove it from the currently
2126                         * scanned package so the previously user-installed
2127                         * application can be scanned.
2128                         */
2129                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2130                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2131                                    + ps.name + "; removing system app.  Last known codePath="
2132                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2133                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2134                                    + scannedPkg.mVersionCode);
2135                            removePackageLI(ps, true);
2136                            mExpectingBetter.put(ps.name, ps.codePath);
2137                        }
2138
2139                        continue;
2140                    }
2141
2142                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2143                        psit.remove();
2144                        logCriticalInfo(Log.WARN, "System package " + ps.name
2145                                + " no longer exists; wiping its data");
2146                        removeDataDirsLI(null, ps.name);
2147                    } else {
2148                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2149                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2150                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2151                        }
2152                    }
2153                }
2154            }
2155
2156            //look for any incomplete package installations
2157            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2158            //clean up list
2159            for(int i = 0; i < deletePkgsList.size(); i++) {
2160                //clean up here
2161                cleanupInstallFailedPackage(deletePkgsList.get(i));
2162            }
2163            //delete tmp files
2164            deleteTempPackageFiles();
2165
2166            // Remove any shared userIDs that have no associated packages
2167            mSettings.pruneSharedUsersLPw();
2168
2169            if (!mOnlyCore) {
2170                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2171                        SystemClock.uptimeMillis());
2172                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2173
2174                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2175                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2176
2177                /**
2178                 * Remove disable package settings for any updated system
2179                 * apps that were removed via an OTA. If they're not a
2180                 * previously-updated app, remove them completely.
2181                 * Otherwise, just revoke their system-level permissions.
2182                 */
2183                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2184                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2185                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2186
2187                    String msg;
2188                    if (deletedPkg == null) {
2189                        msg = "Updated system package " + deletedAppName
2190                                + " no longer exists; wiping its data";
2191                        removeDataDirsLI(null, deletedAppName);
2192                    } else {
2193                        msg = "Updated system app + " + deletedAppName
2194                                + " no longer present; removing system privileges for "
2195                                + deletedAppName;
2196
2197                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2198
2199                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2200                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2201                    }
2202                    logCriticalInfo(Log.WARN, msg);
2203                }
2204
2205                /**
2206                 * Make sure all system apps that we expected to appear on
2207                 * the userdata partition actually showed up. If they never
2208                 * appeared, crawl back and revive the system version.
2209                 */
2210                for (int i = 0; i < mExpectingBetter.size(); i++) {
2211                    final String packageName = mExpectingBetter.keyAt(i);
2212                    if (!mPackages.containsKey(packageName)) {
2213                        final File scanFile = mExpectingBetter.valueAt(i);
2214
2215                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2216                                + " but never showed up; reverting to system");
2217
2218                        final int reparseFlags;
2219                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2220                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2221                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2222                                    | PackageParser.PARSE_IS_PRIVILEGED;
2223                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2224                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2225                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2226                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2227                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2228                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2229                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2230                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2231                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2232                        } else {
2233                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2234                            continue;
2235                        }
2236
2237                        mSettings.enableSystemPackageLPw(packageName);
2238
2239                        try {
2240                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2241                        } catch (PackageManagerException e) {
2242                            Slog.e(TAG, "Failed to parse original system package: "
2243                                    + e.getMessage());
2244                        }
2245                    }
2246                }
2247            }
2248            mExpectingBetter.clear();
2249
2250            // Now that we know all of the shared libraries, update all clients to have
2251            // the correct library paths.
2252            updateAllSharedLibrariesLPw();
2253
2254            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2255                // NOTE: We ignore potential failures here during a system scan (like
2256                // the rest of the commands above) because there's precious little we
2257                // can do about it. A settings error is reported, though.
2258                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2259                        false /* force dexopt */, false /* defer dexopt */);
2260            }
2261
2262            // Now that we know all the packages we are keeping,
2263            // read and update their last usage times.
2264            mPackageUsage.readLP();
2265
2266            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2267                    SystemClock.uptimeMillis());
2268            Slog.i(TAG, "Time to scan packages: "
2269                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2270                    + " seconds");
2271
2272            // If the platform SDK has changed since the last time we booted,
2273            // we need to re-grant app permission to catch any new ones that
2274            // appear.  This is really a hack, and means that apps can in some
2275            // cases get permissions that the user didn't initially explicitly
2276            // allow...  it would be nice to have some better way to handle
2277            // this situation.
2278            int updateFlags = UPDATE_PERMISSIONS_ALL;
2279            if (ver.sdkVersion != mSdkVersion) {
2280                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2281                        + mSdkVersion + "; regranting permissions for internal storage");
2282                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2283            }
2284            updatePermissionsLPw(null, null, updateFlags);
2285            ver.sdkVersion = mSdkVersion;
2286
2287            // If this is the first boot or an update from pre-M, and it is a normal
2288            // boot, then we need to initialize the default preferred apps across
2289            // all defined users.
2290            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2291                for (UserInfo user : sUserManager.getUsers(true)) {
2292                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2293                    applyFactoryDefaultBrowserLPw(user.id);
2294                    primeDomainVerificationsLPw(user.id);
2295                }
2296            }
2297
2298            // If this is first boot after an OTA, and a normal boot, then
2299            // we need to clear code cache directories.
2300            if (mIsUpgrade && !onlyCore) {
2301                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2302                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2303                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2304                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2305                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2306                    }
2307                }
2308                ver.fingerprint = Build.FINGERPRINT;
2309            }
2310
2311            checkDefaultBrowser();
2312
2313            // clear only after permissions and other defaults have been updated
2314            mExistingSystemPackages.clear();
2315            mPromoteSystemApps = false;
2316
2317            // All the changes are done during package scanning.
2318            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2319
2320            // can downgrade to reader
2321            mSettings.writeLPr();
2322
2323            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2324                    SystemClock.uptimeMillis());
2325
2326            mRequiredVerifierPackage = getRequiredVerifierLPr();
2327            mRequiredInstallerPackage = getRequiredInstallerLPr();
2328
2329            mInstallerService = new PackageInstallerService(context, this);
2330
2331            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2332            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2333                    mIntentFilterVerifierComponent);
2334
2335        } // synchronized (mPackages)
2336        } // synchronized (mInstallLock)
2337
2338        // Now after opening every single application zip, make sure they
2339        // are all flushed.  Not really needed, but keeps things nice and
2340        // tidy.
2341        Runtime.getRuntime().gc();
2342
2343        // Expose private service for system components to use.
2344        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2345    }
2346
2347    @Override
2348    public boolean isFirstBoot() {
2349        return !mRestoredSettings;
2350    }
2351
2352    @Override
2353    public boolean isOnlyCoreApps() {
2354        return mOnlyCore;
2355    }
2356
2357    @Override
2358    public boolean isUpgrade() {
2359        return mIsUpgrade;
2360    }
2361
2362    private String getRequiredVerifierLPr() {
2363        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2364        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2365                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2366
2367        String requiredVerifier = null;
2368
2369        final int N = receivers.size();
2370        for (int i = 0; i < N; i++) {
2371            final ResolveInfo info = receivers.get(i);
2372
2373            if (info.activityInfo == null) {
2374                continue;
2375            }
2376
2377            final String packageName = info.activityInfo.packageName;
2378
2379            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2380                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2381                continue;
2382            }
2383
2384            if (requiredVerifier != null) {
2385                throw new RuntimeException("There can be only one required verifier");
2386            }
2387
2388            requiredVerifier = packageName;
2389        }
2390
2391        return requiredVerifier;
2392    }
2393
2394    private String getRequiredInstallerLPr() {
2395        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2396        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2397        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2398
2399        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2400                PACKAGE_MIME_TYPE, 0, 0);
2401
2402        String requiredInstaller = null;
2403
2404        final int N = installers.size();
2405        for (int i = 0; i < N; i++) {
2406            final ResolveInfo info = installers.get(i);
2407            final String packageName = info.activityInfo.packageName;
2408
2409            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2410                continue;
2411            }
2412
2413            if (requiredInstaller != null) {
2414                throw new RuntimeException("There must be one required installer");
2415            }
2416
2417            requiredInstaller = packageName;
2418        }
2419
2420        if (requiredInstaller == null) {
2421            throw new RuntimeException("There must be one required installer");
2422        }
2423
2424        return requiredInstaller;
2425    }
2426
2427    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2428        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2429        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2430                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2431
2432        ComponentName verifierComponentName = null;
2433
2434        int priority = -1000;
2435        final int N = receivers.size();
2436        for (int i = 0; i < N; i++) {
2437            final ResolveInfo info = receivers.get(i);
2438
2439            if (info.activityInfo == null) {
2440                continue;
2441            }
2442
2443            final String packageName = info.activityInfo.packageName;
2444
2445            final PackageSetting ps = mSettings.mPackages.get(packageName);
2446            if (ps == null) {
2447                continue;
2448            }
2449
2450            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2451                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2452                continue;
2453            }
2454
2455            // Select the IntentFilterVerifier with the highest priority
2456            if (priority < info.priority) {
2457                priority = info.priority;
2458                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2459                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2460                        + verifierComponentName + " with priority: " + info.priority);
2461            }
2462        }
2463
2464        return verifierComponentName;
2465    }
2466
2467    private void primeDomainVerificationsLPw(int userId) {
2468        if (DEBUG_DOMAIN_VERIFICATION) {
2469            Slog.d(TAG, "Priming domain verifications in user " + userId);
2470        }
2471
2472        SystemConfig systemConfig = SystemConfig.getInstance();
2473        ArraySet<String> packages = systemConfig.getLinkedApps();
2474        ArraySet<String> domains = new ArraySet<String>();
2475
2476        for (String packageName : packages) {
2477            PackageParser.Package pkg = mPackages.get(packageName);
2478            if (pkg != null) {
2479                if (!pkg.isSystemApp()) {
2480                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2481                    continue;
2482                }
2483
2484                domains.clear();
2485                for (PackageParser.Activity a : pkg.activities) {
2486                    for (ActivityIntentInfo filter : a.intents) {
2487                        if (hasValidDomains(filter)) {
2488                            domains.addAll(filter.getHostsList());
2489                        }
2490                    }
2491                }
2492
2493                if (domains.size() > 0) {
2494                    if (DEBUG_DOMAIN_VERIFICATION) {
2495                        Slog.v(TAG, "      + " + packageName);
2496                    }
2497                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2498                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2499                    // and then 'always' in the per-user state actually used for intent resolution.
2500                    final IntentFilterVerificationInfo ivi;
2501                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2502                            new ArrayList<String>(domains));
2503                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2504                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2505                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2506                } else {
2507                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2508                            + "' does not handle web links");
2509                }
2510            } else {
2511                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2512            }
2513        }
2514
2515        scheduleWritePackageRestrictionsLocked(userId);
2516        scheduleWriteSettingsLocked();
2517    }
2518
2519    private void applyFactoryDefaultBrowserLPw(int userId) {
2520        // The default browser app's package name is stored in a string resource,
2521        // with a product-specific overlay used for vendor customization.
2522        String browserPkg = mContext.getResources().getString(
2523                com.android.internal.R.string.default_browser);
2524        if (!TextUtils.isEmpty(browserPkg)) {
2525            // non-empty string => required to be a known package
2526            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2527            if (ps == null) {
2528                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2529                browserPkg = null;
2530            } else {
2531                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2532            }
2533        }
2534
2535        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2536        // default.  If there's more than one, just leave everything alone.
2537        if (browserPkg == null) {
2538            calculateDefaultBrowserLPw(userId);
2539        }
2540    }
2541
2542    private void calculateDefaultBrowserLPw(int userId) {
2543        List<String> allBrowsers = resolveAllBrowserApps(userId);
2544        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2545        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2546    }
2547
2548    private List<String> resolveAllBrowserApps(int userId) {
2549        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2550        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2551                PackageManager.MATCH_ALL, userId);
2552
2553        final int count = list.size();
2554        List<String> result = new ArrayList<String>(count);
2555        for (int i=0; i<count; i++) {
2556            ResolveInfo info = list.get(i);
2557            if (info.activityInfo == null
2558                    || !info.handleAllWebDataURI
2559                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2560                    || result.contains(info.activityInfo.packageName)) {
2561                continue;
2562            }
2563            result.add(info.activityInfo.packageName);
2564        }
2565
2566        return result;
2567    }
2568
2569    private boolean packageIsBrowser(String packageName, int userId) {
2570        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2571                PackageManager.MATCH_ALL, userId);
2572        final int N = list.size();
2573        for (int i = 0; i < N; i++) {
2574            ResolveInfo info = list.get(i);
2575            if (packageName.equals(info.activityInfo.packageName)) {
2576                return true;
2577            }
2578        }
2579        return false;
2580    }
2581
2582    private void checkDefaultBrowser() {
2583        final int myUserId = UserHandle.myUserId();
2584        final String packageName = getDefaultBrowserPackageName(myUserId);
2585        if (packageName != null) {
2586            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2587            if (info == null) {
2588                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2589                synchronized (mPackages) {
2590                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2591                }
2592            }
2593        }
2594    }
2595
2596    @Override
2597    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2598            throws RemoteException {
2599        try {
2600            return super.onTransact(code, data, reply, flags);
2601        } catch (RuntimeException e) {
2602            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2603                Slog.wtf(TAG, "Package Manager Crash", e);
2604            }
2605            throw e;
2606        }
2607    }
2608
2609    void cleanupInstallFailedPackage(PackageSetting ps) {
2610        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2611
2612        removeDataDirsLI(ps.volumeUuid, ps.name);
2613        if (ps.codePath != null) {
2614            if (ps.codePath.isDirectory()) {
2615                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2616            } else {
2617                ps.codePath.delete();
2618            }
2619        }
2620        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2621            if (ps.resourcePath.isDirectory()) {
2622                FileUtils.deleteContents(ps.resourcePath);
2623            }
2624            ps.resourcePath.delete();
2625        }
2626        mSettings.removePackageLPw(ps.name);
2627    }
2628
2629    static int[] appendInts(int[] cur, int[] add) {
2630        if (add == null) return cur;
2631        if (cur == null) return add;
2632        final int N = add.length;
2633        for (int i=0; i<N; i++) {
2634            cur = appendInt(cur, add[i]);
2635        }
2636        return cur;
2637    }
2638
2639    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2640        if (!sUserManager.exists(userId)) return null;
2641        final PackageSetting ps = (PackageSetting) p.mExtras;
2642        if (ps == null) {
2643            return null;
2644        }
2645
2646        final PermissionsState permissionsState = ps.getPermissionsState();
2647
2648        final int[] gids = permissionsState.computeGids(userId);
2649        final Set<String> permissions = permissionsState.getPermissions(userId);
2650        final PackageUserState state = ps.readUserState(userId);
2651
2652        return PackageParser.generatePackageInfo(p, gids, flags,
2653                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2654    }
2655
2656    @Override
2657    public boolean isPackageFrozen(String packageName) {
2658        synchronized (mPackages) {
2659            final PackageSetting ps = mSettings.mPackages.get(packageName);
2660            if (ps != null) {
2661                return ps.frozen;
2662            }
2663        }
2664        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2665        return true;
2666    }
2667
2668    @Override
2669    public boolean isPackageAvailable(String packageName, int userId) {
2670        if (!sUserManager.exists(userId)) return false;
2671        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2672        synchronized (mPackages) {
2673            PackageParser.Package p = mPackages.get(packageName);
2674            if (p != null) {
2675                final PackageSetting ps = (PackageSetting) p.mExtras;
2676                if (ps != null) {
2677                    final PackageUserState state = ps.readUserState(userId);
2678                    if (state != null) {
2679                        return PackageParser.isAvailable(state);
2680                    }
2681                }
2682            }
2683        }
2684        return false;
2685    }
2686
2687    @Override
2688    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2689        if (!sUserManager.exists(userId)) return null;
2690        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2691        // reader
2692        synchronized (mPackages) {
2693            PackageParser.Package p = mPackages.get(packageName);
2694            if (DEBUG_PACKAGE_INFO)
2695                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2696            if (p != null) {
2697                return generatePackageInfo(p, flags, userId);
2698            }
2699            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2700                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2701            }
2702        }
2703        return null;
2704    }
2705
2706    @Override
2707    public String[] currentToCanonicalPackageNames(String[] names) {
2708        String[] out = new String[names.length];
2709        // reader
2710        synchronized (mPackages) {
2711            for (int i=names.length-1; i>=0; i--) {
2712                PackageSetting ps = mSettings.mPackages.get(names[i]);
2713                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2714            }
2715        }
2716        return out;
2717    }
2718
2719    @Override
2720    public String[] canonicalToCurrentPackageNames(String[] names) {
2721        String[] out = new String[names.length];
2722        // reader
2723        synchronized (mPackages) {
2724            for (int i=names.length-1; i>=0; i--) {
2725                String cur = mSettings.mRenamedPackages.get(names[i]);
2726                out[i] = cur != null ? cur : names[i];
2727            }
2728        }
2729        return out;
2730    }
2731
2732    @Override
2733    public int getPackageUid(String packageName, int userId) {
2734        if (!sUserManager.exists(userId)) return -1;
2735        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2736
2737        // reader
2738        synchronized (mPackages) {
2739            PackageParser.Package p = mPackages.get(packageName);
2740            if(p != null) {
2741                return UserHandle.getUid(userId, p.applicationInfo.uid);
2742            }
2743            PackageSetting ps = mSettings.mPackages.get(packageName);
2744            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2745                return -1;
2746            }
2747            p = ps.pkg;
2748            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2749        }
2750    }
2751
2752    @Override
2753    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2754        if (!sUserManager.exists(userId)) {
2755            return null;
2756        }
2757
2758        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2759                "getPackageGids");
2760
2761        // reader
2762        synchronized (mPackages) {
2763            PackageParser.Package p = mPackages.get(packageName);
2764            if (DEBUG_PACKAGE_INFO) {
2765                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2766            }
2767            if (p != null) {
2768                PackageSetting ps = (PackageSetting) p.mExtras;
2769                return ps.getPermissionsState().computeGids(userId);
2770            }
2771        }
2772
2773        return null;
2774    }
2775
2776    static PermissionInfo generatePermissionInfo(
2777            BasePermission bp, int flags) {
2778        if (bp.perm != null) {
2779            return PackageParser.generatePermissionInfo(bp.perm, flags);
2780        }
2781        PermissionInfo pi = new PermissionInfo();
2782        pi.name = bp.name;
2783        pi.packageName = bp.sourcePackage;
2784        pi.nonLocalizedLabel = bp.name;
2785        pi.protectionLevel = bp.protectionLevel;
2786        return pi;
2787    }
2788
2789    @Override
2790    public PermissionInfo getPermissionInfo(String name, int flags) {
2791        // reader
2792        synchronized (mPackages) {
2793            final BasePermission p = mSettings.mPermissions.get(name);
2794            if (p != null) {
2795                return generatePermissionInfo(p, flags);
2796            }
2797            return null;
2798        }
2799    }
2800
2801    @Override
2802    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2803        // reader
2804        synchronized (mPackages) {
2805            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2806            for (BasePermission p : mSettings.mPermissions.values()) {
2807                if (group == null) {
2808                    if (p.perm == null || p.perm.info.group == null) {
2809                        out.add(generatePermissionInfo(p, flags));
2810                    }
2811                } else {
2812                    if (p.perm != null && group.equals(p.perm.info.group)) {
2813                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2814                    }
2815                }
2816            }
2817
2818            if (out.size() > 0) {
2819                return out;
2820            }
2821            return mPermissionGroups.containsKey(group) ? out : null;
2822        }
2823    }
2824
2825    @Override
2826    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2827        // reader
2828        synchronized (mPackages) {
2829            return PackageParser.generatePermissionGroupInfo(
2830                    mPermissionGroups.get(name), flags);
2831        }
2832    }
2833
2834    @Override
2835    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2836        // reader
2837        synchronized (mPackages) {
2838            final int N = mPermissionGroups.size();
2839            ArrayList<PermissionGroupInfo> out
2840                    = new ArrayList<PermissionGroupInfo>(N);
2841            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2842                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2843            }
2844            return out;
2845        }
2846    }
2847
2848    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2849            int userId) {
2850        if (!sUserManager.exists(userId)) return null;
2851        PackageSetting ps = mSettings.mPackages.get(packageName);
2852        if (ps != null) {
2853            if (ps.pkg == null) {
2854                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2855                        flags, userId);
2856                if (pInfo != null) {
2857                    return pInfo.applicationInfo;
2858                }
2859                return null;
2860            }
2861            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2862                    ps.readUserState(userId), userId);
2863        }
2864        return null;
2865    }
2866
2867    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2868            int userId) {
2869        if (!sUserManager.exists(userId)) return null;
2870        PackageSetting ps = mSettings.mPackages.get(packageName);
2871        if (ps != null) {
2872            PackageParser.Package pkg = ps.pkg;
2873            if (pkg == null) {
2874                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2875                    return null;
2876                }
2877                // Only data remains, so we aren't worried about code paths
2878                pkg = new PackageParser.Package(packageName);
2879                pkg.applicationInfo.packageName = packageName;
2880                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2881                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2882                pkg.applicationInfo.dataDir = Environment
2883                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2884                        .getAbsolutePath();
2885                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2886                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2887            }
2888            return generatePackageInfo(pkg, flags, userId);
2889        }
2890        return null;
2891    }
2892
2893    @Override
2894    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2895        if (!sUserManager.exists(userId)) return null;
2896        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2897        // writer
2898        synchronized (mPackages) {
2899            PackageParser.Package p = mPackages.get(packageName);
2900            if (DEBUG_PACKAGE_INFO) Log.v(
2901                    TAG, "getApplicationInfo " + packageName
2902                    + ": " + p);
2903            if (p != null) {
2904                PackageSetting ps = mSettings.mPackages.get(packageName);
2905                if (ps == null) return null;
2906                // Note: isEnabledLP() does not apply here - always return info
2907                return PackageParser.generateApplicationInfo(
2908                        p, flags, ps.readUserState(userId), userId);
2909            }
2910            if ("android".equals(packageName)||"system".equals(packageName)) {
2911                return mAndroidApplication;
2912            }
2913            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2914                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2915            }
2916        }
2917        return null;
2918    }
2919
2920    @Override
2921    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2922            final IPackageDataObserver observer) {
2923        mContext.enforceCallingOrSelfPermission(
2924                android.Manifest.permission.CLEAR_APP_CACHE, null);
2925        // Queue up an async operation since clearing cache may take a little while.
2926        mHandler.post(new Runnable() {
2927            public void run() {
2928                mHandler.removeCallbacks(this);
2929                int retCode = -1;
2930                synchronized (mInstallLock) {
2931                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2932                    if (retCode < 0) {
2933                        Slog.w(TAG, "Couldn't clear application caches");
2934                    }
2935                }
2936                if (observer != null) {
2937                    try {
2938                        observer.onRemoveCompleted(null, (retCode >= 0));
2939                    } catch (RemoteException e) {
2940                        Slog.w(TAG, "RemoveException when invoking call back");
2941                    }
2942                }
2943            }
2944        });
2945    }
2946
2947    @Override
2948    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2949            final IntentSender pi) {
2950        mContext.enforceCallingOrSelfPermission(
2951                android.Manifest.permission.CLEAR_APP_CACHE, null);
2952        // Queue up an async operation since clearing cache may take a little while.
2953        mHandler.post(new Runnable() {
2954            public void run() {
2955                mHandler.removeCallbacks(this);
2956                int retCode = -1;
2957                synchronized (mInstallLock) {
2958                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2959                    if (retCode < 0) {
2960                        Slog.w(TAG, "Couldn't clear application caches");
2961                    }
2962                }
2963                if(pi != null) {
2964                    try {
2965                        // Callback via pending intent
2966                        int code = (retCode >= 0) ? 1 : 0;
2967                        pi.sendIntent(null, code, null,
2968                                null, null);
2969                    } catch (SendIntentException e1) {
2970                        Slog.i(TAG, "Failed to send pending intent");
2971                    }
2972                }
2973            }
2974        });
2975    }
2976
2977    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2978        synchronized (mInstallLock) {
2979            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2980                throw new IOException("Failed to free enough space");
2981            }
2982        }
2983    }
2984
2985    @Override
2986    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2987        if (!sUserManager.exists(userId)) return null;
2988        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2989        synchronized (mPackages) {
2990            PackageParser.Activity a = mActivities.mActivities.get(component);
2991
2992            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2993            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2994                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2995                if (ps == null) return null;
2996                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2997                        userId);
2998            }
2999            if (mResolveComponentName.equals(component)) {
3000                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3001                        new PackageUserState(), userId);
3002            }
3003        }
3004        return null;
3005    }
3006
3007    @Override
3008    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3009            String resolvedType) {
3010        synchronized (mPackages) {
3011            if (component.equals(mResolveComponentName)) {
3012                // The resolver supports EVERYTHING!
3013                return true;
3014            }
3015            PackageParser.Activity a = mActivities.mActivities.get(component);
3016            if (a == null) {
3017                return false;
3018            }
3019            for (int i=0; i<a.intents.size(); i++) {
3020                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3021                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3022                    return true;
3023                }
3024            }
3025            return false;
3026        }
3027    }
3028
3029    @Override
3030    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3031        if (!sUserManager.exists(userId)) return null;
3032        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3033        synchronized (mPackages) {
3034            PackageParser.Activity a = mReceivers.mActivities.get(component);
3035            if (DEBUG_PACKAGE_INFO) Log.v(
3036                TAG, "getReceiverInfo " + component + ": " + a);
3037            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3038                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3039                if (ps == null) return null;
3040                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3041                        userId);
3042            }
3043        }
3044        return null;
3045    }
3046
3047    @Override
3048    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3049        if (!sUserManager.exists(userId)) return null;
3050        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3051        synchronized (mPackages) {
3052            PackageParser.Service s = mServices.mServices.get(component);
3053            if (DEBUG_PACKAGE_INFO) Log.v(
3054                TAG, "getServiceInfo " + component + ": " + s);
3055            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3056                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3057                if (ps == null) return null;
3058                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3059                        userId);
3060            }
3061        }
3062        return null;
3063    }
3064
3065    @Override
3066    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3067        if (!sUserManager.exists(userId)) return null;
3068        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3069        synchronized (mPackages) {
3070            PackageParser.Provider p = mProviders.mProviders.get(component);
3071            if (DEBUG_PACKAGE_INFO) Log.v(
3072                TAG, "getProviderInfo " + component + ": " + p);
3073            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3074                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3075                if (ps == null) return null;
3076                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3077                        userId);
3078            }
3079        }
3080        return null;
3081    }
3082
3083    @Override
3084    public String[] getSystemSharedLibraryNames() {
3085        Set<String> libSet;
3086        synchronized (mPackages) {
3087            libSet = mSharedLibraries.keySet();
3088            int size = libSet.size();
3089            if (size > 0) {
3090                String[] libs = new String[size];
3091                libSet.toArray(libs);
3092                return libs;
3093            }
3094        }
3095        return null;
3096    }
3097
3098    /**
3099     * @hide
3100     */
3101    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3102        synchronized (mPackages) {
3103            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3104            if (lib != null && lib.apk != null) {
3105                return mPackages.get(lib.apk);
3106            }
3107        }
3108        return null;
3109    }
3110
3111    @Override
3112    public FeatureInfo[] getSystemAvailableFeatures() {
3113        Collection<FeatureInfo> featSet;
3114        synchronized (mPackages) {
3115            featSet = mAvailableFeatures.values();
3116            int size = featSet.size();
3117            if (size > 0) {
3118                FeatureInfo[] features = new FeatureInfo[size+1];
3119                featSet.toArray(features);
3120                FeatureInfo fi = new FeatureInfo();
3121                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3122                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3123                features[size] = fi;
3124                return features;
3125            }
3126        }
3127        return null;
3128    }
3129
3130    @Override
3131    public boolean hasSystemFeature(String name) {
3132        synchronized (mPackages) {
3133            return mAvailableFeatures.containsKey(name);
3134        }
3135    }
3136
3137    private void checkValidCaller(int uid, int userId) {
3138        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3139            return;
3140
3141        throw new SecurityException("Caller uid=" + uid
3142                + " is not privileged to communicate with user=" + userId);
3143    }
3144
3145    @Override
3146    public int checkPermission(String permName, String pkgName, int userId) {
3147        if (!sUserManager.exists(userId)) {
3148            return PackageManager.PERMISSION_DENIED;
3149        }
3150
3151        synchronized (mPackages) {
3152            final PackageParser.Package p = mPackages.get(pkgName);
3153            if (p != null && p.mExtras != null) {
3154                final PackageSetting ps = (PackageSetting) p.mExtras;
3155                final PermissionsState permissionsState = ps.getPermissionsState();
3156                if (permissionsState.hasPermission(permName, userId)) {
3157                    return PackageManager.PERMISSION_GRANTED;
3158                }
3159                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3160                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3161                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3162                    return PackageManager.PERMISSION_GRANTED;
3163                }
3164            }
3165        }
3166
3167        return PackageManager.PERMISSION_DENIED;
3168    }
3169
3170    @Override
3171    public int checkUidPermission(String permName, int uid) {
3172        final int userId = UserHandle.getUserId(uid);
3173
3174        if (!sUserManager.exists(userId)) {
3175            return PackageManager.PERMISSION_DENIED;
3176        }
3177
3178        synchronized (mPackages) {
3179            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3180            if (obj != null) {
3181                final SettingBase ps = (SettingBase) obj;
3182                final PermissionsState permissionsState = ps.getPermissionsState();
3183                if (permissionsState.hasPermission(permName, userId)) {
3184                    return PackageManager.PERMISSION_GRANTED;
3185                }
3186                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3187                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3188                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3189                    return PackageManager.PERMISSION_GRANTED;
3190                }
3191            } else {
3192                ArraySet<String> perms = mSystemPermissions.get(uid);
3193                if (perms != null) {
3194                    if (perms.contains(permName)) {
3195                        return PackageManager.PERMISSION_GRANTED;
3196                    }
3197                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3198                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3199                        return PackageManager.PERMISSION_GRANTED;
3200                    }
3201                }
3202            }
3203        }
3204
3205        return PackageManager.PERMISSION_DENIED;
3206    }
3207
3208    @Override
3209    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3210        if (UserHandle.getCallingUserId() != userId) {
3211            mContext.enforceCallingPermission(
3212                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3213                    "isPermissionRevokedByPolicy for user " + userId);
3214        }
3215
3216        if (checkPermission(permission, packageName, userId)
3217                == PackageManager.PERMISSION_GRANTED) {
3218            return false;
3219        }
3220
3221        final long identity = Binder.clearCallingIdentity();
3222        try {
3223            final int flags = getPermissionFlags(permission, packageName, userId);
3224            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3225        } finally {
3226            Binder.restoreCallingIdentity(identity);
3227        }
3228    }
3229
3230    @Override
3231    public String getPermissionControllerPackageName() {
3232        synchronized (mPackages) {
3233            return mRequiredInstallerPackage;
3234        }
3235    }
3236
3237    /**
3238     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3239     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3240     * @param checkShell TODO(yamasani):
3241     * @param message the message to log on security exception
3242     */
3243    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3244            boolean checkShell, String message) {
3245        if (userId < 0) {
3246            throw new IllegalArgumentException("Invalid userId " + userId);
3247        }
3248        if (checkShell) {
3249            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3250        }
3251        if (userId == UserHandle.getUserId(callingUid)) return;
3252        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3253            if (requireFullPermission) {
3254                mContext.enforceCallingOrSelfPermission(
3255                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3256            } else {
3257                try {
3258                    mContext.enforceCallingOrSelfPermission(
3259                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3260                } catch (SecurityException se) {
3261                    mContext.enforceCallingOrSelfPermission(
3262                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3263                }
3264            }
3265        }
3266    }
3267
3268    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3269        if (callingUid == Process.SHELL_UID) {
3270            if (userHandle >= 0
3271                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3272                throw new SecurityException("Shell does not have permission to access user "
3273                        + userHandle);
3274            } else if (userHandle < 0) {
3275                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3276                        + Debug.getCallers(3));
3277            }
3278        }
3279    }
3280
3281    private BasePermission findPermissionTreeLP(String permName) {
3282        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3283            if (permName.startsWith(bp.name) &&
3284                    permName.length() > bp.name.length() &&
3285                    permName.charAt(bp.name.length()) == '.') {
3286                return bp;
3287            }
3288        }
3289        return null;
3290    }
3291
3292    private BasePermission checkPermissionTreeLP(String permName) {
3293        if (permName != null) {
3294            BasePermission bp = findPermissionTreeLP(permName);
3295            if (bp != null) {
3296                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3297                    return bp;
3298                }
3299                throw new SecurityException("Calling uid "
3300                        + Binder.getCallingUid()
3301                        + " is not allowed to add to permission tree "
3302                        + bp.name + " owned by uid " + bp.uid);
3303            }
3304        }
3305        throw new SecurityException("No permission tree found for " + permName);
3306    }
3307
3308    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3309        if (s1 == null) {
3310            return s2 == null;
3311        }
3312        if (s2 == null) {
3313            return false;
3314        }
3315        if (s1.getClass() != s2.getClass()) {
3316            return false;
3317        }
3318        return s1.equals(s2);
3319    }
3320
3321    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3322        if (pi1.icon != pi2.icon) return false;
3323        if (pi1.logo != pi2.logo) return false;
3324        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3325        if (!compareStrings(pi1.name, pi2.name)) return false;
3326        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3327        // We'll take care of setting this one.
3328        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3329        // These are not currently stored in settings.
3330        //if (!compareStrings(pi1.group, pi2.group)) return false;
3331        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3332        //if (pi1.labelRes != pi2.labelRes) return false;
3333        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3334        return true;
3335    }
3336
3337    int permissionInfoFootprint(PermissionInfo info) {
3338        int size = info.name.length();
3339        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3340        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3341        return size;
3342    }
3343
3344    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3345        int size = 0;
3346        for (BasePermission perm : mSettings.mPermissions.values()) {
3347            if (perm.uid == tree.uid) {
3348                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3349            }
3350        }
3351        return size;
3352    }
3353
3354    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3355        // We calculate the max size of permissions defined by this uid and throw
3356        // if that plus the size of 'info' would exceed our stated maximum.
3357        if (tree.uid != Process.SYSTEM_UID) {
3358            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3359            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3360                throw new SecurityException("Permission tree size cap exceeded");
3361            }
3362        }
3363    }
3364
3365    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3366        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3367            throw new SecurityException("Label must be specified in permission");
3368        }
3369        BasePermission tree = checkPermissionTreeLP(info.name);
3370        BasePermission bp = mSettings.mPermissions.get(info.name);
3371        boolean added = bp == null;
3372        boolean changed = true;
3373        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3374        if (added) {
3375            enforcePermissionCapLocked(info, tree);
3376            bp = new BasePermission(info.name, tree.sourcePackage,
3377                    BasePermission.TYPE_DYNAMIC);
3378        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3379            throw new SecurityException(
3380                    "Not allowed to modify non-dynamic permission "
3381                    + info.name);
3382        } else {
3383            if (bp.protectionLevel == fixedLevel
3384                    && bp.perm.owner.equals(tree.perm.owner)
3385                    && bp.uid == tree.uid
3386                    && comparePermissionInfos(bp.perm.info, info)) {
3387                changed = false;
3388            }
3389        }
3390        bp.protectionLevel = fixedLevel;
3391        info = new PermissionInfo(info);
3392        info.protectionLevel = fixedLevel;
3393        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3394        bp.perm.info.packageName = tree.perm.info.packageName;
3395        bp.uid = tree.uid;
3396        if (added) {
3397            mSettings.mPermissions.put(info.name, bp);
3398        }
3399        if (changed) {
3400            if (!async) {
3401                mSettings.writeLPr();
3402            } else {
3403                scheduleWriteSettingsLocked();
3404            }
3405        }
3406        return added;
3407    }
3408
3409    @Override
3410    public boolean addPermission(PermissionInfo info) {
3411        synchronized (mPackages) {
3412            return addPermissionLocked(info, false);
3413        }
3414    }
3415
3416    @Override
3417    public boolean addPermissionAsync(PermissionInfo info) {
3418        synchronized (mPackages) {
3419            return addPermissionLocked(info, true);
3420        }
3421    }
3422
3423    @Override
3424    public void removePermission(String name) {
3425        synchronized (mPackages) {
3426            checkPermissionTreeLP(name);
3427            BasePermission bp = mSettings.mPermissions.get(name);
3428            if (bp != null) {
3429                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3430                    throw new SecurityException(
3431                            "Not allowed to modify non-dynamic permission "
3432                            + name);
3433                }
3434                mSettings.mPermissions.remove(name);
3435                mSettings.writeLPr();
3436            }
3437        }
3438    }
3439
3440    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3441            BasePermission bp) {
3442        int index = pkg.requestedPermissions.indexOf(bp.name);
3443        if (index == -1) {
3444            throw new SecurityException("Package " + pkg.packageName
3445                    + " has not requested permission " + bp.name);
3446        }
3447        if (!bp.isRuntime() && !bp.isDevelopment()) {
3448            throw new SecurityException("Permission " + bp.name
3449                    + " is not a changeable permission type");
3450        }
3451    }
3452
3453    @Override
3454    public void grantRuntimePermission(String packageName, String name, final int userId) {
3455        if (!sUserManager.exists(userId)) {
3456            Log.e(TAG, "No such user:" + userId);
3457            return;
3458        }
3459
3460        mContext.enforceCallingOrSelfPermission(
3461                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3462                "grantRuntimePermission");
3463
3464        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3465                "grantRuntimePermission");
3466
3467        final int uid;
3468        final SettingBase sb;
3469
3470        synchronized (mPackages) {
3471            final PackageParser.Package pkg = mPackages.get(packageName);
3472            if (pkg == null) {
3473                throw new IllegalArgumentException("Unknown package: " + packageName);
3474            }
3475
3476            final BasePermission bp = mSettings.mPermissions.get(name);
3477            if (bp == null) {
3478                throw new IllegalArgumentException("Unknown permission: " + name);
3479            }
3480
3481            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3482
3483            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3484            sb = (SettingBase) pkg.mExtras;
3485            if (sb == null) {
3486                throw new IllegalArgumentException("Unknown package: " + packageName);
3487            }
3488
3489            final PermissionsState permissionsState = sb.getPermissionsState();
3490
3491            final int flags = permissionsState.getPermissionFlags(name, userId);
3492            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3493                throw new SecurityException("Cannot grant system fixed permission: "
3494                        + name + " for package: " + packageName);
3495            }
3496
3497            if (bp.isDevelopment()) {
3498                // Development permissions must be handled specially, since they are not
3499                // normal runtime permissions.  For now they apply to all users.
3500                if (permissionsState.grantInstallPermission(bp) !=
3501                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3502                    scheduleWriteSettingsLocked();
3503                }
3504                return;
3505            }
3506
3507            final int result = permissionsState.grantRuntimePermission(bp, userId);
3508            switch (result) {
3509                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3510                    return;
3511                }
3512
3513                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3514                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3515                    mHandler.post(new Runnable() {
3516                        @Override
3517                        public void run() {
3518                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3519                        }
3520                    });
3521                } break;
3522            }
3523
3524            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3525
3526            // Not critical if that is lost - app has to request again.
3527            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3528        }
3529
3530        // Only need to do this if user is initialized. Otherwise it's a new user
3531        // and there are no processes running as the user yet and there's no need
3532        // to make an expensive call to remount processes for the changed permissions.
3533        if (READ_EXTERNAL_STORAGE.equals(name)
3534                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3535            final long token = Binder.clearCallingIdentity();
3536            try {
3537                if (sUserManager.isInitialized(userId)) {
3538                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3539                            MountServiceInternal.class);
3540                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3541                }
3542            } finally {
3543                Binder.restoreCallingIdentity(token);
3544            }
3545        }
3546    }
3547
3548    @Override
3549    public void revokeRuntimePermission(String packageName, String name, int userId) {
3550        if (!sUserManager.exists(userId)) {
3551            Log.e(TAG, "No such user:" + userId);
3552            return;
3553        }
3554
3555        mContext.enforceCallingOrSelfPermission(
3556                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3557                "revokeRuntimePermission");
3558
3559        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3560                "revokeRuntimePermission");
3561
3562        final int appId;
3563
3564        synchronized (mPackages) {
3565            final PackageParser.Package pkg = mPackages.get(packageName);
3566            if (pkg == null) {
3567                throw new IllegalArgumentException("Unknown package: " + packageName);
3568            }
3569
3570            final BasePermission bp = mSettings.mPermissions.get(name);
3571            if (bp == null) {
3572                throw new IllegalArgumentException("Unknown permission: " + name);
3573            }
3574
3575            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3576
3577            SettingBase sb = (SettingBase) pkg.mExtras;
3578            if (sb == null) {
3579                throw new IllegalArgumentException("Unknown package: " + packageName);
3580            }
3581
3582            final PermissionsState permissionsState = sb.getPermissionsState();
3583
3584            final int flags = permissionsState.getPermissionFlags(name, userId);
3585            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3586                throw new SecurityException("Cannot revoke system fixed permission: "
3587                        + name + " for package: " + packageName);
3588            }
3589
3590            if (bp.isDevelopment()) {
3591                // Development permissions must be handled specially, since they are not
3592                // normal runtime permissions.  For now they apply to all users.
3593                if (permissionsState.revokeInstallPermission(bp) !=
3594                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3595                    scheduleWriteSettingsLocked();
3596                }
3597                return;
3598            }
3599
3600            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3601                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3602                return;
3603            }
3604
3605            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3606
3607            // Critical, after this call app should never have the permission.
3608            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3609
3610            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3611        }
3612
3613        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3614    }
3615
3616    @Override
3617    public void resetRuntimePermissions() {
3618        mContext.enforceCallingOrSelfPermission(
3619                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3620                "revokeRuntimePermission");
3621
3622        int callingUid = Binder.getCallingUid();
3623        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3624            mContext.enforceCallingOrSelfPermission(
3625                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3626                    "resetRuntimePermissions");
3627        }
3628
3629        synchronized (mPackages) {
3630            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3631            for (int userId : UserManagerService.getInstance().getUserIds()) {
3632                final int packageCount = mPackages.size();
3633                for (int i = 0; i < packageCount; i++) {
3634                    PackageParser.Package pkg = mPackages.valueAt(i);
3635                    if (!(pkg.mExtras instanceof PackageSetting)) {
3636                        continue;
3637                    }
3638                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3639                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3640                }
3641            }
3642        }
3643    }
3644
3645    @Override
3646    public int getPermissionFlags(String name, String packageName, int userId) {
3647        if (!sUserManager.exists(userId)) {
3648            return 0;
3649        }
3650
3651        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3652
3653        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3654                "getPermissionFlags");
3655
3656        synchronized (mPackages) {
3657            final PackageParser.Package pkg = mPackages.get(packageName);
3658            if (pkg == null) {
3659                throw new IllegalArgumentException("Unknown package: " + packageName);
3660            }
3661
3662            final BasePermission bp = mSettings.mPermissions.get(name);
3663            if (bp == null) {
3664                throw new IllegalArgumentException("Unknown permission: " + name);
3665            }
3666
3667            SettingBase sb = (SettingBase) pkg.mExtras;
3668            if (sb == null) {
3669                throw new IllegalArgumentException("Unknown package: " + packageName);
3670            }
3671
3672            PermissionsState permissionsState = sb.getPermissionsState();
3673            return permissionsState.getPermissionFlags(name, userId);
3674        }
3675    }
3676
3677    @Override
3678    public void updatePermissionFlags(String name, String packageName, int flagMask,
3679            int flagValues, int userId) {
3680        if (!sUserManager.exists(userId)) {
3681            return;
3682        }
3683
3684        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3685
3686        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3687                "updatePermissionFlags");
3688
3689        // Only the system can change these flags and nothing else.
3690        if (getCallingUid() != Process.SYSTEM_UID) {
3691            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3692            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3693            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3694            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3695        }
3696
3697        synchronized (mPackages) {
3698            final PackageParser.Package pkg = mPackages.get(packageName);
3699            if (pkg == null) {
3700                throw new IllegalArgumentException("Unknown package: " + packageName);
3701            }
3702
3703            final BasePermission bp = mSettings.mPermissions.get(name);
3704            if (bp == null) {
3705                throw new IllegalArgumentException("Unknown permission: " + name);
3706            }
3707
3708            SettingBase sb = (SettingBase) pkg.mExtras;
3709            if (sb == null) {
3710                throw new IllegalArgumentException("Unknown package: " + packageName);
3711            }
3712
3713            PermissionsState permissionsState = sb.getPermissionsState();
3714
3715            // Only the package manager can change flags for system component permissions.
3716            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3717            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3718                return;
3719            }
3720
3721            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3722
3723            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3724                // Install and runtime permissions are stored in different places,
3725                // so figure out what permission changed and persist the change.
3726                if (permissionsState.getInstallPermissionState(name) != null) {
3727                    scheduleWriteSettingsLocked();
3728                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3729                        || hadState) {
3730                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3731                }
3732            }
3733        }
3734    }
3735
3736    /**
3737     * Update the permission flags for all packages and runtime permissions of a user in order
3738     * to allow device or profile owner to remove POLICY_FIXED.
3739     */
3740    @Override
3741    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3742        if (!sUserManager.exists(userId)) {
3743            return;
3744        }
3745
3746        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3747
3748        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3749                "updatePermissionFlagsForAllApps");
3750
3751        // Only the system can change system fixed flags.
3752        if (getCallingUid() != Process.SYSTEM_UID) {
3753            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3754            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3755        }
3756
3757        synchronized (mPackages) {
3758            boolean changed = false;
3759            final int packageCount = mPackages.size();
3760            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3761                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3762                SettingBase sb = (SettingBase) pkg.mExtras;
3763                if (sb == null) {
3764                    continue;
3765                }
3766                PermissionsState permissionsState = sb.getPermissionsState();
3767                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3768                        userId, flagMask, flagValues);
3769            }
3770            if (changed) {
3771                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3772            }
3773        }
3774    }
3775
3776    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3777        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3778                != PackageManager.PERMISSION_GRANTED
3779            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3780                != PackageManager.PERMISSION_GRANTED) {
3781            throw new SecurityException(message + " requires "
3782                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3783                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3784        }
3785    }
3786
3787    @Override
3788    public boolean shouldShowRequestPermissionRationale(String permissionName,
3789            String packageName, int userId) {
3790        if (UserHandle.getCallingUserId() != userId) {
3791            mContext.enforceCallingPermission(
3792                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3793                    "canShowRequestPermissionRationale for user " + userId);
3794        }
3795
3796        final int uid = getPackageUid(packageName, userId);
3797        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3798            return false;
3799        }
3800
3801        if (checkPermission(permissionName, packageName, userId)
3802                == PackageManager.PERMISSION_GRANTED) {
3803            return false;
3804        }
3805
3806        final int flags;
3807
3808        final long identity = Binder.clearCallingIdentity();
3809        try {
3810            flags = getPermissionFlags(permissionName,
3811                    packageName, userId);
3812        } finally {
3813            Binder.restoreCallingIdentity(identity);
3814        }
3815
3816        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3817                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3818                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3819
3820        if ((flags & fixedFlags) != 0) {
3821            return false;
3822        }
3823
3824        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3825    }
3826
3827    @Override
3828    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3829        mContext.enforceCallingOrSelfPermission(
3830                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3831                "addOnPermissionsChangeListener");
3832
3833        synchronized (mPackages) {
3834            mOnPermissionChangeListeners.addListenerLocked(listener);
3835        }
3836    }
3837
3838    @Override
3839    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3840        synchronized (mPackages) {
3841            mOnPermissionChangeListeners.removeListenerLocked(listener);
3842        }
3843    }
3844
3845    @Override
3846    public boolean isProtectedBroadcast(String actionName) {
3847        synchronized (mPackages) {
3848            return mProtectedBroadcasts.contains(actionName);
3849        }
3850    }
3851
3852    @Override
3853    public int checkSignatures(String pkg1, String pkg2) {
3854        synchronized (mPackages) {
3855            final PackageParser.Package p1 = mPackages.get(pkg1);
3856            final PackageParser.Package p2 = mPackages.get(pkg2);
3857            if (p1 == null || p1.mExtras == null
3858                    || p2 == null || p2.mExtras == null) {
3859                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3860            }
3861            return compareSignatures(p1.mSignatures, p2.mSignatures);
3862        }
3863    }
3864
3865    @Override
3866    public int checkUidSignatures(int uid1, int uid2) {
3867        // Map to base uids.
3868        uid1 = UserHandle.getAppId(uid1);
3869        uid2 = UserHandle.getAppId(uid2);
3870        // reader
3871        synchronized (mPackages) {
3872            Signature[] s1;
3873            Signature[] s2;
3874            Object obj = mSettings.getUserIdLPr(uid1);
3875            if (obj != null) {
3876                if (obj instanceof SharedUserSetting) {
3877                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3878                } else if (obj instanceof PackageSetting) {
3879                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3880                } else {
3881                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3882                }
3883            } else {
3884                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3885            }
3886            obj = mSettings.getUserIdLPr(uid2);
3887            if (obj != null) {
3888                if (obj instanceof SharedUserSetting) {
3889                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3890                } else if (obj instanceof PackageSetting) {
3891                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3892                } else {
3893                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3894                }
3895            } else {
3896                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3897            }
3898            return compareSignatures(s1, s2);
3899        }
3900    }
3901
3902    private void killUid(int appId, int userId, String reason) {
3903        final long identity = Binder.clearCallingIdentity();
3904        try {
3905            IActivityManager am = ActivityManagerNative.getDefault();
3906            if (am != null) {
3907                try {
3908                    am.killUid(appId, userId, reason);
3909                } catch (RemoteException e) {
3910                    /* ignore - same process */
3911                }
3912            }
3913        } finally {
3914            Binder.restoreCallingIdentity(identity);
3915        }
3916    }
3917
3918    /**
3919     * Compares two sets of signatures. Returns:
3920     * <br />
3921     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3922     * <br />
3923     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3924     * <br />
3925     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3926     * <br />
3927     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3928     * <br />
3929     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3930     */
3931    static int compareSignatures(Signature[] s1, Signature[] s2) {
3932        if (s1 == null) {
3933            return s2 == null
3934                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3935                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3936        }
3937
3938        if (s2 == null) {
3939            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3940        }
3941
3942        if (s1.length != s2.length) {
3943            return PackageManager.SIGNATURE_NO_MATCH;
3944        }
3945
3946        // Since both signature sets are of size 1, we can compare without HashSets.
3947        if (s1.length == 1) {
3948            return s1[0].equals(s2[0]) ?
3949                    PackageManager.SIGNATURE_MATCH :
3950                    PackageManager.SIGNATURE_NO_MATCH;
3951        }
3952
3953        ArraySet<Signature> set1 = new ArraySet<Signature>();
3954        for (Signature sig : s1) {
3955            set1.add(sig);
3956        }
3957        ArraySet<Signature> set2 = new ArraySet<Signature>();
3958        for (Signature sig : s2) {
3959            set2.add(sig);
3960        }
3961        // Make sure s2 contains all signatures in s1.
3962        if (set1.equals(set2)) {
3963            return PackageManager.SIGNATURE_MATCH;
3964        }
3965        return PackageManager.SIGNATURE_NO_MATCH;
3966    }
3967
3968    /**
3969     * If the database version for this type of package (internal storage or
3970     * external storage) is less than the version where package signatures
3971     * were updated, return true.
3972     */
3973    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3974        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3975        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3976    }
3977
3978    /**
3979     * Used for backward compatibility to make sure any packages with
3980     * certificate chains get upgraded to the new style. {@code existingSigs}
3981     * will be in the old format (since they were stored on disk from before the
3982     * system upgrade) and {@code scannedSigs} will be in the newer format.
3983     */
3984    private int compareSignaturesCompat(PackageSignatures existingSigs,
3985            PackageParser.Package scannedPkg) {
3986        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3987            return PackageManager.SIGNATURE_NO_MATCH;
3988        }
3989
3990        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3991        for (Signature sig : existingSigs.mSignatures) {
3992            existingSet.add(sig);
3993        }
3994        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3995        for (Signature sig : scannedPkg.mSignatures) {
3996            try {
3997                Signature[] chainSignatures = sig.getChainSignatures();
3998                for (Signature chainSig : chainSignatures) {
3999                    scannedCompatSet.add(chainSig);
4000                }
4001            } catch (CertificateEncodingException e) {
4002                scannedCompatSet.add(sig);
4003            }
4004        }
4005        /*
4006         * Make sure the expanded scanned set contains all signatures in the
4007         * existing one.
4008         */
4009        if (scannedCompatSet.equals(existingSet)) {
4010            // Migrate the old signatures to the new scheme.
4011            existingSigs.assignSignatures(scannedPkg.mSignatures);
4012            // The new KeySets will be re-added later in the scanning process.
4013            synchronized (mPackages) {
4014                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4015            }
4016            return PackageManager.SIGNATURE_MATCH;
4017        }
4018        return PackageManager.SIGNATURE_NO_MATCH;
4019    }
4020
4021    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4022        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4023        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4024    }
4025
4026    private int compareSignaturesRecover(PackageSignatures existingSigs,
4027            PackageParser.Package scannedPkg) {
4028        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4029            return PackageManager.SIGNATURE_NO_MATCH;
4030        }
4031
4032        String msg = null;
4033        try {
4034            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4035                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4036                        + scannedPkg.packageName);
4037                return PackageManager.SIGNATURE_MATCH;
4038            }
4039        } catch (CertificateException e) {
4040            msg = e.getMessage();
4041        }
4042
4043        logCriticalInfo(Log.INFO,
4044                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4045        return PackageManager.SIGNATURE_NO_MATCH;
4046    }
4047
4048    @Override
4049    public String[] getPackagesForUid(int uid) {
4050        uid = UserHandle.getAppId(uid);
4051        // reader
4052        synchronized (mPackages) {
4053            Object obj = mSettings.getUserIdLPr(uid);
4054            if (obj instanceof SharedUserSetting) {
4055                final SharedUserSetting sus = (SharedUserSetting) obj;
4056                final int N = sus.packages.size();
4057                final String[] res = new String[N];
4058                final Iterator<PackageSetting> it = sus.packages.iterator();
4059                int i = 0;
4060                while (it.hasNext()) {
4061                    res[i++] = it.next().name;
4062                }
4063                return res;
4064            } else if (obj instanceof PackageSetting) {
4065                final PackageSetting ps = (PackageSetting) obj;
4066                return new String[] { ps.name };
4067            }
4068        }
4069        return null;
4070    }
4071
4072    @Override
4073    public String getNameForUid(int uid) {
4074        // reader
4075        synchronized (mPackages) {
4076            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4077            if (obj instanceof SharedUserSetting) {
4078                final SharedUserSetting sus = (SharedUserSetting) obj;
4079                return sus.name + ":" + sus.userId;
4080            } else if (obj instanceof PackageSetting) {
4081                final PackageSetting ps = (PackageSetting) obj;
4082                return ps.name;
4083            }
4084        }
4085        return null;
4086    }
4087
4088    @Override
4089    public int getUidForSharedUser(String sharedUserName) {
4090        if(sharedUserName == null) {
4091            return -1;
4092        }
4093        // reader
4094        synchronized (mPackages) {
4095            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4096            if (suid == null) {
4097                return -1;
4098            }
4099            return suid.userId;
4100        }
4101    }
4102
4103    @Override
4104    public int getFlagsForUid(int uid) {
4105        synchronized (mPackages) {
4106            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4107            if (obj instanceof SharedUserSetting) {
4108                final SharedUserSetting sus = (SharedUserSetting) obj;
4109                return sus.pkgFlags;
4110            } else if (obj instanceof PackageSetting) {
4111                final PackageSetting ps = (PackageSetting) obj;
4112                return ps.pkgFlags;
4113            }
4114        }
4115        return 0;
4116    }
4117
4118    @Override
4119    public int getPrivateFlagsForUid(int uid) {
4120        synchronized (mPackages) {
4121            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4122            if (obj instanceof SharedUserSetting) {
4123                final SharedUserSetting sus = (SharedUserSetting) obj;
4124                return sus.pkgPrivateFlags;
4125            } else if (obj instanceof PackageSetting) {
4126                final PackageSetting ps = (PackageSetting) obj;
4127                return ps.pkgPrivateFlags;
4128            }
4129        }
4130        return 0;
4131    }
4132
4133    @Override
4134    public boolean isUidPrivileged(int uid) {
4135        uid = UserHandle.getAppId(uid);
4136        // reader
4137        synchronized (mPackages) {
4138            Object obj = mSettings.getUserIdLPr(uid);
4139            if (obj instanceof SharedUserSetting) {
4140                final SharedUserSetting sus = (SharedUserSetting) obj;
4141                final Iterator<PackageSetting> it = sus.packages.iterator();
4142                while (it.hasNext()) {
4143                    if (it.next().isPrivileged()) {
4144                        return true;
4145                    }
4146                }
4147            } else if (obj instanceof PackageSetting) {
4148                final PackageSetting ps = (PackageSetting) obj;
4149                return ps.isPrivileged();
4150            }
4151        }
4152        return false;
4153    }
4154
4155    @Override
4156    public String[] getAppOpPermissionPackages(String permissionName) {
4157        synchronized (mPackages) {
4158            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4159            if (pkgs == null) {
4160                return null;
4161            }
4162            return pkgs.toArray(new String[pkgs.size()]);
4163        }
4164    }
4165
4166    @Override
4167    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4168            int flags, int userId) {
4169        if (!sUserManager.exists(userId)) return null;
4170        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4171        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4172        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4173    }
4174
4175    @Override
4176    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4177            IntentFilter filter, int match, ComponentName activity) {
4178        final int userId = UserHandle.getCallingUserId();
4179        if (DEBUG_PREFERRED) {
4180            Log.v(TAG, "setLastChosenActivity intent=" + intent
4181                + " resolvedType=" + resolvedType
4182                + " flags=" + flags
4183                + " filter=" + filter
4184                + " match=" + match
4185                + " activity=" + activity);
4186            filter.dump(new PrintStreamPrinter(System.out), "    ");
4187        }
4188        intent.setComponent(null);
4189        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4190        // Find any earlier preferred or last chosen entries and nuke them
4191        findPreferredActivity(intent, resolvedType,
4192                flags, query, 0, false, true, false, userId);
4193        // Add the new activity as the last chosen for this filter
4194        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4195                "Setting last chosen");
4196    }
4197
4198    @Override
4199    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4200        final int userId = UserHandle.getCallingUserId();
4201        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4202        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4203        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4204                false, false, false, userId);
4205    }
4206
4207    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4208            int flags, List<ResolveInfo> query, int userId) {
4209        if (query != null) {
4210            final int N = query.size();
4211            if (N == 1) {
4212                return query.get(0);
4213            } else if (N > 1) {
4214                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4215                // If there is more than one activity with the same priority,
4216                // then let the user decide between them.
4217                ResolveInfo r0 = query.get(0);
4218                ResolveInfo r1 = query.get(1);
4219                if (DEBUG_INTENT_MATCHING || debug) {
4220                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4221                            + r1.activityInfo.name + "=" + r1.priority);
4222                }
4223                // If the first activity has a higher priority, or a different
4224                // default, then it is always desireable to pick it.
4225                if (r0.priority != r1.priority
4226                        || r0.preferredOrder != r1.preferredOrder
4227                        || r0.isDefault != r1.isDefault) {
4228                    return query.get(0);
4229                }
4230                // If we have saved a preference for a preferred activity for
4231                // this Intent, use that.
4232                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4233                        flags, query, r0.priority, true, false, debug, userId);
4234                if (ri != null) {
4235                    return ri;
4236                }
4237                ri = new ResolveInfo(mResolveInfo);
4238                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4239                ri.activityInfo.applicationInfo = new ApplicationInfo(
4240                        ri.activityInfo.applicationInfo);
4241                if (userId != 0) {
4242                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4243                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4244                }
4245                // Make sure that the resolver is displayable in car mode
4246                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4247                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4248                return ri;
4249            }
4250        }
4251        return null;
4252    }
4253
4254    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4255            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4256        final int N = query.size();
4257        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4258                .get(userId);
4259        // Get the list of persistent preferred activities that handle the intent
4260        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4261        List<PersistentPreferredActivity> pprefs = ppir != null
4262                ? ppir.queryIntent(intent, resolvedType,
4263                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4264                : null;
4265        if (pprefs != null && pprefs.size() > 0) {
4266            final int M = pprefs.size();
4267            for (int i=0; i<M; i++) {
4268                final PersistentPreferredActivity ppa = pprefs.get(i);
4269                if (DEBUG_PREFERRED || debug) {
4270                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4271                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4272                            + "\n  component=" + ppa.mComponent);
4273                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4274                }
4275                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4276                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4277                if (DEBUG_PREFERRED || debug) {
4278                    Slog.v(TAG, "Found persistent preferred activity:");
4279                    if (ai != null) {
4280                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4281                    } else {
4282                        Slog.v(TAG, "  null");
4283                    }
4284                }
4285                if (ai == null) {
4286                    // This previously registered persistent preferred activity
4287                    // component is no longer known. Ignore it and do NOT remove it.
4288                    continue;
4289                }
4290                for (int j=0; j<N; j++) {
4291                    final ResolveInfo ri = query.get(j);
4292                    if (!ri.activityInfo.applicationInfo.packageName
4293                            .equals(ai.applicationInfo.packageName)) {
4294                        continue;
4295                    }
4296                    if (!ri.activityInfo.name.equals(ai.name)) {
4297                        continue;
4298                    }
4299                    //  Found a persistent preference that can handle the intent.
4300                    if (DEBUG_PREFERRED || debug) {
4301                        Slog.v(TAG, "Returning persistent preferred activity: " +
4302                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4303                    }
4304                    return ri;
4305                }
4306            }
4307        }
4308        return null;
4309    }
4310
4311    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4312            List<ResolveInfo> query, int priority, boolean always,
4313            boolean removeMatches, boolean debug, int userId) {
4314        if (!sUserManager.exists(userId)) return null;
4315        // writer
4316        synchronized (mPackages) {
4317            if (intent.getSelector() != null) {
4318                intent = intent.getSelector();
4319            }
4320            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4321
4322            // Try to find a matching persistent preferred activity.
4323            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4324                    debug, userId);
4325
4326            // If a persistent preferred activity matched, use it.
4327            if (pri != null) {
4328                return pri;
4329            }
4330
4331            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4332            // Get the list of preferred activities that handle the intent
4333            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4334            List<PreferredActivity> prefs = pir != null
4335                    ? pir.queryIntent(intent, resolvedType,
4336                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4337                    : null;
4338            if (prefs != null && prefs.size() > 0) {
4339                boolean changed = false;
4340                try {
4341                    // First figure out how good the original match set is.
4342                    // We will only allow preferred activities that came
4343                    // from the same match quality.
4344                    int match = 0;
4345
4346                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4347
4348                    final int N = query.size();
4349                    for (int j=0; j<N; j++) {
4350                        final ResolveInfo ri = query.get(j);
4351                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4352                                + ": 0x" + Integer.toHexString(match));
4353                        if (ri.match > match) {
4354                            match = ri.match;
4355                        }
4356                    }
4357
4358                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4359                            + Integer.toHexString(match));
4360
4361                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4362                    final int M = prefs.size();
4363                    for (int i=0; i<M; i++) {
4364                        final PreferredActivity pa = prefs.get(i);
4365                        if (DEBUG_PREFERRED || debug) {
4366                            Slog.v(TAG, "Checking PreferredActivity ds="
4367                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4368                                    + "\n  component=" + pa.mPref.mComponent);
4369                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4370                        }
4371                        if (pa.mPref.mMatch != match) {
4372                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4373                                    + Integer.toHexString(pa.mPref.mMatch));
4374                            continue;
4375                        }
4376                        // If it's not an "always" type preferred activity and that's what we're
4377                        // looking for, skip it.
4378                        if (always && !pa.mPref.mAlways) {
4379                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4380                            continue;
4381                        }
4382                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4383                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4384                        if (DEBUG_PREFERRED || debug) {
4385                            Slog.v(TAG, "Found preferred activity:");
4386                            if (ai != null) {
4387                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4388                            } else {
4389                                Slog.v(TAG, "  null");
4390                            }
4391                        }
4392                        if (ai == null) {
4393                            // This previously registered preferred activity
4394                            // component is no longer known.  Most likely an update
4395                            // to the app was installed and in the new version this
4396                            // component no longer exists.  Clean it up by removing
4397                            // it from the preferred activities list, and skip it.
4398                            Slog.w(TAG, "Removing dangling preferred activity: "
4399                                    + pa.mPref.mComponent);
4400                            pir.removeFilter(pa);
4401                            changed = true;
4402                            continue;
4403                        }
4404                        for (int j=0; j<N; j++) {
4405                            final ResolveInfo ri = query.get(j);
4406                            if (!ri.activityInfo.applicationInfo.packageName
4407                                    .equals(ai.applicationInfo.packageName)) {
4408                                continue;
4409                            }
4410                            if (!ri.activityInfo.name.equals(ai.name)) {
4411                                continue;
4412                            }
4413
4414                            if (removeMatches) {
4415                                pir.removeFilter(pa);
4416                                changed = true;
4417                                if (DEBUG_PREFERRED) {
4418                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4419                                }
4420                                break;
4421                            }
4422
4423                            // Okay we found a previously set preferred or last chosen app.
4424                            // If the result set is different from when this
4425                            // was created, we need to clear it and re-ask the
4426                            // user their preference, if we're looking for an "always" type entry.
4427                            if (always && !pa.mPref.sameSet(query)) {
4428                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4429                                        + intent + " type " + resolvedType);
4430                                if (DEBUG_PREFERRED) {
4431                                    Slog.v(TAG, "Removing preferred activity since set changed "
4432                                            + pa.mPref.mComponent);
4433                                }
4434                                pir.removeFilter(pa);
4435                                // Re-add the filter as a "last chosen" entry (!always)
4436                                PreferredActivity lastChosen = new PreferredActivity(
4437                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4438                                pir.addFilter(lastChosen);
4439                                changed = true;
4440                                return null;
4441                            }
4442
4443                            // Yay! Either the set matched or we're looking for the last chosen
4444                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4445                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4446                            return ri;
4447                        }
4448                    }
4449                } finally {
4450                    if (changed) {
4451                        if (DEBUG_PREFERRED) {
4452                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4453                        }
4454                        scheduleWritePackageRestrictionsLocked(userId);
4455                    }
4456                }
4457            }
4458        }
4459        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4460        return null;
4461    }
4462
4463    /*
4464     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4465     */
4466    @Override
4467    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4468            int targetUserId) {
4469        mContext.enforceCallingOrSelfPermission(
4470                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4471        List<CrossProfileIntentFilter> matches =
4472                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4473        if (matches != null) {
4474            int size = matches.size();
4475            for (int i = 0; i < size; i++) {
4476                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4477            }
4478        }
4479        if (hasWebURI(intent)) {
4480            // cross-profile app linking works only towards the parent.
4481            final UserInfo parent = getProfileParent(sourceUserId);
4482            synchronized(mPackages) {
4483                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4484                        intent, resolvedType, 0, sourceUserId, parent.id);
4485                return xpDomainInfo != null;
4486            }
4487        }
4488        return false;
4489    }
4490
4491    private UserInfo getProfileParent(int userId) {
4492        final long identity = Binder.clearCallingIdentity();
4493        try {
4494            return sUserManager.getProfileParent(userId);
4495        } finally {
4496            Binder.restoreCallingIdentity(identity);
4497        }
4498    }
4499
4500    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4501            String resolvedType, int userId) {
4502        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4503        if (resolver != null) {
4504            return resolver.queryIntent(intent, resolvedType, false, userId);
4505        }
4506        return null;
4507    }
4508
4509    @Override
4510    public List<ResolveInfo> queryIntentActivities(Intent intent,
4511            String resolvedType, int flags, int userId) {
4512        if (!sUserManager.exists(userId)) return Collections.emptyList();
4513        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4514        ComponentName comp = intent.getComponent();
4515        if (comp == null) {
4516            if (intent.getSelector() != null) {
4517                intent = intent.getSelector();
4518                comp = intent.getComponent();
4519            }
4520        }
4521
4522        if (comp != null) {
4523            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4524            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4525            if (ai != null) {
4526                final ResolveInfo ri = new ResolveInfo();
4527                ri.activityInfo = ai;
4528                list.add(ri);
4529            }
4530            return list;
4531        }
4532
4533        // reader
4534        synchronized (mPackages) {
4535            final String pkgName = intent.getPackage();
4536            if (pkgName == null) {
4537                List<CrossProfileIntentFilter> matchingFilters =
4538                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4539                // Check for results that need to skip the current profile.
4540                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4541                        resolvedType, flags, userId);
4542                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4543                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4544                    result.add(xpResolveInfo);
4545                    return filterIfNotPrimaryUser(result, userId);
4546                }
4547
4548                // Check for results in the current profile.
4549                List<ResolveInfo> result = mActivities.queryIntent(
4550                        intent, resolvedType, flags, userId);
4551
4552                // Check for cross profile results.
4553                xpResolveInfo = queryCrossProfileIntents(
4554                        matchingFilters, intent, resolvedType, flags, userId);
4555                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4556                    result.add(xpResolveInfo);
4557                    Collections.sort(result, mResolvePrioritySorter);
4558                }
4559                result = filterIfNotPrimaryUser(result, userId);
4560                if (hasWebURI(intent)) {
4561                    CrossProfileDomainInfo xpDomainInfo = null;
4562                    final UserInfo parent = getProfileParent(userId);
4563                    if (parent != null) {
4564                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4565                                flags, userId, parent.id);
4566                    }
4567                    if (xpDomainInfo != null) {
4568                        if (xpResolveInfo != null) {
4569                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4570                            // in the result.
4571                            result.remove(xpResolveInfo);
4572                        }
4573                        if (result.size() == 0) {
4574                            result.add(xpDomainInfo.resolveInfo);
4575                            return result;
4576                        }
4577                    } else if (result.size() <= 1) {
4578                        return result;
4579                    }
4580                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4581                            xpDomainInfo, userId);
4582                    Collections.sort(result, mResolvePrioritySorter);
4583                }
4584                return result;
4585            }
4586            final PackageParser.Package pkg = mPackages.get(pkgName);
4587            if (pkg != null) {
4588                return filterIfNotPrimaryUser(
4589                        mActivities.queryIntentForPackage(
4590                                intent, resolvedType, flags, pkg.activities, userId),
4591                        userId);
4592            }
4593            return new ArrayList<ResolveInfo>();
4594        }
4595    }
4596
4597    private static class CrossProfileDomainInfo {
4598        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4599        ResolveInfo resolveInfo;
4600        /* Best domain verification status of the activities found in the other profile */
4601        int bestDomainVerificationStatus;
4602    }
4603
4604    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4605            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4606        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4607                sourceUserId)) {
4608            return null;
4609        }
4610        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4611                resolvedType, flags, parentUserId);
4612
4613        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4614            return null;
4615        }
4616        CrossProfileDomainInfo result = null;
4617        int size = resultTargetUser.size();
4618        for (int i = 0; i < size; i++) {
4619            ResolveInfo riTargetUser = resultTargetUser.get(i);
4620            // Intent filter verification is only for filters that specify a host. So don't return
4621            // those that handle all web uris.
4622            if (riTargetUser.handleAllWebDataURI) {
4623                continue;
4624            }
4625            String packageName = riTargetUser.activityInfo.packageName;
4626            PackageSetting ps = mSettings.mPackages.get(packageName);
4627            if (ps == null) {
4628                continue;
4629            }
4630            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4631            int status = (int)(verificationState >> 32);
4632            if (result == null) {
4633                result = new CrossProfileDomainInfo();
4634                result.resolveInfo =
4635                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4636                result.bestDomainVerificationStatus = status;
4637            } else {
4638                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4639                        result.bestDomainVerificationStatus);
4640            }
4641        }
4642        // Don't consider matches with status NEVER across profiles.
4643        if (result != null && result.bestDomainVerificationStatus
4644                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4645            return null;
4646        }
4647        return result;
4648    }
4649
4650    /**
4651     * Verification statuses are ordered from the worse to the best, except for
4652     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4653     */
4654    private int bestDomainVerificationStatus(int status1, int status2) {
4655        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4656            return status2;
4657        }
4658        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4659            return status1;
4660        }
4661        return (int) MathUtils.max(status1, status2);
4662    }
4663
4664    private boolean isUserEnabled(int userId) {
4665        long callingId = Binder.clearCallingIdentity();
4666        try {
4667            UserInfo userInfo = sUserManager.getUserInfo(userId);
4668            return userInfo != null && userInfo.isEnabled();
4669        } finally {
4670            Binder.restoreCallingIdentity(callingId);
4671        }
4672    }
4673
4674    /**
4675     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4676     *
4677     * @return filtered list
4678     */
4679    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4680        if (userId == UserHandle.USER_OWNER) {
4681            return resolveInfos;
4682        }
4683        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4684            ResolveInfo info = resolveInfos.get(i);
4685            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4686                resolveInfos.remove(i);
4687            }
4688        }
4689        return resolveInfos;
4690    }
4691
4692    private static boolean hasWebURI(Intent intent) {
4693        if (intent.getData() == null) {
4694            return false;
4695        }
4696        final String scheme = intent.getScheme();
4697        if (TextUtils.isEmpty(scheme)) {
4698            return false;
4699        }
4700        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4701    }
4702
4703    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4704            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4705            int userId) {
4706        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4707
4708        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4709            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4710                    candidates.size());
4711        }
4712
4713        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4714        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4715        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4716        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4717        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4718        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4719
4720        synchronized (mPackages) {
4721            final int count = candidates.size();
4722            // First, try to use linked apps. Partition the candidates into four lists:
4723            // one for the final results, one for the "do not use ever", one for "undefined status"
4724            // and finally one for "browser app type".
4725            for (int n=0; n<count; n++) {
4726                ResolveInfo info = candidates.get(n);
4727                String packageName = info.activityInfo.packageName;
4728                PackageSetting ps = mSettings.mPackages.get(packageName);
4729                if (ps != null) {
4730                    // Add to the special match all list (Browser use case)
4731                    if (info.handleAllWebDataURI) {
4732                        matchAllList.add(info);
4733                        continue;
4734                    }
4735                    // Try to get the status from User settings first
4736                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4737                    int status = (int)(packedStatus >> 32);
4738                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4739                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4740                        if (DEBUG_DOMAIN_VERIFICATION) {
4741                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4742                                    + " : linkgen=" + linkGeneration);
4743                        }
4744                        // Use link-enabled generation as preferredOrder, i.e.
4745                        // prefer newly-enabled over earlier-enabled.
4746                        info.preferredOrder = linkGeneration;
4747                        alwaysList.add(info);
4748                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4749                        if (DEBUG_DOMAIN_VERIFICATION) {
4750                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4751                        }
4752                        neverList.add(info);
4753                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4754                        if (DEBUG_DOMAIN_VERIFICATION) {
4755                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4756                        }
4757                        alwaysAskList.add(info);
4758                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4759                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4760                        if (DEBUG_DOMAIN_VERIFICATION) {
4761                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4762                        }
4763                        undefinedList.add(info);
4764                    }
4765                }
4766            }
4767
4768            // We'll want to include browser possibilities in a few cases
4769            boolean includeBrowser = false;
4770
4771            // First try to add the "always" resolution(s) for the current user, if any
4772            if (alwaysList.size() > 0) {
4773                result.addAll(alwaysList);
4774            // if there is an "always" for the parent user, add it.
4775            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4776                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4777                result.add(xpDomainInfo.resolveInfo);
4778            } else {
4779                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4780                result.addAll(undefinedList);
4781                if (xpDomainInfo != null && (
4782                        xpDomainInfo.bestDomainVerificationStatus
4783                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4784                        || xpDomainInfo.bestDomainVerificationStatus
4785                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4786                    result.add(xpDomainInfo.resolveInfo);
4787                }
4788                includeBrowser = true;
4789            }
4790
4791            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4792            // If there were 'always' entries their preferred order has been set, so we also
4793            // back that off to make the alternatives equivalent
4794            if (alwaysAskList.size() > 0) {
4795                for (ResolveInfo i : result) {
4796                    i.preferredOrder = 0;
4797                }
4798                result.addAll(alwaysAskList);
4799                includeBrowser = true;
4800            }
4801
4802            if (includeBrowser) {
4803                // Also add browsers (all of them or only the default one)
4804                if (DEBUG_DOMAIN_VERIFICATION) {
4805                    Slog.v(TAG, "   ...including browsers in candidate set");
4806                }
4807                if ((matchFlags & MATCH_ALL) != 0) {
4808                    result.addAll(matchAllList);
4809                } else {
4810                    // Browser/generic handling case.  If there's a default browser, go straight
4811                    // to that (but only if there is no other higher-priority match).
4812                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4813                    int maxMatchPrio = 0;
4814                    ResolveInfo defaultBrowserMatch = null;
4815                    final int numCandidates = matchAllList.size();
4816                    for (int n = 0; n < numCandidates; n++) {
4817                        ResolveInfo info = matchAllList.get(n);
4818                        // track the highest overall match priority...
4819                        if (info.priority > maxMatchPrio) {
4820                            maxMatchPrio = info.priority;
4821                        }
4822                        // ...and the highest-priority default browser match
4823                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4824                            if (defaultBrowserMatch == null
4825                                    || (defaultBrowserMatch.priority < info.priority)) {
4826                                if (debug) {
4827                                    Slog.v(TAG, "Considering default browser match " + info);
4828                                }
4829                                defaultBrowserMatch = info;
4830                            }
4831                        }
4832                    }
4833                    if (defaultBrowserMatch != null
4834                            && defaultBrowserMatch.priority >= maxMatchPrio
4835                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4836                    {
4837                        if (debug) {
4838                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4839                        }
4840                        result.add(defaultBrowserMatch);
4841                    } else {
4842                        result.addAll(matchAllList);
4843                    }
4844                }
4845
4846                // If there is nothing selected, add all candidates and remove the ones that the user
4847                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4848                if (result.size() == 0) {
4849                    result.addAll(candidates);
4850                    result.removeAll(neverList);
4851                }
4852            }
4853        }
4854        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4855            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4856                    result.size());
4857            for (ResolveInfo info : result) {
4858                Slog.v(TAG, "  + " + info.activityInfo);
4859            }
4860        }
4861        return result;
4862    }
4863
4864    // Returns a packed value as a long:
4865    //
4866    // high 'int'-sized word: link status: undefined/ask/never/always.
4867    // low 'int'-sized word: relative priority among 'always' results.
4868    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4869        long result = ps.getDomainVerificationStatusForUser(userId);
4870        // if none available, get the master status
4871        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4872            if (ps.getIntentFilterVerificationInfo() != null) {
4873                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4874            }
4875        }
4876        return result;
4877    }
4878
4879    private ResolveInfo querySkipCurrentProfileIntents(
4880            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4881            int flags, int sourceUserId) {
4882        if (matchingFilters != null) {
4883            int size = matchingFilters.size();
4884            for (int i = 0; i < size; i ++) {
4885                CrossProfileIntentFilter filter = matchingFilters.get(i);
4886                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4887                    // Checking if there are activities in the target user that can handle the
4888                    // intent.
4889                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4890                            flags, sourceUserId);
4891                    if (resolveInfo != null) {
4892                        return resolveInfo;
4893                    }
4894                }
4895            }
4896        }
4897        return null;
4898    }
4899
4900    // Return matching ResolveInfo if any for skip current profile intent filters.
4901    private ResolveInfo queryCrossProfileIntents(
4902            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4903            int flags, int sourceUserId) {
4904        if (matchingFilters != null) {
4905            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4906            // match the same intent. For performance reasons, it is better not to
4907            // run queryIntent twice for the same userId
4908            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4909            int size = matchingFilters.size();
4910            for (int i = 0; i < size; i++) {
4911                CrossProfileIntentFilter filter = matchingFilters.get(i);
4912                int targetUserId = filter.getTargetUserId();
4913                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4914                        && !alreadyTriedUserIds.get(targetUserId)) {
4915                    // Checking if there are activities in the target user that can handle the
4916                    // intent.
4917                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4918                            flags, sourceUserId);
4919                    if (resolveInfo != null) return resolveInfo;
4920                    alreadyTriedUserIds.put(targetUserId, true);
4921                }
4922            }
4923        }
4924        return null;
4925    }
4926
4927    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4928            String resolvedType, int flags, int sourceUserId) {
4929        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4930                resolvedType, flags, filter.getTargetUserId());
4931        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4932            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4933        }
4934        return null;
4935    }
4936
4937    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4938            int sourceUserId, int targetUserId) {
4939        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4940        String className;
4941        if (targetUserId == UserHandle.USER_OWNER) {
4942            className = FORWARD_INTENT_TO_USER_OWNER;
4943        } else {
4944            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4945        }
4946        ComponentName forwardingActivityComponentName = new ComponentName(
4947                mAndroidApplication.packageName, className);
4948        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4949                sourceUserId);
4950        if (targetUserId == UserHandle.USER_OWNER) {
4951            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4952            forwardingResolveInfo.noResourceId = true;
4953        }
4954        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4955        forwardingResolveInfo.priority = 0;
4956        forwardingResolveInfo.preferredOrder = 0;
4957        forwardingResolveInfo.match = 0;
4958        forwardingResolveInfo.isDefault = true;
4959        forwardingResolveInfo.filter = filter;
4960        forwardingResolveInfo.targetUserId = targetUserId;
4961        return forwardingResolveInfo;
4962    }
4963
4964    @Override
4965    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4966            Intent[] specifics, String[] specificTypes, Intent intent,
4967            String resolvedType, int flags, int userId) {
4968        if (!sUserManager.exists(userId)) return Collections.emptyList();
4969        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4970                false, "query intent activity options");
4971        final String resultsAction = intent.getAction();
4972
4973        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4974                | PackageManager.GET_RESOLVED_FILTER, userId);
4975
4976        if (DEBUG_INTENT_MATCHING) {
4977            Log.v(TAG, "Query " + intent + ": " + results);
4978        }
4979
4980        int specificsPos = 0;
4981        int N;
4982
4983        // todo: note that the algorithm used here is O(N^2).  This
4984        // isn't a problem in our current environment, but if we start running
4985        // into situations where we have more than 5 or 10 matches then this
4986        // should probably be changed to something smarter...
4987
4988        // First we go through and resolve each of the specific items
4989        // that were supplied, taking care of removing any corresponding
4990        // duplicate items in the generic resolve list.
4991        if (specifics != null) {
4992            for (int i=0; i<specifics.length; i++) {
4993                final Intent sintent = specifics[i];
4994                if (sintent == null) {
4995                    continue;
4996                }
4997
4998                if (DEBUG_INTENT_MATCHING) {
4999                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5000                }
5001
5002                String action = sintent.getAction();
5003                if (resultsAction != null && resultsAction.equals(action)) {
5004                    // If this action was explicitly requested, then don't
5005                    // remove things that have it.
5006                    action = null;
5007                }
5008
5009                ResolveInfo ri = null;
5010                ActivityInfo ai = null;
5011
5012                ComponentName comp = sintent.getComponent();
5013                if (comp == null) {
5014                    ri = resolveIntent(
5015                        sintent,
5016                        specificTypes != null ? specificTypes[i] : null,
5017                            flags, userId);
5018                    if (ri == null) {
5019                        continue;
5020                    }
5021                    if (ri == mResolveInfo) {
5022                        // ACK!  Must do something better with this.
5023                    }
5024                    ai = ri.activityInfo;
5025                    comp = new ComponentName(ai.applicationInfo.packageName,
5026                            ai.name);
5027                } else {
5028                    ai = getActivityInfo(comp, flags, userId);
5029                    if (ai == null) {
5030                        continue;
5031                    }
5032                }
5033
5034                // Look for any generic query activities that are duplicates
5035                // of this specific one, and remove them from the results.
5036                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5037                N = results.size();
5038                int j;
5039                for (j=specificsPos; j<N; j++) {
5040                    ResolveInfo sri = results.get(j);
5041                    if ((sri.activityInfo.name.equals(comp.getClassName())
5042                            && sri.activityInfo.applicationInfo.packageName.equals(
5043                                    comp.getPackageName()))
5044                        || (action != null && sri.filter.matchAction(action))) {
5045                        results.remove(j);
5046                        if (DEBUG_INTENT_MATCHING) Log.v(
5047                            TAG, "Removing duplicate item from " + j
5048                            + " due to specific " + specificsPos);
5049                        if (ri == null) {
5050                            ri = sri;
5051                        }
5052                        j--;
5053                        N--;
5054                    }
5055                }
5056
5057                // Add this specific item to its proper place.
5058                if (ri == null) {
5059                    ri = new ResolveInfo();
5060                    ri.activityInfo = ai;
5061                }
5062                results.add(specificsPos, ri);
5063                ri.specificIndex = i;
5064                specificsPos++;
5065            }
5066        }
5067
5068        // Now we go through the remaining generic results and remove any
5069        // duplicate actions that are found here.
5070        N = results.size();
5071        for (int i=specificsPos; i<N-1; i++) {
5072            final ResolveInfo rii = results.get(i);
5073            if (rii.filter == null) {
5074                continue;
5075            }
5076
5077            // Iterate over all of the actions of this result's intent
5078            // filter...  typically this should be just one.
5079            final Iterator<String> it = rii.filter.actionsIterator();
5080            if (it == null) {
5081                continue;
5082            }
5083            while (it.hasNext()) {
5084                final String action = it.next();
5085                if (resultsAction != null && resultsAction.equals(action)) {
5086                    // If this action was explicitly requested, then don't
5087                    // remove things that have it.
5088                    continue;
5089                }
5090                for (int j=i+1; j<N; j++) {
5091                    final ResolveInfo rij = results.get(j);
5092                    if (rij.filter != null && rij.filter.hasAction(action)) {
5093                        results.remove(j);
5094                        if (DEBUG_INTENT_MATCHING) Log.v(
5095                            TAG, "Removing duplicate item from " + j
5096                            + " due to action " + action + " at " + i);
5097                        j--;
5098                        N--;
5099                    }
5100                }
5101            }
5102
5103            // If the caller didn't request filter information, drop it now
5104            // so we don't have to marshall/unmarshall it.
5105            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5106                rii.filter = null;
5107            }
5108        }
5109
5110        // Filter out the caller activity if so requested.
5111        if (caller != null) {
5112            N = results.size();
5113            for (int i=0; i<N; i++) {
5114                ActivityInfo ainfo = results.get(i).activityInfo;
5115                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5116                        && caller.getClassName().equals(ainfo.name)) {
5117                    results.remove(i);
5118                    break;
5119                }
5120            }
5121        }
5122
5123        // If the caller didn't request filter information,
5124        // drop them now so we don't have to
5125        // marshall/unmarshall it.
5126        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5127            N = results.size();
5128            for (int i=0; i<N; i++) {
5129                results.get(i).filter = null;
5130            }
5131        }
5132
5133        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5134        return results;
5135    }
5136
5137    @Override
5138    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5139            int userId) {
5140        if (!sUserManager.exists(userId)) return Collections.emptyList();
5141        ComponentName comp = intent.getComponent();
5142        if (comp == null) {
5143            if (intent.getSelector() != null) {
5144                intent = intent.getSelector();
5145                comp = intent.getComponent();
5146            }
5147        }
5148        if (comp != null) {
5149            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5150            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5151            if (ai != null) {
5152                ResolveInfo ri = new ResolveInfo();
5153                ri.activityInfo = ai;
5154                list.add(ri);
5155            }
5156            return list;
5157        }
5158
5159        // reader
5160        synchronized (mPackages) {
5161            String pkgName = intent.getPackage();
5162            if (pkgName == null) {
5163                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5164            }
5165            final PackageParser.Package pkg = mPackages.get(pkgName);
5166            if (pkg != null) {
5167                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5168                        userId);
5169            }
5170            return null;
5171        }
5172    }
5173
5174    @Override
5175    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5176        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5177        if (!sUserManager.exists(userId)) return null;
5178        if (query != null) {
5179            if (query.size() >= 1) {
5180                // If there is more than one service with the same priority,
5181                // just arbitrarily pick the first one.
5182                return query.get(0);
5183            }
5184        }
5185        return null;
5186    }
5187
5188    @Override
5189    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5190            int userId) {
5191        if (!sUserManager.exists(userId)) return Collections.emptyList();
5192        ComponentName comp = intent.getComponent();
5193        if (comp == null) {
5194            if (intent.getSelector() != null) {
5195                intent = intent.getSelector();
5196                comp = intent.getComponent();
5197            }
5198        }
5199        if (comp != null) {
5200            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5201            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5202            if (si != null) {
5203                final ResolveInfo ri = new ResolveInfo();
5204                ri.serviceInfo = si;
5205                list.add(ri);
5206            }
5207            return list;
5208        }
5209
5210        // reader
5211        synchronized (mPackages) {
5212            String pkgName = intent.getPackage();
5213            if (pkgName == null) {
5214                return mServices.queryIntent(intent, resolvedType, flags, userId);
5215            }
5216            final PackageParser.Package pkg = mPackages.get(pkgName);
5217            if (pkg != null) {
5218                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5219                        userId);
5220            }
5221            return null;
5222        }
5223    }
5224
5225    @Override
5226    public List<ResolveInfo> queryIntentContentProviders(
5227            Intent intent, String resolvedType, int flags, int userId) {
5228        if (!sUserManager.exists(userId)) return Collections.emptyList();
5229        ComponentName comp = intent.getComponent();
5230        if (comp == null) {
5231            if (intent.getSelector() != null) {
5232                intent = intent.getSelector();
5233                comp = intent.getComponent();
5234            }
5235        }
5236        if (comp != null) {
5237            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5238            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5239            if (pi != null) {
5240                final ResolveInfo ri = new ResolveInfo();
5241                ri.providerInfo = pi;
5242                list.add(ri);
5243            }
5244            return list;
5245        }
5246
5247        // reader
5248        synchronized (mPackages) {
5249            String pkgName = intent.getPackage();
5250            if (pkgName == null) {
5251                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5252            }
5253            final PackageParser.Package pkg = mPackages.get(pkgName);
5254            if (pkg != null) {
5255                return mProviders.queryIntentForPackage(
5256                        intent, resolvedType, flags, pkg.providers, userId);
5257            }
5258            return null;
5259        }
5260    }
5261
5262    @Override
5263    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5264        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5265
5266        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5267
5268        // writer
5269        synchronized (mPackages) {
5270            ArrayList<PackageInfo> list;
5271            if (listUninstalled) {
5272                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5273                for (PackageSetting ps : mSettings.mPackages.values()) {
5274                    PackageInfo pi;
5275                    if (ps.pkg != null) {
5276                        pi = generatePackageInfo(ps.pkg, flags, userId);
5277                    } else {
5278                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5279                    }
5280                    if (pi != null) {
5281                        list.add(pi);
5282                    }
5283                }
5284            } else {
5285                list = new ArrayList<PackageInfo>(mPackages.size());
5286                for (PackageParser.Package p : mPackages.values()) {
5287                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5288                    if (pi != null) {
5289                        list.add(pi);
5290                    }
5291                }
5292            }
5293
5294            return new ParceledListSlice<PackageInfo>(list);
5295        }
5296    }
5297
5298    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5299            String[] permissions, boolean[] tmp, int flags, int userId) {
5300        int numMatch = 0;
5301        final PermissionsState permissionsState = ps.getPermissionsState();
5302        for (int i=0; i<permissions.length; i++) {
5303            final String permission = permissions[i];
5304            if (permissionsState.hasPermission(permission, userId)) {
5305                tmp[i] = true;
5306                numMatch++;
5307            } else {
5308                tmp[i] = false;
5309            }
5310        }
5311        if (numMatch == 0) {
5312            return;
5313        }
5314        PackageInfo pi;
5315        if (ps.pkg != null) {
5316            pi = generatePackageInfo(ps.pkg, flags, userId);
5317        } else {
5318            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5319        }
5320        // The above might return null in cases of uninstalled apps or install-state
5321        // skew across users/profiles.
5322        if (pi != null) {
5323            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5324                if (numMatch == permissions.length) {
5325                    pi.requestedPermissions = permissions;
5326                } else {
5327                    pi.requestedPermissions = new String[numMatch];
5328                    numMatch = 0;
5329                    for (int i=0; i<permissions.length; i++) {
5330                        if (tmp[i]) {
5331                            pi.requestedPermissions[numMatch] = permissions[i];
5332                            numMatch++;
5333                        }
5334                    }
5335                }
5336            }
5337            list.add(pi);
5338        }
5339    }
5340
5341    @Override
5342    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5343            String[] permissions, int flags, int userId) {
5344        if (!sUserManager.exists(userId)) return null;
5345        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5346
5347        // writer
5348        synchronized (mPackages) {
5349            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5350            boolean[] tmpBools = new boolean[permissions.length];
5351            if (listUninstalled) {
5352                for (PackageSetting ps : mSettings.mPackages.values()) {
5353                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5354                }
5355            } else {
5356                for (PackageParser.Package pkg : mPackages.values()) {
5357                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5358                    if (ps != null) {
5359                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5360                                userId);
5361                    }
5362                }
5363            }
5364
5365            return new ParceledListSlice<PackageInfo>(list);
5366        }
5367    }
5368
5369    @Override
5370    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5371        if (!sUserManager.exists(userId)) return null;
5372        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5373
5374        // writer
5375        synchronized (mPackages) {
5376            ArrayList<ApplicationInfo> list;
5377            if (listUninstalled) {
5378                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5379                for (PackageSetting ps : mSettings.mPackages.values()) {
5380                    ApplicationInfo ai;
5381                    if (ps.pkg != null) {
5382                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5383                                ps.readUserState(userId), userId);
5384                    } else {
5385                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5386                    }
5387                    if (ai != null) {
5388                        list.add(ai);
5389                    }
5390                }
5391            } else {
5392                list = new ArrayList<ApplicationInfo>(mPackages.size());
5393                for (PackageParser.Package p : mPackages.values()) {
5394                    if (p.mExtras != null) {
5395                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5396                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5397                        if (ai != null) {
5398                            list.add(ai);
5399                        }
5400                    }
5401                }
5402            }
5403
5404            return new ParceledListSlice<ApplicationInfo>(list);
5405        }
5406    }
5407
5408    public List<ApplicationInfo> getPersistentApplications(int flags) {
5409        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5410
5411        // reader
5412        synchronized (mPackages) {
5413            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5414            final int userId = UserHandle.getCallingUserId();
5415            while (i.hasNext()) {
5416                final PackageParser.Package p = i.next();
5417                if (p.applicationInfo != null
5418                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5419                        && (!mSafeMode || isSystemApp(p))) {
5420                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5421                    if (ps != null) {
5422                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5423                                ps.readUserState(userId), userId);
5424                        if (ai != null) {
5425                            finalList.add(ai);
5426                        }
5427                    }
5428                }
5429            }
5430        }
5431
5432        return finalList;
5433    }
5434
5435    @Override
5436    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5437        if (!sUserManager.exists(userId)) return null;
5438        // reader
5439        synchronized (mPackages) {
5440            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5441            PackageSetting ps = provider != null
5442                    ? mSettings.mPackages.get(provider.owner.packageName)
5443                    : null;
5444            return ps != null
5445                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5446                    && (!mSafeMode || (provider.info.applicationInfo.flags
5447                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5448                    ? PackageParser.generateProviderInfo(provider, flags,
5449                            ps.readUserState(userId), userId)
5450                    : null;
5451        }
5452    }
5453
5454    /**
5455     * @deprecated
5456     */
5457    @Deprecated
5458    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5459        // reader
5460        synchronized (mPackages) {
5461            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5462                    .entrySet().iterator();
5463            final int userId = UserHandle.getCallingUserId();
5464            while (i.hasNext()) {
5465                Map.Entry<String, PackageParser.Provider> entry = i.next();
5466                PackageParser.Provider p = entry.getValue();
5467                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5468
5469                if (ps != null && p.syncable
5470                        && (!mSafeMode || (p.info.applicationInfo.flags
5471                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5472                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5473                            ps.readUserState(userId), userId);
5474                    if (info != null) {
5475                        outNames.add(entry.getKey());
5476                        outInfo.add(info);
5477                    }
5478                }
5479            }
5480        }
5481    }
5482
5483    @Override
5484    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5485            int uid, int flags) {
5486        ArrayList<ProviderInfo> finalList = null;
5487        // reader
5488        synchronized (mPackages) {
5489            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5490            final int userId = processName != null ?
5491                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5492            while (i.hasNext()) {
5493                final PackageParser.Provider p = i.next();
5494                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5495                if (ps != null && p.info.authority != null
5496                        && (processName == null
5497                                || (p.info.processName.equals(processName)
5498                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5499                        && mSettings.isEnabledLPr(p.info, flags, userId)
5500                        && (!mSafeMode
5501                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5502                    if (finalList == null) {
5503                        finalList = new ArrayList<ProviderInfo>(3);
5504                    }
5505                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5506                            ps.readUserState(userId), userId);
5507                    if (info != null) {
5508                        finalList.add(info);
5509                    }
5510                }
5511            }
5512        }
5513
5514        if (finalList != null) {
5515            Collections.sort(finalList, mProviderInitOrderSorter);
5516            return new ParceledListSlice<ProviderInfo>(finalList);
5517        }
5518
5519        return null;
5520    }
5521
5522    @Override
5523    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5524            int flags) {
5525        // reader
5526        synchronized (mPackages) {
5527            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5528            return PackageParser.generateInstrumentationInfo(i, flags);
5529        }
5530    }
5531
5532    @Override
5533    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5534            int flags) {
5535        ArrayList<InstrumentationInfo> finalList =
5536            new ArrayList<InstrumentationInfo>();
5537
5538        // reader
5539        synchronized (mPackages) {
5540            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5541            while (i.hasNext()) {
5542                final PackageParser.Instrumentation p = i.next();
5543                if (targetPackage == null
5544                        || targetPackage.equals(p.info.targetPackage)) {
5545                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5546                            flags);
5547                    if (ii != null) {
5548                        finalList.add(ii);
5549                    }
5550                }
5551            }
5552        }
5553
5554        return finalList;
5555    }
5556
5557    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5558        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5559        if (overlays == null) {
5560            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5561            return;
5562        }
5563        for (PackageParser.Package opkg : overlays.values()) {
5564            // Not much to do if idmap fails: we already logged the error
5565            // and we certainly don't want to abort installation of pkg simply
5566            // because an overlay didn't fit properly. For these reasons,
5567            // ignore the return value of createIdmapForPackagePairLI.
5568            createIdmapForPackagePairLI(pkg, opkg);
5569        }
5570    }
5571
5572    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5573            PackageParser.Package opkg) {
5574        if (!opkg.mTrustedOverlay) {
5575            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5576                    opkg.baseCodePath + ": overlay not trusted");
5577            return false;
5578        }
5579        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5580        if (overlaySet == null) {
5581            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5582                    opkg.baseCodePath + " but target package has no known overlays");
5583            return false;
5584        }
5585        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5586        // TODO: generate idmap for split APKs
5587        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5588            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5589                    + opkg.baseCodePath);
5590            return false;
5591        }
5592        PackageParser.Package[] overlayArray =
5593            overlaySet.values().toArray(new PackageParser.Package[0]);
5594        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5595            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5596                return p1.mOverlayPriority - p2.mOverlayPriority;
5597            }
5598        };
5599        Arrays.sort(overlayArray, cmp);
5600
5601        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5602        int i = 0;
5603        for (PackageParser.Package p : overlayArray) {
5604            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5605        }
5606        return true;
5607    }
5608
5609    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5610        final File[] files = dir.listFiles();
5611        if (ArrayUtils.isEmpty(files)) {
5612            Log.d(TAG, "No files in app dir " + dir);
5613            return;
5614        }
5615
5616        if (DEBUG_PACKAGE_SCANNING) {
5617            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5618                    + " flags=0x" + Integer.toHexString(parseFlags));
5619        }
5620
5621        for (File file : files) {
5622            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5623                    && !PackageInstallerService.isStageName(file.getName());
5624            if (!isPackage) {
5625                // Ignore entries which are not packages
5626                continue;
5627            }
5628            try {
5629                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5630                        scanFlags, currentTime, null);
5631            } catch (PackageManagerException e) {
5632                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5633
5634                // Delete invalid userdata apps
5635                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5636                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5637                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5638                    if (file.isDirectory()) {
5639                        mInstaller.rmPackageDir(file.getAbsolutePath());
5640                    } else {
5641                        file.delete();
5642                    }
5643                }
5644            }
5645        }
5646    }
5647
5648    private static File getSettingsProblemFile() {
5649        File dataDir = Environment.getDataDirectory();
5650        File systemDir = new File(dataDir, "system");
5651        File fname = new File(systemDir, "uiderrors.txt");
5652        return fname;
5653    }
5654
5655    static void reportSettingsProblem(int priority, String msg) {
5656        logCriticalInfo(priority, msg);
5657    }
5658
5659    static void logCriticalInfo(int priority, String msg) {
5660        Slog.println(priority, TAG, msg);
5661        EventLogTags.writePmCriticalInfo(msg);
5662        try {
5663            File fname = getSettingsProblemFile();
5664            FileOutputStream out = new FileOutputStream(fname, true);
5665            PrintWriter pw = new FastPrintWriter(out);
5666            SimpleDateFormat formatter = new SimpleDateFormat();
5667            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5668            pw.println(dateString + ": " + msg);
5669            pw.close();
5670            FileUtils.setPermissions(
5671                    fname.toString(),
5672                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5673                    -1, -1);
5674        } catch (java.io.IOException e) {
5675        }
5676    }
5677
5678    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5679            PackageParser.Package pkg, File srcFile, int parseFlags)
5680            throws PackageManagerException {
5681        if (ps != null
5682                && ps.codePath.equals(srcFile)
5683                && ps.timeStamp == srcFile.lastModified()
5684                && !isCompatSignatureUpdateNeeded(pkg)
5685                && !isRecoverSignatureUpdateNeeded(pkg)) {
5686            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5687            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5688            ArraySet<PublicKey> signingKs;
5689            synchronized (mPackages) {
5690                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5691            }
5692            if (ps.signatures.mSignatures != null
5693                    && ps.signatures.mSignatures.length != 0
5694                    && signingKs != null) {
5695                // Optimization: reuse the existing cached certificates
5696                // if the package appears to be unchanged.
5697                pkg.mSignatures = ps.signatures.mSignatures;
5698                pkg.mSigningKeys = signingKs;
5699                return;
5700            }
5701
5702            Slog.w(TAG, "PackageSetting for " + ps.name
5703                    + " is missing signatures.  Collecting certs again to recover them.");
5704        } else {
5705            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5706        }
5707
5708        try {
5709            pp.collectCertificates(pkg, parseFlags);
5710            pp.collectManifestDigest(pkg);
5711        } catch (PackageParserException e) {
5712            throw PackageManagerException.from(e);
5713        }
5714    }
5715
5716    /*
5717     *  Scan a package and return the newly parsed package.
5718     *  Returns null in case of errors and the error code is stored in mLastScanError
5719     */
5720    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5721            long currentTime, UserHandle user) throws PackageManagerException {
5722        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5723        parseFlags |= mDefParseFlags;
5724        PackageParser pp = new PackageParser();
5725        pp.setSeparateProcesses(mSeparateProcesses);
5726        pp.setOnlyCoreApps(mOnlyCore);
5727        pp.setDisplayMetrics(mMetrics);
5728
5729        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5730            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5731        }
5732
5733        final PackageParser.Package pkg;
5734        try {
5735            pkg = pp.parsePackage(scanFile, parseFlags);
5736        } catch (PackageParserException e) {
5737            throw PackageManagerException.from(e);
5738        }
5739
5740        PackageSetting ps = null;
5741        PackageSetting updatedPkg;
5742        // reader
5743        synchronized (mPackages) {
5744            // Look to see if we already know about this package.
5745            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5746            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5747                // This package has been renamed to its original name.  Let's
5748                // use that.
5749                ps = mSettings.peekPackageLPr(oldName);
5750            }
5751            // If there was no original package, see one for the real package name.
5752            if (ps == null) {
5753                ps = mSettings.peekPackageLPr(pkg.packageName);
5754            }
5755            // Check to see if this package could be hiding/updating a system
5756            // package.  Must look for it either under the original or real
5757            // package name depending on our state.
5758            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5759            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5760        }
5761        boolean updatedPkgBetter = false;
5762        // First check if this is a system package that may involve an update
5763        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5764            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5765            // it needs to drop FLAG_PRIVILEGED.
5766            if (locationIsPrivileged(scanFile)) {
5767                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5768            } else {
5769                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5770            }
5771
5772            if (ps != null && !ps.codePath.equals(scanFile)) {
5773                // The path has changed from what was last scanned...  check the
5774                // version of the new path against what we have stored to determine
5775                // what to do.
5776                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5777                if (pkg.mVersionCode <= ps.versionCode) {
5778                    // The system package has been updated and the code path does not match
5779                    // Ignore entry. Skip it.
5780                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5781                            + " ignored: updated version " + ps.versionCode
5782                            + " better than this " + pkg.mVersionCode);
5783                    if (!updatedPkg.codePath.equals(scanFile)) {
5784                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5785                                + ps.name + " changing from " + updatedPkg.codePathString
5786                                + " to " + scanFile);
5787                        updatedPkg.codePath = scanFile;
5788                        updatedPkg.codePathString = scanFile.toString();
5789                        updatedPkg.resourcePath = scanFile;
5790                        updatedPkg.resourcePathString = scanFile.toString();
5791                    }
5792                    updatedPkg.pkg = pkg;
5793                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5794                            "Package " + ps.name + " at " + scanFile
5795                                    + " ignored: updated version " + ps.versionCode
5796                                    + " better than this " + pkg.mVersionCode);
5797                } else {
5798                    // The current app on the system partition is better than
5799                    // what we have updated to on the data partition; switch
5800                    // back to the system partition version.
5801                    // At this point, its safely assumed that package installation for
5802                    // apps in system partition will go through. If not there won't be a working
5803                    // version of the app
5804                    // writer
5805                    synchronized (mPackages) {
5806                        // Just remove the loaded entries from package lists.
5807                        mPackages.remove(ps.name);
5808                    }
5809
5810                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5811                            + " reverting from " + ps.codePathString
5812                            + ": new version " + pkg.mVersionCode
5813                            + " better than installed " + ps.versionCode);
5814
5815                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5816                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5817                    synchronized (mInstallLock) {
5818                        args.cleanUpResourcesLI();
5819                    }
5820                    synchronized (mPackages) {
5821                        mSettings.enableSystemPackageLPw(ps.name);
5822                    }
5823                    updatedPkgBetter = true;
5824                }
5825            }
5826        }
5827
5828        if (updatedPkg != null) {
5829            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5830            // initially
5831            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5832
5833            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5834            // flag set initially
5835            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5836                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5837            }
5838        }
5839
5840        // Verify certificates against what was last scanned
5841        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5842
5843        /*
5844         * A new system app appeared, but we already had a non-system one of the
5845         * same name installed earlier.
5846         */
5847        boolean shouldHideSystemApp = false;
5848        if (updatedPkg == null && ps != null
5849                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5850            /*
5851             * Check to make sure the signatures match first. If they don't,
5852             * wipe the installed application and its data.
5853             */
5854            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5855                    != PackageManager.SIGNATURE_MATCH) {
5856                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5857                        + " signatures don't match existing userdata copy; removing");
5858                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5859                ps = null;
5860            } else {
5861                /*
5862                 * If the newly-added system app is an older version than the
5863                 * already installed version, hide it. It will be scanned later
5864                 * and re-added like an update.
5865                 */
5866                if (pkg.mVersionCode <= ps.versionCode) {
5867                    shouldHideSystemApp = true;
5868                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5869                            + " but new version " + pkg.mVersionCode + " better than installed "
5870                            + ps.versionCode + "; hiding system");
5871                } else {
5872                    /*
5873                     * The newly found system app is a newer version that the
5874                     * one previously installed. Simply remove the
5875                     * already-installed application and replace it with our own
5876                     * while keeping the application data.
5877                     */
5878                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5879                            + " reverting from " + ps.codePathString + ": new version "
5880                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5881                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5882                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5883                    synchronized (mInstallLock) {
5884                        args.cleanUpResourcesLI();
5885                    }
5886                }
5887            }
5888        }
5889
5890        // The apk is forward locked (not public) if its code and resources
5891        // are kept in different files. (except for app in either system or
5892        // vendor path).
5893        // TODO grab this value from PackageSettings
5894        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5895            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5896                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5897            }
5898        }
5899
5900        // TODO: extend to support forward-locked splits
5901        String resourcePath = null;
5902        String baseResourcePath = null;
5903        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5904            if (ps != null && ps.resourcePathString != null) {
5905                resourcePath = ps.resourcePathString;
5906                baseResourcePath = ps.resourcePathString;
5907            } else {
5908                // Should not happen at all. Just log an error.
5909                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5910            }
5911        } else {
5912            resourcePath = pkg.codePath;
5913            baseResourcePath = pkg.baseCodePath;
5914        }
5915
5916        // Set application objects path explicitly.
5917        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5918        pkg.applicationInfo.setCodePath(pkg.codePath);
5919        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5920        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5921        pkg.applicationInfo.setResourcePath(resourcePath);
5922        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5923        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5924
5925        // Note that we invoke the following method only if we are about to unpack an application
5926        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5927                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5928
5929        /*
5930         * If the system app should be overridden by a previously installed
5931         * data, hide the system app now and let the /data/app scan pick it up
5932         * again.
5933         */
5934        if (shouldHideSystemApp) {
5935            synchronized (mPackages) {
5936                mSettings.disableSystemPackageLPw(pkg.packageName);
5937            }
5938        }
5939
5940        return scannedPkg;
5941    }
5942
5943    private static String fixProcessName(String defProcessName,
5944            String processName, int uid) {
5945        if (processName == null) {
5946            return defProcessName;
5947        }
5948        return processName;
5949    }
5950
5951    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5952            throws PackageManagerException {
5953        if (pkgSetting.signatures.mSignatures != null) {
5954            // Already existing package. Make sure signatures match
5955            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5956                    == PackageManager.SIGNATURE_MATCH;
5957            if (!match) {
5958                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5959                        == PackageManager.SIGNATURE_MATCH;
5960            }
5961            if (!match) {
5962                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5963                        == PackageManager.SIGNATURE_MATCH;
5964            }
5965            if (!match) {
5966                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5967                        + pkg.packageName + " signatures do not match the "
5968                        + "previously installed version; ignoring!");
5969            }
5970        }
5971
5972        // Check for shared user signatures
5973        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5974            // Already existing package. Make sure signatures match
5975            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5976                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5977            if (!match) {
5978                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5979                        == PackageManager.SIGNATURE_MATCH;
5980            }
5981            if (!match) {
5982                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5983                        == PackageManager.SIGNATURE_MATCH;
5984            }
5985            if (!match) {
5986                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5987                        "Package " + pkg.packageName
5988                        + " has no signatures that match those in shared user "
5989                        + pkgSetting.sharedUser.name + "; ignoring!");
5990            }
5991        }
5992    }
5993
5994    /**
5995     * Enforces that only the system UID or root's UID can call a method exposed
5996     * via Binder.
5997     *
5998     * @param message used as message if SecurityException is thrown
5999     * @throws SecurityException if the caller is not system or root
6000     */
6001    private static final void enforceSystemOrRoot(String message) {
6002        final int uid = Binder.getCallingUid();
6003        if (uid != Process.SYSTEM_UID && uid != 0) {
6004            throw new SecurityException(message);
6005        }
6006    }
6007
6008    @Override
6009    public void performBootDexOpt() {
6010        enforceSystemOrRoot("Only the system can request dexopt be performed");
6011
6012        // Before everything else, see whether we need to fstrim.
6013        try {
6014            IMountService ms = PackageHelper.getMountService();
6015            if (ms != null) {
6016                final boolean isUpgrade = isUpgrade();
6017                boolean doTrim = isUpgrade;
6018                if (doTrim) {
6019                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6020                } else {
6021                    final long interval = android.provider.Settings.Global.getLong(
6022                            mContext.getContentResolver(),
6023                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6024                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6025                    if (interval > 0) {
6026                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6027                        if (timeSinceLast > interval) {
6028                            doTrim = true;
6029                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6030                                    + "; running immediately");
6031                        }
6032                    }
6033                }
6034                if (doTrim) {
6035                    if (!isFirstBoot()) {
6036                        try {
6037                            ActivityManagerNative.getDefault().showBootMessage(
6038                                    mContext.getResources().getString(
6039                                            R.string.android_upgrading_fstrim), true);
6040                        } catch (RemoteException e) {
6041                        }
6042                    }
6043                    ms.runMaintenance();
6044                }
6045            } else {
6046                Slog.e(TAG, "Mount service unavailable!");
6047            }
6048        } catch (RemoteException e) {
6049            // Can't happen; MountService is local
6050        }
6051
6052        final ArraySet<PackageParser.Package> pkgs;
6053        synchronized (mPackages) {
6054            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6055        }
6056
6057        if (pkgs != null) {
6058            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6059            // in case the device runs out of space.
6060            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6061            // Give priority to core apps.
6062            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6063                PackageParser.Package pkg = it.next();
6064                if (pkg.coreApp) {
6065                    if (DEBUG_DEXOPT) {
6066                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6067                    }
6068                    sortedPkgs.add(pkg);
6069                    it.remove();
6070                }
6071            }
6072            // Give priority to system apps that listen for pre boot complete.
6073            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6074            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6075            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6076                PackageParser.Package pkg = it.next();
6077                if (pkgNames.contains(pkg.packageName)) {
6078                    if (DEBUG_DEXOPT) {
6079                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6080                    }
6081                    sortedPkgs.add(pkg);
6082                    it.remove();
6083                }
6084            }
6085            // Give priority to system apps.
6086            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6087                PackageParser.Package pkg = it.next();
6088                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6089                    if (DEBUG_DEXOPT) {
6090                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6091                    }
6092                    sortedPkgs.add(pkg);
6093                    it.remove();
6094                }
6095            }
6096            // Give priority to updated system apps.
6097            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6098                PackageParser.Package pkg = it.next();
6099                if (pkg.isUpdatedSystemApp()) {
6100                    if (DEBUG_DEXOPT) {
6101                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6102                    }
6103                    sortedPkgs.add(pkg);
6104                    it.remove();
6105                }
6106            }
6107            // Give priority to apps that listen for boot complete.
6108            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6109            pkgNames = getPackageNamesForIntent(intent);
6110            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6111                PackageParser.Package pkg = it.next();
6112                if (pkgNames.contains(pkg.packageName)) {
6113                    if (DEBUG_DEXOPT) {
6114                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6115                    }
6116                    sortedPkgs.add(pkg);
6117                    it.remove();
6118                }
6119            }
6120            // Filter out packages that aren't recently used.
6121            filterRecentlyUsedApps(pkgs);
6122            // Add all remaining apps.
6123            for (PackageParser.Package pkg : pkgs) {
6124                if (DEBUG_DEXOPT) {
6125                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6126                }
6127                sortedPkgs.add(pkg);
6128            }
6129
6130            // If we want to be lazy, filter everything that wasn't recently used.
6131            if (mLazyDexOpt) {
6132                filterRecentlyUsedApps(sortedPkgs);
6133            }
6134
6135            int i = 0;
6136            int total = sortedPkgs.size();
6137            File dataDir = Environment.getDataDirectory();
6138            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6139            if (lowThreshold == 0) {
6140                throw new IllegalStateException("Invalid low memory threshold");
6141            }
6142            for (PackageParser.Package pkg : sortedPkgs) {
6143                long usableSpace = dataDir.getUsableSpace();
6144                if (usableSpace < lowThreshold) {
6145                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6146                    break;
6147                }
6148                performBootDexOpt(pkg, ++i, total);
6149            }
6150        }
6151    }
6152
6153    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6154        // Filter out packages that aren't recently used.
6155        //
6156        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6157        // should do a full dexopt.
6158        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6159            int total = pkgs.size();
6160            int skipped = 0;
6161            long now = System.currentTimeMillis();
6162            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6163                PackageParser.Package pkg = i.next();
6164                long then = pkg.mLastPackageUsageTimeInMills;
6165                if (then + mDexOptLRUThresholdInMills < now) {
6166                    if (DEBUG_DEXOPT) {
6167                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6168                              ((then == 0) ? "never" : new Date(then)));
6169                    }
6170                    i.remove();
6171                    skipped++;
6172                }
6173            }
6174            if (DEBUG_DEXOPT) {
6175                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6176            }
6177        }
6178    }
6179
6180    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6181        List<ResolveInfo> ris = null;
6182        try {
6183            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6184                    intent, null, 0, UserHandle.USER_OWNER);
6185        } catch (RemoteException e) {
6186        }
6187        ArraySet<String> pkgNames = new ArraySet<String>();
6188        if (ris != null) {
6189            for (ResolveInfo ri : ris) {
6190                pkgNames.add(ri.activityInfo.packageName);
6191            }
6192        }
6193        return pkgNames;
6194    }
6195
6196    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6197        if (DEBUG_DEXOPT) {
6198            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6199        }
6200        if (!isFirstBoot()) {
6201            try {
6202                ActivityManagerNative.getDefault().showBootMessage(
6203                        mContext.getResources().getString(R.string.android_upgrading_apk,
6204                                curr, total), true);
6205            } catch (RemoteException e) {
6206            }
6207        }
6208        PackageParser.Package p = pkg;
6209        synchronized (mInstallLock) {
6210            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6211                    false /* force dex */, false /* defer */, true /* include dependencies */);
6212        }
6213    }
6214
6215    @Override
6216    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6217        return performDexOpt(packageName, instructionSet, false);
6218    }
6219
6220    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6221        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6222        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6223        if (!dexopt && !updateUsage) {
6224            // We aren't going to dexopt or update usage, so bail early.
6225            return false;
6226        }
6227        PackageParser.Package p;
6228        final String targetInstructionSet;
6229        synchronized (mPackages) {
6230            p = mPackages.get(packageName);
6231            if (p == null) {
6232                return false;
6233            }
6234            if (updateUsage) {
6235                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6236            }
6237            mPackageUsage.write(false);
6238            if (!dexopt) {
6239                // We aren't going to dexopt, so bail early.
6240                return false;
6241            }
6242
6243            targetInstructionSet = instructionSet != null ? instructionSet :
6244                    getPrimaryInstructionSet(p.applicationInfo);
6245            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6246                return false;
6247            }
6248        }
6249        long callingId = Binder.clearCallingIdentity();
6250        try {
6251            synchronized (mInstallLock) {
6252                final String[] instructionSets = new String[] { targetInstructionSet };
6253                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6254                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6255                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6256            }
6257        } finally {
6258            Binder.restoreCallingIdentity(callingId);
6259        }
6260    }
6261
6262    public ArraySet<String> getPackagesThatNeedDexOpt() {
6263        ArraySet<String> pkgs = null;
6264        synchronized (mPackages) {
6265            for (PackageParser.Package p : mPackages.values()) {
6266                if (DEBUG_DEXOPT) {
6267                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6268                }
6269                if (!p.mDexOptPerformed.isEmpty()) {
6270                    continue;
6271                }
6272                if (pkgs == null) {
6273                    pkgs = new ArraySet<String>();
6274                }
6275                pkgs.add(p.packageName);
6276            }
6277        }
6278        return pkgs;
6279    }
6280
6281    public void shutdown() {
6282        mPackageUsage.write(true);
6283    }
6284
6285    @Override
6286    public void forceDexOpt(String packageName) {
6287        enforceSystemOrRoot("forceDexOpt");
6288
6289        PackageParser.Package pkg;
6290        synchronized (mPackages) {
6291            pkg = mPackages.get(packageName);
6292            if (pkg == null) {
6293                throw new IllegalArgumentException("Missing package: " + packageName);
6294            }
6295        }
6296
6297        synchronized (mInstallLock) {
6298            final String[] instructionSets = new String[] {
6299                    getPrimaryInstructionSet(pkg.applicationInfo) };
6300            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6301                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6302            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6303                throw new IllegalStateException("Failed to dexopt: " + res);
6304            }
6305        }
6306    }
6307
6308    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6309        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6310            Slog.w(TAG, "Unable to update from " + oldPkg.name
6311                    + " to " + newPkg.packageName
6312                    + ": old package not in system partition");
6313            return false;
6314        } else if (mPackages.get(oldPkg.name) != null) {
6315            Slog.w(TAG, "Unable to update from " + oldPkg.name
6316                    + " to " + newPkg.packageName
6317                    + ": old package still exists");
6318            return false;
6319        }
6320        return true;
6321    }
6322
6323    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6324        int[] users = sUserManager.getUserIds();
6325        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6326        if (res < 0) {
6327            return res;
6328        }
6329        for (int user : users) {
6330            if (user != 0) {
6331                res = mInstaller.createUserData(volumeUuid, packageName,
6332                        UserHandle.getUid(user, uid), user, seinfo);
6333                if (res < 0) {
6334                    return res;
6335                }
6336            }
6337        }
6338        return res;
6339    }
6340
6341    private int removeDataDirsLI(String volumeUuid, String packageName) {
6342        int[] users = sUserManager.getUserIds();
6343        int res = 0;
6344        for (int user : users) {
6345            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6346            if (resInner < 0) {
6347                res = resInner;
6348            }
6349        }
6350
6351        return res;
6352    }
6353
6354    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6355        int[] users = sUserManager.getUserIds();
6356        int res = 0;
6357        for (int user : users) {
6358            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6359            if (resInner < 0) {
6360                res = resInner;
6361            }
6362        }
6363        return res;
6364    }
6365
6366    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6367            PackageParser.Package changingLib) {
6368        if (file.path != null) {
6369            usesLibraryFiles.add(file.path);
6370            return;
6371        }
6372        PackageParser.Package p = mPackages.get(file.apk);
6373        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6374            // If we are doing this while in the middle of updating a library apk,
6375            // then we need to make sure to use that new apk for determining the
6376            // dependencies here.  (We haven't yet finished committing the new apk
6377            // to the package manager state.)
6378            if (p == null || p.packageName.equals(changingLib.packageName)) {
6379                p = changingLib;
6380            }
6381        }
6382        if (p != null) {
6383            usesLibraryFiles.addAll(p.getAllCodePaths());
6384        }
6385    }
6386
6387    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6388            PackageParser.Package changingLib) throws PackageManagerException {
6389        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6390            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6391            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6392            for (int i=0; i<N; i++) {
6393                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6394                if (file == null) {
6395                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6396                            "Package " + pkg.packageName + " requires unavailable shared library "
6397                            + pkg.usesLibraries.get(i) + "; failing!");
6398                }
6399                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6400            }
6401            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6402            for (int i=0; i<N; i++) {
6403                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6404                if (file == null) {
6405                    Slog.w(TAG, "Package " + pkg.packageName
6406                            + " desires unavailable shared library "
6407                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6408                } else {
6409                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6410                }
6411            }
6412            N = usesLibraryFiles.size();
6413            if (N > 0) {
6414                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6415            } else {
6416                pkg.usesLibraryFiles = null;
6417            }
6418        }
6419    }
6420
6421    private static boolean hasString(List<String> list, List<String> which) {
6422        if (list == null) {
6423            return false;
6424        }
6425        for (int i=list.size()-1; i>=0; i--) {
6426            for (int j=which.size()-1; j>=0; j--) {
6427                if (which.get(j).equals(list.get(i))) {
6428                    return true;
6429                }
6430            }
6431        }
6432        return false;
6433    }
6434
6435    private void updateAllSharedLibrariesLPw() {
6436        for (PackageParser.Package pkg : mPackages.values()) {
6437            try {
6438                updateSharedLibrariesLPw(pkg, null);
6439            } catch (PackageManagerException e) {
6440                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6441            }
6442        }
6443    }
6444
6445    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6446            PackageParser.Package changingPkg) {
6447        ArrayList<PackageParser.Package> res = null;
6448        for (PackageParser.Package pkg : mPackages.values()) {
6449            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6450                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6451                if (res == null) {
6452                    res = new ArrayList<PackageParser.Package>();
6453                }
6454                res.add(pkg);
6455                try {
6456                    updateSharedLibrariesLPw(pkg, changingPkg);
6457                } catch (PackageManagerException e) {
6458                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6459                }
6460            }
6461        }
6462        return res;
6463    }
6464
6465    /**
6466     * Derive the value of the {@code cpuAbiOverride} based on the provided
6467     * value and an optional stored value from the package settings.
6468     */
6469    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6470        String cpuAbiOverride = null;
6471
6472        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6473            cpuAbiOverride = null;
6474        } else if (abiOverride != null) {
6475            cpuAbiOverride = abiOverride;
6476        } else if (settings != null) {
6477            cpuAbiOverride = settings.cpuAbiOverrideString;
6478        }
6479
6480        return cpuAbiOverride;
6481    }
6482
6483    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6484            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6485        boolean success = false;
6486        try {
6487            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6488                    currentTime, user);
6489            success = true;
6490            return res;
6491        } finally {
6492            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6493                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6494            }
6495        }
6496    }
6497
6498    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6499            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6500        final File scanFile = new File(pkg.codePath);
6501        if (pkg.applicationInfo.getCodePath() == null ||
6502                pkg.applicationInfo.getResourcePath() == null) {
6503            // Bail out. The resource and code paths haven't been set.
6504            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6505                    "Code and resource paths haven't been set correctly");
6506        }
6507
6508        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6509            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6510        } else {
6511            // Only allow system apps to be flagged as core apps.
6512            pkg.coreApp = false;
6513        }
6514
6515        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6516            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6517        }
6518
6519        if (mCustomResolverComponentName != null &&
6520                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6521            setUpCustomResolverActivity(pkg);
6522        }
6523
6524        if (pkg.packageName.equals("android")) {
6525            synchronized (mPackages) {
6526                if (mAndroidApplication != null) {
6527                    Slog.w(TAG, "*************************************************");
6528                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6529                    Slog.w(TAG, " file=" + scanFile);
6530                    Slog.w(TAG, "*************************************************");
6531                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6532                            "Core android package being redefined.  Skipping.");
6533                }
6534
6535                // Set up information for our fall-back user intent resolution activity.
6536                mPlatformPackage = pkg;
6537                pkg.mVersionCode = mSdkVersion;
6538                mAndroidApplication = pkg.applicationInfo;
6539
6540                if (!mResolverReplaced) {
6541                    mResolveActivity.applicationInfo = mAndroidApplication;
6542                    mResolveActivity.name = ResolverActivity.class.getName();
6543                    mResolveActivity.packageName = mAndroidApplication.packageName;
6544                    mResolveActivity.processName = "system:ui";
6545                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6546                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6547                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6548                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6549                    mResolveActivity.exported = true;
6550                    mResolveActivity.enabled = true;
6551                    mResolveInfo.activityInfo = mResolveActivity;
6552                    mResolveInfo.priority = 0;
6553                    mResolveInfo.preferredOrder = 0;
6554                    mResolveInfo.match = 0;
6555                    mResolveComponentName = new ComponentName(
6556                            mAndroidApplication.packageName, mResolveActivity.name);
6557                }
6558            }
6559        }
6560
6561        if (DEBUG_PACKAGE_SCANNING) {
6562            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6563                Log.d(TAG, "Scanning package " + pkg.packageName);
6564        }
6565
6566        if (mPackages.containsKey(pkg.packageName)
6567                || mSharedLibraries.containsKey(pkg.packageName)) {
6568            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6569                    "Application package " + pkg.packageName
6570                    + " already installed.  Skipping duplicate.");
6571        }
6572
6573        // If we're only installing presumed-existing packages, require that the
6574        // scanned APK is both already known and at the path previously established
6575        // for it.  Previously unknown packages we pick up normally, but if we have an
6576        // a priori expectation about this package's install presence, enforce it.
6577        // With a singular exception for new system packages. When an OTA contains
6578        // a new system package, we allow the codepath to change from a system location
6579        // to the user-installed location. If we don't allow this change, any newer,
6580        // user-installed version of the application will be ignored.
6581        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6582            if (mExpectingBetter.containsKey(pkg.packageName)) {
6583                logCriticalInfo(Log.WARN,
6584                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6585            } else {
6586                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6587                if (known != null) {
6588                    if (DEBUG_PACKAGE_SCANNING) {
6589                        Log.d(TAG, "Examining " + pkg.codePath
6590                                + " and requiring known paths " + known.codePathString
6591                                + " & " + known.resourcePathString);
6592                    }
6593                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6594                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6595                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6596                                "Application package " + pkg.packageName
6597                                + " found at " + pkg.applicationInfo.getCodePath()
6598                                + " but expected at " + known.codePathString + "; ignoring.");
6599                    }
6600                }
6601            }
6602        }
6603
6604        // Initialize package source and resource directories
6605        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6606        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6607
6608        SharedUserSetting suid = null;
6609        PackageSetting pkgSetting = null;
6610
6611        if (!isSystemApp(pkg)) {
6612            // Only system apps can use these features.
6613            pkg.mOriginalPackages = null;
6614            pkg.mRealPackage = null;
6615            pkg.mAdoptPermissions = null;
6616        }
6617
6618        // writer
6619        synchronized (mPackages) {
6620            if (pkg.mSharedUserId != null) {
6621                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6622                if (suid == null) {
6623                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6624                            "Creating application package " + pkg.packageName
6625                            + " for shared user failed");
6626                }
6627                if (DEBUG_PACKAGE_SCANNING) {
6628                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6629                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6630                                + "): packages=" + suid.packages);
6631                }
6632            }
6633
6634            // Check if we are renaming from an original package name.
6635            PackageSetting origPackage = null;
6636            String realName = null;
6637            if (pkg.mOriginalPackages != null) {
6638                // This package may need to be renamed to a previously
6639                // installed name.  Let's check on that...
6640                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6641                if (pkg.mOriginalPackages.contains(renamed)) {
6642                    // This package had originally been installed as the
6643                    // original name, and we have already taken care of
6644                    // transitioning to the new one.  Just update the new
6645                    // one to continue using the old name.
6646                    realName = pkg.mRealPackage;
6647                    if (!pkg.packageName.equals(renamed)) {
6648                        // Callers into this function may have already taken
6649                        // care of renaming the package; only do it here if
6650                        // it is not already done.
6651                        pkg.setPackageName(renamed);
6652                    }
6653
6654                } else {
6655                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6656                        if ((origPackage = mSettings.peekPackageLPr(
6657                                pkg.mOriginalPackages.get(i))) != null) {
6658                            // We do have the package already installed under its
6659                            // original name...  should we use it?
6660                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6661                                // New package is not compatible with original.
6662                                origPackage = null;
6663                                continue;
6664                            } else if (origPackage.sharedUser != null) {
6665                                // Make sure uid is compatible between packages.
6666                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6667                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6668                                            + " to " + pkg.packageName + ": old uid "
6669                                            + origPackage.sharedUser.name
6670                                            + " differs from " + pkg.mSharedUserId);
6671                                    origPackage = null;
6672                                    continue;
6673                                }
6674                            } else {
6675                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6676                                        + pkg.packageName + " to old name " + origPackage.name);
6677                            }
6678                            break;
6679                        }
6680                    }
6681                }
6682            }
6683
6684            if (mTransferedPackages.contains(pkg.packageName)) {
6685                Slog.w(TAG, "Package " + pkg.packageName
6686                        + " was transferred to another, but its .apk remains");
6687            }
6688
6689            // Just create the setting, don't add it yet. For already existing packages
6690            // the PkgSetting exists already and doesn't have to be created.
6691            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6692                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6693                    pkg.applicationInfo.primaryCpuAbi,
6694                    pkg.applicationInfo.secondaryCpuAbi,
6695                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6696                    user, false);
6697            if (pkgSetting == null) {
6698                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6699                        "Creating application package " + pkg.packageName + " failed");
6700            }
6701
6702            if (pkgSetting.origPackage != null) {
6703                // If we are first transitioning from an original package,
6704                // fix up the new package's name now.  We need to do this after
6705                // looking up the package under its new name, so getPackageLP
6706                // can take care of fiddling things correctly.
6707                pkg.setPackageName(origPackage.name);
6708
6709                // File a report about this.
6710                String msg = "New package " + pkgSetting.realName
6711                        + " renamed to replace old package " + pkgSetting.name;
6712                reportSettingsProblem(Log.WARN, msg);
6713
6714                // Make a note of it.
6715                mTransferedPackages.add(origPackage.name);
6716
6717                // No longer need to retain this.
6718                pkgSetting.origPackage = null;
6719            }
6720
6721            if (realName != null) {
6722                // Make a note of it.
6723                mTransferedPackages.add(pkg.packageName);
6724            }
6725
6726            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6727                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6728            }
6729
6730            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6731                // Check all shared libraries and map to their actual file path.
6732                // We only do this here for apps not on a system dir, because those
6733                // are the only ones that can fail an install due to this.  We
6734                // will take care of the system apps by updating all of their
6735                // library paths after the scan is done.
6736                updateSharedLibrariesLPw(pkg, null);
6737            }
6738
6739            if (mFoundPolicyFile) {
6740                SELinuxMMAC.assignSeinfoValue(pkg);
6741            }
6742
6743            pkg.applicationInfo.uid = pkgSetting.appId;
6744            pkg.mExtras = pkgSetting;
6745            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6746                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6747                    // We just determined the app is signed correctly, so bring
6748                    // over the latest parsed certs.
6749                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6750                } else {
6751                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6752                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6753                                "Package " + pkg.packageName + " upgrade keys do not match the "
6754                                + "previously installed version");
6755                    } else {
6756                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6757                        String msg = "System package " + pkg.packageName
6758                            + " signature changed; retaining data.";
6759                        reportSettingsProblem(Log.WARN, msg);
6760                    }
6761                }
6762            } else {
6763                try {
6764                    verifySignaturesLP(pkgSetting, pkg);
6765                    // We just determined the app is signed correctly, so bring
6766                    // over the latest parsed certs.
6767                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6768                } catch (PackageManagerException e) {
6769                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6770                        throw e;
6771                    }
6772                    // The signature has changed, but this package is in the system
6773                    // image...  let's recover!
6774                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6775                    // However...  if this package is part of a shared user, but it
6776                    // doesn't match the signature of the shared user, let's fail.
6777                    // What this means is that you can't change the signatures
6778                    // associated with an overall shared user, which doesn't seem all
6779                    // that unreasonable.
6780                    if (pkgSetting.sharedUser != null) {
6781                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6782                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6783                            throw new PackageManagerException(
6784                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6785                                            "Signature mismatch for shared user : "
6786                                            + pkgSetting.sharedUser);
6787                        }
6788                    }
6789                    // File a report about this.
6790                    String msg = "System package " + pkg.packageName
6791                        + " signature changed; retaining data.";
6792                    reportSettingsProblem(Log.WARN, msg);
6793                }
6794            }
6795            // Verify that this new package doesn't have any content providers
6796            // that conflict with existing packages.  Only do this if the
6797            // package isn't already installed, since we don't want to break
6798            // things that are installed.
6799            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6800                final int N = pkg.providers.size();
6801                int i;
6802                for (i=0; i<N; i++) {
6803                    PackageParser.Provider p = pkg.providers.get(i);
6804                    if (p.info.authority != null) {
6805                        String names[] = p.info.authority.split(";");
6806                        for (int j = 0; j < names.length; j++) {
6807                            if (mProvidersByAuthority.containsKey(names[j])) {
6808                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6809                                final String otherPackageName =
6810                                        ((other != null && other.getComponentName() != null) ?
6811                                                other.getComponentName().getPackageName() : "?");
6812                                throw new PackageManagerException(
6813                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6814                                                "Can't install because provider name " + names[j]
6815                                                + " (in package " + pkg.applicationInfo.packageName
6816                                                + ") is already used by " + otherPackageName);
6817                            }
6818                        }
6819                    }
6820                }
6821            }
6822
6823            if (pkg.mAdoptPermissions != null) {
6824                // This package wants to adopt ownership of permissions from
6825                // another package.
6826                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6827                    final String origName = pkg.mAdoptPermissions.get(i);
6828                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6829                    if (orig != null) {
6830                        if (verifyPackageUpdateLPr(orig, pkg)) {
6831                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6832                                    + pkg.packageName);
6833                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6834                        }
6835                    }
6836                }
6837            }
6838        }
6839
6840        final String pkgName = pkg.packageName;
6841
6842        final long scanFileTime = scanFile.lastModified();
6843        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6844        pkg.applicationInfo.processName = fixProcessName(
6845                pkg.applicationInfo.packageName,
6846                pkg.applicationInfo.processName,
6847                pkg.applicationInfo.uid);
6848
6849        File dataPath;
6850        if (mPlatformPackage == pkg) {
6851            // The system package is special.
6852            dataPath = new File(Environment.getDataDirectory(), "system");
6853
6854            pkg.applicationInfo.dataDir = dataPath.getPath();
6855
6856        } else {
6857            // This is a normal package, need to make its data directory.
6858            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6859                    UserHandle.USER_OWNER, pkg.packageName);
6860
6861            boolean uidError = false;
6862            if (dataPath.exists()) {
6863                int currentUid = 0;
6864                try {
6865                    StructStat stat = Os.stat(dataPath.getPath());
6866                    currentUid = stat.st_uid;
6867                } catch (ErrnoException e) {
6868                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6869                }
6870
6871                // If we have mismatched owners for the data path, we have a problem.
6872                if (currentUid != pkg.applicationInfo.uid) {
6873                    boolean recovered = false;
6874                    if (currentUid == 0) {
6875                        // The directory somehow became owned by root.  Wow.
6876                        // This is probably because the system was stopped while
6877                        // installd was in the middle of messing with its libs
6878                        // directory.  Ask installd to fix that.
6879                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6880                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6881                        if (ret >= 0) {
6882                            recovered = true;
6883                            String msg = "Package " + pkg.packageName
6884                                    + " unexpectedly changed to uid 0; recovered to " +
6885                                    + pkg.applicationInfo.uid;
6886                            reportSettingsProblem(Log.WARN, msg);
6887                        }
6888                    }
6889                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6890                            || (scanFlags&SCAN_BOOTING) != 0)) {
6891                        // If this is a system app, we can at least delete its
6892                        // current data so the application will still work.
6893                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6894                        if (ret >= 0) {
6895                            // TODO: Kill the processes first
6896                            // Old data gone!
6897                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6898                                    ? "System package " : "Third party package ";
6899                            String msg = prefix + pkg.packageName
6900                                    + " has changed from uid: "
6901                                    + currentUid + " to "
6902                                    + pkg.applicationInfo.uid + "; old data erased";
6903                            reportSettingsProblem(Log.WARN, msg);
6904                            recovered = true;
6905
6906                            // And now re-install the app.
6907                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6908                                    pkg.applicationInfo.seinfo);
6909                            if (ret == -1) {
6910                                // Ack should not happen!
6911                                msg = prefix + pkg.packageName
6912                                        + " could not have data directory re-created after delete.";
6913                                reportSettingsProblem(Log.WARN, msg);
6914                                throw new PackageManagerException(
6915                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6916                            }
6917                        }
6918                        if (!recovered) {
6919                            mHasSystemUidErrors = true;
6920                        }
6921                    } else if (!recovered) {
6922                        // If we allow this install to proceed, we will be broken.
6923                        // Abort, abort!
6924                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6925                                "scanPackageLI");
6926                    }
6927                    if (!recovered) {
6928                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6929                            + pkg.applicationInfo.uid + "/fs_"
6930                            + currentUid;
6931                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6932                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6933                        String msg = "Package " + pkg.packageName
6934                                + " has mismatched uid: "
6935                                + currentUid + " on disk, "
6936                                + pkg.applicationInfo.uid + " in settings";
6937                        // writer
6938                        synchronized (mPackages) {
6939                            mSettings.mReadMessages.append(msg);
6940                            mSettings.mReadMessages.append('\n');
6941                            uidError = true;
6942                            if (!pkgSetting.uidError) {
6943                                reportSettingsProblem(Log.ERROR, msg);
6944                            }
6945                        }
6946                    }
6947                }
6948                pkg.applicationInfo.dataDir = dataPath.getPath();
6949                if (mShouldRestoreconData) {
6950                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6951                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6952                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6953                }
6954            } else {
6955                if (DEBUG_PACKAGE_SCANNING) {
6956                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6957                        Log.v(TAG, "Want this data dir: " + dataPath);
6958                }
6959                //invoke installer to do the actual installation
6960                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6961                        pkg.applicationInfo.seinfo);
6962                if (ret < 0) {
6963                    // Error from installer
6964                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6965                            "Unable to create data dirs [errorCode=" + ret + "]");
6966                }
6967
6968                if (dataPath.exists()) {
6969                    pkg.applicationInfo.dataDir = dataPath.getPath();
6970                } else {
6971                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6972                    pkg.applicationInfo.dataDir = null;
6973                }
6974            }
6975
6976            pkgSetting.uidError = uidError;
6977        }
6978
6979        final String path = scanFile.getPath();
6980        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6981
6982        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6983            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6984
6985            // Some system apps still use directory structure for native libraries
6986            // in which case we might end up not detecting abi solely based on apk
6987            // structure. Try to detect abi based on directory structure.
6988            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6989                    pkg.applicationInfo.primaryCpuAbi == null) {
6990                setBundledAppAbisAndRoots(pkg, pkgSetting);
6991                setNativeLibraryPaths(pkg);
6992            }
6993
6994        } else {
6995            if ((scanFlags & SCAN_MOVE) != 0) {
6996                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6997                // but we already have this packages package info in the PackageSetting. We just
6998                // use that and derive the native library path based on the new codepath.
6999                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7000                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7001            }
7002
7003            // Set native library paths again. For moves, the path will be updated based on the
7004            // ABIs we've determined above. For non-moves, the path will be updated based on the
7005            // ABIs we determined during compilation, but the path will depend on the final
7006            // package path (after the rename away from the stage path).
7007            setNativeLibraryPaths(pkg);
7008        }
7009
7010        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7011        final int[] userIds = sUserManager.getUserIds();
7012        synchronized (mInstallLock) {
7013            // Make sure all user data directories are ready to roll; we're okay
7014            // if they already exist
7015            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7016                for (int userId : userIds) {
7017                    if (userId != 0) {
7018                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7019                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7020                                pkg.applicationInfo.seinfo);
7021                    }
7022                }
7023            }
7024
7025            // Create a native library symlink only if we have native libraries
7026            // and if the native libraries are 32 bit libraries. We do not provide
7027            // this symlink for 64 bit libraries.
7028            if (pkg.applicationInfo.primaryCpuAbi != null &&
7029                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7030                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7031                for (int userId : userIds) {
7032                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7033                            nativeLibPath, userId) < 0) {
7034                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7035                                "Failed linking native library dir (user=" + userId + ")");
7036                    }
7037                }
7038            }
7039        }
7040
7041        // This is a special case for the "system" package, where the ABI is
7042        // dictated by the zygote configuration (and init.rc). We should keep track
7043        // of this ABI so that we can deal with "normal" applications that run under
7044        // the same UID correctly.
7045        if (mPlatformPackage == pkg) {
7046            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7047                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7048        }
7049
7050        // If there's a mismatch between the abi-override in the package setting
7051        // and the abiOverride specified for the install. Warn about this because we
7052        // would've already compiled the app without taking the package setting into
7053        // account.
7054        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7055            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7056                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7057                        " for package: " + pkg.packageName);
7058            }
7059        }
7060
7061        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7062        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7063        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7064
7065        // Copy the derived override back to the parsed package, so that we can
7066        // update the package settings accordingly.
7067        pkg.cpuAbiOverride = cpuAbiOverride;
7068
7069        if (DEBUG_ABI_SELECTION) {
7070            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7071                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7072                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7073        }
7074
7075        // Push the derived path down into PackageSettings so we know what to
7076        // clean up at uninstall time.
7077        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7078
7079        if (DEBUG_ABI_SELECTION) {
7080            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7081                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7082                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7083        }
7084
7085        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7086            // We don't do this here during boot because we can do it all
7087            // at once after scanning all existing packages.
7088            //
7089            // We also do this *before* we perform dexopt on this package, so that
7090            // we can avoid redundant dexopts, and also to make sure we've got the
7091            // code and package path correct.
7092            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7093                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7094        }
7095
7096        if ((scanFlags & SCAN_NO_DEX) == 0) {
7097            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7098                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7099            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7100                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7101            }
7102        }
7103        if (mFactoryTest && pkg.requestedPermissions.contains(
7104                android.Manifest.permission.FACTORY_TEST)) {
7105            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7106        }
7107
7108        ArrayList<PackageParser.Package> clientLibPkgs = null;
7109
7110        // writer
7111        synchronized (mPackages) {
7112            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7113                // Only system apps can add new shared libraries.
7114                if (pkg.libraryNames != null) {
7115                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7116                        String name = pkg.libraryNames.get(i);
7117                        boolean allowed = false;
7118                        if (pkg.isUpdatedSystemApp()) {
7119                            // New library entries can only be added through the
7120                            // system image.  This is important to get rid of a lot
7121                            // of nasty edge cases: for example if we allowed a non-
7122                            // system update of the app to add a library, then uninstalling
7123                            // the update would make the library go away, and assumptions
7124                            // we made such as through app install filtering would now
7125                            // have allowed apps on the device which aren't compatible
7126                            // with it.  Better to just have the restriction here, be
7127                            // conservative, and create many fewer cases that can negatively
7128                            // impact the user experience.
7129                            final PackageSetting sysPs = mSettings
7130                                    .getDisabledSystemPkgLPr(pkg.packageName);
7131                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7132                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7133                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7134                                        allowed = true;
7135                                        allowed = true;
7136                                        break;
7137                                    }
7138                                }
7139                            }
7140                        } else {
7141                            allowed = true;
7142                        }
7143                        if (allowed) {
7144                            if (!mSharedLibraries.containsKey(name)) {
7145                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7146                            } else if (!name.equals(pkg.packageName)) {
7147                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7148                                        + name + " already exists; skipping");
7149                            }
7150                        } else {
7151                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7152                                    + name + " that is not declared on system image; skipping");
7153                        }
7154                    }
7155                    if ((scanFlags&SCAN_BOOTING) == 0) {
7156                        // If we are not booting, we need to update any applications
7157                        // that are clients of our shared library.  If we are booting,
7158                        // this will all be done once the scan is complete.
7159                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7160                    }
7161                }
7162            }
7163        }
7164
7165        // We also need to dexopt any apps that are dependent on this library.  Note that
7166        // if these fail, we should abort the install since installing the library will
7167        // result in some apps being broken.
7168        if (clientLibPkgs != null) {
7169            if ((scanFlags & SCAN_NO_DEX) == 0) {
7170                for (int i = 0; i < clientLibPkgs.size(); i++) {
7171                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7172                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7173                            null /* instruction sets */, forceDex,
7174                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7175                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7176                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7177                                "scanPackageLI failed to dexopt clientLibPkgs");
7178                    }
7179                }
7180            }
7181        }
7182
7183        // Request the ActivityManager to kill the process(only for existing packages)
7184        // so that we do not end up in a confused state while the user is still using the older
7185        // version of the application while the new one gets installed.
7186        if ((scanFlags & SCAN_REPLACING) != 0) {
7187            killApplication(pkg.applicationInfo.packageName,
7188                        pkg.applicationInfo.uid, "replace pkg");
7189        }
7190
7191        // Also need to kill any apps that are dependent on the library.
7192        if (clientLibPkgs != null) {
7193            for (int i=0; i<clientLibPkgs.size(); i++) {
7194                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7195                killApplication(clientPkg.applicationInfo.packageName,
7196                        clientPkg.applicationInfo.uid, "update lib");
7197            }
7198        }
7199
7200        // Make sure we're not adding any bogus keyset info
7201        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7202        ksms.assertScannedPackageValid(pkg);
7203
7204        // writer
7205        synchronized (mPackages) {
7206            // We don't expect installation to fail beyond this point
7207
7208            // Add the new setting to mSettings
7209            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7210            // Add the new setting to mPackages
7211            mPackages.put(pkg.applicationInfo.packageName, pkg);
7212            // Make sure we don't accidentally delete its data.
7213            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7214            while (iter.hasNext()) {
7215                PackageCleanItem item = iter.next();
7216                if (pkgName.equals(item.packageName)) {
7217                    iter.remove();
7218                }
7219            }
7220
7221            // Take care of first install / last update times.
7222            if (currentTime != 0) {
7223                if (pkgSetting.firstInstallTime == 0) {
7224                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7225                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7226                    pkgSetting.lastUpdateTime = currentTime;
7227                }
7228            } else if (pkgSetting.firstInstallTime == 0) {
7229                // We need *something*.  Take time time stamp of the file.
7230                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7231            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7232                if (scanFileTime != pkgSetting.timeStamp) {
7233                    // A package on the system image has changed; consider this
7234                    // to be an update.
7235                    pkgSetting.lastUpdateTime = scanFileTime;
7236                }
7237            }
7238
7239            // Add the package's KeySets to the global KeySetManagerService
7240            ksms.addScannedPackageLPw(pkg);
7241
7242            int N = pkg.providers.size();
7243            StringBuilder r = null;
7244            int i;
7245            for (i=0; i<N; i++) {
7246                PackageParser.Provider p = pkg.providers.get(i);
7247                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7248                        p.info.processName, pkg.applicationInfo.uid);
7249                mProviders.addProvider(p);
7250                p.syncable = p.info.isSyncable;
7251                if (p.info.authority != null) {
7252                    String names[] = p.info.authority.split(";");
7253                    p.info.authority = null;
7254                    for (int j = 0; j < names.length; j++) {
7255                        if (j == 1 && p.syncable) {
7256                            // We only want the first authority for a provider to possibly be
7257                            // syncable, so if we already added this provider using a different
7258                            // authority clear the syncable flag. We copy the provider before
7259                            // changing it because the mProviders object contains a reference
7260                            // to a provider that we don't want to change.
7261                            // Only do this for the second authority since the resulting provider
7262                            // object can be the same for all future authorities for this provider.
7263                            p = new PackageParser.Provider(p);
7264                            p.syncable = false;
7265                        }
7266                        if (!mProvidersByAuthority.containsKey(names[j])) {
7267                            mProvidersByAuthority.put(names[j], p);
7268                            if (p.info.authority == null) {
7269                                p.info.authority = names[j];
7270                            } else {
7271                                p.info.authority = p.info.authority + ";" + names[j];
7272                            }
7273                            if (DEBUG_PACKAGE_SCANNING) {
7274                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7275                                    Log.d(TAG, "Registered content provider: " + names[j]
7276                                            + ", className = " + p.info.name + ", isSyncable = "
7277                                            + p.info.isSyncable);
7278                            }
7279                        } else {
7280                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7281                            Slog.w(TAG, "Skipping provider name " + names[j] +
7282                                    " (in package " + pkg.applicationInfo.packageName +
7283                                    "): name already used by "
7284                                    + ((other != null && other.getComponentName() != null)
7285                                            ? other.getComponentName().getPackageName() : "?"));
7286                        }
7287                    }
7288                }
7289                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7290                    if (r == null) {
7291                        r = new StringBuilder(256);
7292                    } else {
7293                        r.append(' ');
7294                    }
7295                    r.append(p.info.name);
7296                }
7297            }
7298            if (r != null) {
7299                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7300            }
7301
7302            N = pkg.services.size();
7303            r = null;
7304            for (i=0; i<N; i++) {
7305                PackageParser.Service s = pkg.services.get(i);
7306                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7307                        s.info.processName, pkg.applicationInfo.uid);
7308                mServices.addService(s);
7309                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7310                    if (r == null) {
7311                        r = new StringBuilder(256);
7312                    } else {
7313                        r.append(' ');
7314                    }
7315                    r.append(s.info.name);
7316                }
7317            }
7318            if (r != null) {
7319                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7320            }
7321
7322            N = pkg.receivers.size();
7323            r = null;
7324            for (i=0; i<N; i++) {
7325                PackageParser.Activity a = pkg.receivers.get(i);
7326                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7327                        a.info.processName, pkg.applicationInfo.uid);
7328                mReceivers.addActivity(a, "receiver");
7329                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7330                    if (r == null) {
7331                        r = new StringBuilder(256);
7332                    } else {
7333                        r.append(' ');
7334                    }
7335                    r.append(a.info.name);
7336                }
7337            }
7338            if (r != null) {
7339                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7340            }
7341
7342            N = pkg.activities.size();
7343            r = null;
7344            for (i=0; i<N; i++) {
7345                PackageParser.Activity a = pkg.activities.get(i);
7346                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7347                        a.info.processName, pkg.applicationInfo.uid);
7348                mActivities.addActivity(a, "activity");
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(a.info.name);
7356                }
7357            }
7358            if (r != null) {
7359                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7360            }
7361
7362            N = pkg.permissionGroups.size();
7363            r = null;
7364            for (i=0; i<N; i++) {
7365                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7366                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7367                if (cur == null) {
7368                    mPermissionGroups.put(pg.info.name, pg);
7369                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7370                        if (r == null) {
7371                            r = new StringBuilder(256);
7372                        } else {
7373                            r.append(' ');
7374                        }
7375                        r.append(pg.info.name);
7376                    }
7377                } else {
7378                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7379                            + pg.info.packageName + " ignored: original from "
7380                            + cur.info.packageName);
7381                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7382                        if (r == null) {
7383                            r = new StringBuilder(256);
7384                        } else {
7385                            r.append(' ');
7386                        }
7387                        r.append("DUP:");
7388                        r.append(pg.info.name);
7389                    }
7390                }
7391            }
7392            if (r != null) {
7393                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7394            }
7395
7396            N = pkg.permissions.size();
7397            r = null;
7398            for (i=0; i<N; i++) {
7399                PackageParser.Permission p = pkg.permissions.get(i);
7400
7401                // Assume by default that we did not install this permission into the system.
7402                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7403
7404                // Now that permission groups have a special meaning, we ignore permission
7405                // groups for legacy apps to prevent unexpected behavior. In particular,
7406                // permissions for one app being granted to someone just becuase they happen
7407                // to be in a group defined by another app (before this had no implications).
7408                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7409                    p.group = mPermissionGroups.get(p.info.group);
7410                    // Warn for a permission in an unknown group.
7411                    if (p.info.group != null && p.group == null) {
7412                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7413                                + p.info.packageName + " in an unknown group " + p.info.group);
7414                    }
7415                }
7416
7417                ArrayMap<String, BasePermission> permissionMap =
7418                        p.tree ? mSettings.mPermissionTrees
7419                                : mSettings.mPermissions;
7420                BasePermission bp = permissionMap.get(p.info.name);
7421
7422                // Allow system apps to redefine non-system permissions
7423                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7424                    final boolean currentOwnerIsSystem = (bp.perm != null
7425                            && isSystemApp(bp.perm.owner));
7426                    if (isSystemApp(p.owner)) {
7427                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7428                            // It's a built-in permission and no owner, take ownership now
7429                            bp.packageSetting = pkgSetting;
7430                            bp.perm = p;
7431                            bp.uid = pkg.applicationInfo.uid;
7432                            bp.sourcePackage = p.info.packageName;
7433                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7434                        } else if (!currentOwnerIsSystem) {
7435                            String msg = "New decl " + p.owner + " of permission  "
7436                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7437                            reportSettingsProblem(Log.WARN, msg);
7438                            bp = null;
7439                        }
7440                    }
7441                }
7442
7443                if (bp == null) {
7444                    bp = new BasePermission(p.info.name, p.info.packageName,
7445                            BasePermission.TYPE_NORMAL);
7446                    permissionMap.put(p.info.name, bp);
7447                }
7448
7449                if (bp.perm == null) {
7450                    if (bp.sourcePackage == null
7451                            || bp.sourcePackage.equals(p.info.packageName)) {
7452                        BasePermission tree = findPermissionTreeLP(p.info.name);
7453                        if (tree == null
7454                                || tree.sourcePackage.equals(p.info.packageName)) {
7455                            bp.packageSetting = pkgSetting;
7456                            bp.perm = p;
7457                            bp.uid = pkg.applicationInfo.uid;
7458                            bp.sourcePackage = p.info.packageName;
7459                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7460                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7461                                if (r == null) {
7462                                    r = new StringBuilder(256);
7463                                } else {
7464                                    r.append(' ');
7465                                }
7466                                r.append(p.info.name);
7467                            }
7468                        } else {
7469                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7470                                    + p.info.packageName + " ignored: base tree "
7471                                    + tree.name + " is from package "
7472                                    + tree.sourcePackage);
7473                        }
7474                    } else {
7475                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7476                                + p.info.packageName + " ignored: original from "
7477                                + bp.sourcePackage);
7478                    }
7479                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7480                    if (r == null) {
7481                        r = new StringBuilder(256);
7482                    } else {
7483                        r.append(' ');
7484                    }
7485                    r.append("DUP:");
7486                    r.append(p.info.name);
7487                }
7488                if (bp.perm == p) {
7489                    bp.protectionLevel = p.info.protectionLevel;
7490                }
7491            }
7492
7493            if (r != null) {
7494                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7495            }
7496
7497            N = pkg.instrumentation.size();
7498            r = null;
7499            for (i=0; i<N; i++) {
7500                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7501                a.info.packageName = pkg.applicationInfo.packageName;
7502                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7503                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7504                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7505                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7506                a.info.dataDir = pkg.applicationInfo.dataDir;
7507
7508                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7509                // need other information about the application, like the ABI and what not ?
7510                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7511                mInstrumentation.put(a.getComponentName(), a);
7512                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7513                    if (r == null) {
7514                        r = new StringBuilder(256);
7515                    } else {
7516                        r.append(' ');
7517                    }
7518                    r.append(a.info.name);
7519                }
7520            }
7521            if (r != null) {
7522                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7523            }
7524
7525            if (pkg.protectedBroadcasts != null) {
7526                N = pkg.protectedBroadcasts.size();
7527                for (i=0; i<N; i++) {
7528                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7529                }
7530            }
7531
7532            pkgSetting.setTimeStamp(scanFileTime);
7533
7534            // Create idmap files for pairs of (packages, overlay packages).
7535            // Note: "android", ie framework-res.apk, is handled by native layers.
7536            if (pkg.mOverlayTarget != null) {
7537                // This is an overlay package.
7538                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7539                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7540                        mOverlays.put(pkg.mOverlayTarget,
7541                                new ArrayMap<String, PackageParser.Package>());
7542                    }
7543                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7544                    map.put(pkg.packageName, pkg);
7545                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7546                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7547                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7548                                "scanPackageLI failed to createIdmap");
7549                    }
7550                }
7551            } else if (mOverlays.containsKey(pkg.packageName) &&
7552                    !pkg.packageName.equals("android")) {
7553                // This is a regular package, with one or more known overlay packages.
7554                createIdmapsForPackageLI(pkg);
7555            }
7556        }
7557
7558        return pkg;
7559    }
7560
7561    /**
7562     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7563     * is derived purely on the basis of the contents of {@code scanFile} and
7564     * {@code cpuAbiOverride}.
7565     *
7566     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7567     */
7568    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7569                                 String cpuAbiOverride, boolean extractLibs)
7570            throws PackageManagerException {
7571        // TODO: We can probably be smarter about this stuff. For installed apps,
7572        // we can calculate this information at install time once and for all. For
7573        // system apps, we can probably assume that this information doesn't change
7574        // after the first boot scan. As things stand, we do lots of unnecessary work.
7575
7576        // Give ourselves some initial paths; we'll come back for another
7577        // pass once we've determined ABI below.
7578        setNativeLibraryPaths(pkg);
7579
7580        // We would never need to extract libs for forward-locked and external packages,
7581        // since the container service will do it for us. We shouldn't attempt to
7582        // extract libs from system app when it was not updated.
7583        if (pkg.isForwardLocked() || isExternal(pkg) ||
7584            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7585            extractLibs = false;
7586        }
7587
7588        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7589        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7590
7591        NativeLibraryHelper.Handle handle = null;
7592        try {
7593            handle = NativeLibraryHelper.Handle.create(scanFile);
7594            // TODO(multiArch): This can be null for apps that didn't go through the
7595            // usual installation process. We can calculate it again, like we
7596            // do during install time.
7597            //
7598            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7599            // unnecessary.
7600            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7601
7602            // Null out the abis so that they can be recalculated.
7603            pkg.applicationInfo.primaryCpuAbi = null;
7604            pkg.applicationInfo.secondaryCpuAbi = null;
7605            if (isMultiArch(pkg.applicationInfo)) {
7606                // Warn if we've set an abiOverride for multi-lib packages..
7607                // By definition, we need to copy both 32 and 64 bit libraries for
7608                // such packages.
7609                if (pkg.cpuAbiOverride != null
7610                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7611                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7612                }
7613
7614                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7615                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7616                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7617                    if (extractLibs) {
7618                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7619                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7620                                useIsaSpecificSubdirs);
7621                    } else {
7622                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7623                    }
7624                }
7625
7626                maybeThrowExceptionForMultiArchCopy(
7627                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7628
7629                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7630                    if (extractLibs) {
7631                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7632                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7633                                useIsaSpecificSubdirs);
7634                    } else {
7635                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7636                    }
7637                }
7638
7639                maybeThrowExceptionForMultiArchCopy(
7640                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7641
7642                if (abi64 >= 0) {
7643                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7644                }
7645
7646                if (abi32 >= 0) {
7647                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7648                    if (abi64 >= 0) {
7649                        pkg.applicationInfo.secondaryCpuAbi = abi;
7650                    } else {
7651                        pkg.applicationInfo.primaryCpuAbi = abi;
7652                    }
7653                }
7654            } else {
7655                String[] abiList = (cpuAbiOverride != null) ?
7656                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7657
7658                // Enable gross and lame hacks for apps that are built with old
7659                // SDK tools. We must scan their APKs for renderscript bitcode and
7660                // not launch them if it's present. Don't bother checking on devices
7661                // that don't have 64 bit support.
7662                boolean needsRenderScriptOverride = false;
7663                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7664                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7665                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7666                    needsRenderScriptOverride = true;
7667                }
7668
7669                final int copyRet;
7670                if (extractLibs) {
7671                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7672                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7673                } else {
7674                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7675                }
7676
7677                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7678                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7679                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7680                }
7681
7682                if (copyRet >= 0) {
7683                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7684                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7685                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7686                } else if (needsRenderScriptOverride) {
7687                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7688                }
7689            }
7690        } catch (IOException ioe) {
7691            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7692        } finally {
7693            IoUtils.closeQuietly(handle);
7694        }
7695
7696        // Now that we've calculated the ABIs and determined if it's an internal app,
7697        // we will go ahead and populate the nativeLibraryPath.
7698        setNativeLibraryPaths(pkg);
7699    }
7700
7701    /**
7702     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7703     * i.e, so that all packages can be run inside a single process if required.
7704     *
7705     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7706     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7707     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7708     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7709     * updating a package that belongs to a shared user.
7710     *
7711     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7712     * adds unnecessary complexity.
7713     */
7714    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7715            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7716        String requiredInstructionSet = null;
7717        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7718            requiredInstructionSet = VMRuntime.getInstructionSet(
7719                     scannedPackage.applicationInfo.primaryCpuAbi);
7720        }
7721
7722        PackageSetting requirer = null;
7723        for (PackageSetting ps : packagesForUser) {
7724            // If packagesForUser contains scannedPackage, we skip it. This will happen
7725            // when scannedPackage is an update of an existing package. Without this check,
7726            // we will never be able to change the ABI of any package belonging to a shared
7727            // user, even if it's compatible with other packages.
7728            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7729                if (ps.primaryCpuAbiString == null) {
7730                    continue;
7731                }
7732
7733                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7734                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7735                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7736                    // this but there's not much we can do.
7737                    String errorMessage = "Instruction set mismatch, "
7738                            + ((requirer == null) ? "[caller]" : requirer)
7739                            + " requires " + requiredInstructionSet + " whereas " + ps
7740                            + " requires " + instructionSet;
7741                    Slog.w(TAG, errorMessage);
7742                }
7743
7744                if (requiredInstructionSet == null) {
7745                    requiredInstructionSet = instructionSet;
7746                    requirer = ps;
7747                }
7748            }
7749        }
7750
7751        if (requiredInstructionSet != null) {
7752            String adjustedAbi;
7753            if (requirer != null) {
7754                // requirer != null implies that either scannedPackage was null or that scannedPackage
7755                // did not require an ABI, in which case we have to adjust scannedPackage to match
7756                // the ABI of the set (which is the same as requirer's ABI)
7757                adjustedAbi = requirer.primaryCpuAbiString;
7758                if (scannedPackage != null) {
7759                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7760                }
7761            } else {
7762                // requirer == null implies that we're updating all ABIs in the set to
7763                // match scannedPackage.
7764                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7765            }
7766
7767            for (PackageSetting ps : packagesForUser) {
7768                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7769                    if (ps.primaryCpuAbiString != null) {
7770                        continue;
7771                    }
7772
7773                    ps.primaryCpuAbiString = adjustedAbi;
7774                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7775                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7776                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7777
7778                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7779                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7780                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7781                            ps.primaryCpuAbiString = null;
7782                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7783                            return;
7784                        } else {
7785                            mInstaller.rmdex(ps.codePathString,
7786                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7787                        }
7788                    }
7789                }
7790            }
7791        }
7792    }
7793
7794    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7795        synchronized (mPackages) {
7796            mResolverReplaced = true;
7797            // Set up information for custom user intent resolution activity.
7798            mResolveActivity.applicationInfo = pkg.applicationInfo;
7799            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7800            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7801            mResolveActivity.processName = pkg.applicationInfo.packageName;
7802            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7803            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7804                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7805            mResolveActivity.theme = 0;
7806            mResolveActivity.exported = true;
7807            mResolveActivity.enabled = true;
7808            mResolveInfo.activityInfo = mResolveActivity;
7809            mResolveInfo.priority = 0;
7810            mResolveInfo.preferredOrder = 0;
7811            mResolveInfo.match = 0;
7812            mResolveComponentName = mCustomResolverComponentName;
7813            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7814                    mResolveComponentName);
7815        }
7816    }
7817
7818    private static String calculateBundledApkRoot(final String codePathString) {
7819        final File codePath = new File(codePathString);
7820        final File codeRoot;
7821        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7822            codeRoot = Environment.getRootDirectory();
7823        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7824            codeRoot = Environment.getOemDirectory();
7825        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7826            codeRoot = Environment.getVendorDirectory();
7827        } else {
7828            // Unrecognized code path; take its top real segment as the apk root:
7829            // e.g. /something/app/blah.apk => /something
7830            try {
7831                File f = codePath.getCanonicalFile();
7832                File parent = f.getParentFile();    // non-null because codePath is a file
7833                File tmp;
7834                while ((tmp = parent.getParentFile()) != null) {
7835                    f = parent;
7836                    parent = tmp;
7837                }
7838                codeRoot = f;
7839                Slog.w(TAG, "Unrecognized code path "
7840                        + codePath + " - using " + codeRoot);
7841            } catch (IOException e) {
7842                // Can't canonicalize the code path -- shenanigans?
7843                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7844                return Environment.getRootDirectory().getPath();
7845            }
7846        }
7847        return codeRoot.getPath();
7848    }
7849
7850    /**
7851     * Derive and set the location of native libraries for the given package,
7852     * which varies depending on where and how the package was installed.
7853     */
7854    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7855        final ApplicationInfo info = pkg.applicationInfo;
7856        final String codePath = pkg.codePath;
7857        final File codeFile = new File(codePath);
7858        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7859        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7860
7861        info.nativeLibraryRootDir = null;
7862        info.nativeLibraryRootRequiresIsa = false;
7863        info.nativeLibraryDir = null;
7864        info.secondaryNativeLibraryDir = null;
7865
7866        if (isApkFile(codeFile)) {
7867            // Monolithic install
7868            if (bundledApp) {
7869                // If "/system/lib64/apkname" exists, assume that is the per-package
7870                // native library directory to use; otherwise use "/system/lib/apkname".
7871                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7872                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7873                        getPrimaryInstructionSet(info));
7874
7875                // This is a bundled system app so choose the path based on the ABI.
7876                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7877                // is just the default path.
7878                final String apkName = deriveCodePathName(codePath);
7879                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7880                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7881                        apkName).getAbsolutePath();
7882
7883                if (info.secondaryCpuAbi != null) {
7884                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7885                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7886                            secondaryLibDir, apkName).getAbsolutePath();
7887                }
7888            } else if (asecApp) {
7889                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7890                        .getAbsolutePath();
7891            } else {
7892                final String apkName = deriveCodePathName(codePath);
7893                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7894                        .getAbsolutePath();
7895            }
7896
7897            info.nativeLibraryRootRequiresIsa = false;
7898            info.nativeLibraryDir = info.nativeLibraryRootDir;
7899        } else {
7900            // Cluster install
7901            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7902            info.nativeLibraryRootRequiresIsa = true;
7903
7904            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7905                    getPrimaryInstructionSet(info)).getAbsolutePath();
7906
7907            if (info.secondaryCpuAbi != null) {
7908                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7909                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7910            }
7911        }
7912    }
7913
7914    /**
7915     * Calculate the abis and roots for a bundled app. These can uniquely
7916     * be determined from the contents of the system partition, i.e whether
7917     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7918     * of this information, and instead assume that the system was built
7919     * sensibly.
7920     */
7921    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7922                                           PackageSetting pkgSetting) {
7923        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7924
7925        // If "/system/lib64/apkname" exists, assume that is the per-package
7926        // native library directory to use; otherwise use "/system/lib/apkname".
7927        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7928        setBundledAppAbi(pkg, apkRoot, apkName);
7929        // pkgSetting might be null during rescan following uninstall of updates
7930        // to a bundled app, so accommodate that possibility.  The settings in
7931        // that case will be established later from the parsed package.
7932        //
7933        // If the settings aren't null, sync them up with what we've just derived.
7934        // note that apkRoot isn't stored in the package settings.
7935        if (pkgSetting != null) {
7936            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7937            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7938        }
7939    }
7940
7941    /**
7942     * Deduces the ABI of a bundled app and sets the relevant fields on the
7943     * parsed pkg object.
7944     *
7945     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7946     *        under which system libraries are installed.
7947     * @param apkName the name of the installed package.
7948     */
7949    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7950        final File codeFile = new File(pkg.codePath);
7951
7952        final boolean has64BitLibs;
7953        final boolean has32BitLibs;
7954        if (isApkFile(codeFile)) {
7955            // Monolithic install
7956            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7957            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7958        } else {
7959            // Cluster install
7960            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7961            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7962                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7963                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7964                has64BitLibs = (new File(rootDir, isa)).exists();
7965            } else {
7966                has64BitLibs = false;
7967            }
7968            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7969                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7970                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7971                has32BitLibs = (new File(rootDir, isa)).exists();
7972            } else {
7973                has32BitLibs = false;
7974            }
7975        }
7976
7977        if (has64BitLibs && !has32BitLibs) {
7978            // The package has 64 bit libs, but not 32 bit libs. Its primary
7979            // ABI should be 64 bit. We can safely assume here that the bundled
7980            // native libraries correspond to the most preferred ABI in the list.
7981
7982            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7983            pkg.applicationInfo.secondaryCpuAbi = null;
7984        } else if (has32BitLibs && !has64BitLibs) {
7985            // The package has 32 bit libs but not 64 bit libs. Its primary
7986            // ABI should be 32 bit.
7987
7988            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7989            pkg.applicationInfo.secondaryCpuAbi = null;
7990        } else if (has32BitLibs && has64BitLibs) {
7991            // The application has both 64 and 32 bit bundled libraries. We check
7992            // here that the app declares multiArch support, and warn if it doesn't.
7993            //
7994            // We will be lenient here and record both ABIs. The primary will be the
7995            // ABI that's higher on the list, i.e, a device that's configured to prefer
7996            // 64 bit apps will see a 64 bit primary ABI,
7997
7998            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7999                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8000            }
8001
8002            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8003                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8004                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8005            } else {
8006                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8007                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8008            }
8009        } else {
8010            pkg.applicationInfo.primaryCpuAbi = null;
8011            pkg.applicationInfo.secondaryCpuAbi = null;
8012        }
8013    }
8014
8015    private void killApplication(String pkgName, int appId, String reason) {
8016        // Request the ActivityManager to kill the process(only for existing packages)
8017        // so that we do not end up in a confused state while the user is still using the older
8018        // version of the application while the new one gets installed.
8019        IActivityManager am = ActivityManagerNative.getDefault();
8020        if (am != null) {
8021            try {
8022                am.killApplicationWithAppId(pkgName, appId, reason);
8023            } catch (RemoteException e) {
8024            }
8025        }
8026    }
8027
8028    void removePackageLI(PackageSetting ps, boolean chatty) {
8029        if (DEBUG_INSTALL) {
8030            if (chatty)
8031                Log.d(TAG, "Removing package " + ps.name);
8032        }
8033
8034        // writer
8035        synchronized (mPackages) {
8036            mPackages.remove(ps.name);
8037            final PackageParser.Package pkg = ps.pkg;
8038            if (pkg != null) {
8039                cleanPackageDataStructuresLILPw(pkg, chatty);
8040            }
8041        }
8042    }
8043
8044    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8045        if (DEBUG_INSTALL) {
8046            if (chatty)
8047                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8048        }
8049
8050        // writer
8051        synchronized (mPackages) {
8052            mPackages.remove(pkg.applicationInfo.packageName);
8053            cleanPackageDataStructuresLILPw(pkg, chatty);
8054        }
8055    }
8056
8057    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8058        int N = pkg.providers.size();
8059        StringBuilder r = null;
8060        int i;
8061        for (i=0; i<N; i++) {
8062            PackageParser.Provider p = pkg.providers.get(i);
8063            mProviders.removeProvider(p);
8064            if (p.info.authority == null) {
8065
8066                /* There was another ContentProvider with this authority when
8067                 * this app was installed so this authority is null,
8068                 * Ignore it as we don't have to unregister the provider.
8069                 */
8070                continue;
8071            }
8072            String names[] = p.info.authority.split(";");
8073            for (int j = 0; j < names.length; j++) {
8074                if (mProvidersByAuthority.get(names[j]) == p) {
8075                    mProvidersByAuthority.remove(names[j]);
8076                    if (DEBUG_REMOVE) {
8077                        if (chatty)
8078                            Log.d(TAG, "Unregistered content provider: " + names[j]
8079                                    + ", className = " + p.info.name + ", isSyncable = "
8080                                    + p.info.isSyncable);
8081                    }
8082                }
8083            }
8084            if (DEBUG_REMOVE && chatty) {
8085                if (r == null) {
8086                    r = new StringBuilder(256);
8087                } else {
8088                    r.append(' ');
8089                }
8090                r.append(p.info.name);
8091            }
8092        }
8093        if (r != null) {
8094            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8095        }
8096
8097        N = pkg.services.size();
8098        r = null;
8099        for (i=0; i<N; i++) {
8100            PackageParser.Service s = pkg.services.get(i);
8101            mServices.removeService(s);
8102            if (chatty) {
8103                if (r == null) {
8104                    r = new StringBuilder(256);
8105                } else {
8106                    r.append(' ');
8107                }
8108                r.append(s.info.name);
8109            }
8110        }
8111        if (r != null) {
8112            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8113        }
8114
8115        N = pkg.receivers.size();
8116        r = null;
8117        for (i=0; i<N; i++) {
8118            PackageParser.Activity a = pkg.receivers.get(i);
8119            mReceivers.removeActivity(a, "receiver");
8120            if (DEBUG_REMOVE && chatty) {
8121                if (r == null) {
8122                    r = new StringBuilder(256);
8123                } else {
8124                    r.append(' ');
8125                }
8126                r.append(a.info.name);
8127            }
8128        }
8129        if (r != null) {
8130            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8131        }
8132
8133        N = pkg.activities.size();
8134        r = null;
8135        for (i=0; i<N; i++) {
8136            PackageParser.Activity a = pkg.activities.get(i);
8137            mActivities.removeActivity(a, "activity");
8138            if (DEBUG_REMOVE && chatty) {
8139                if (r == null) {
8140                    r = new StringBuilder(256);
8141                } else {
8142                    r.append(' ');
8143                }
8144                r.append(a.info.name);
8145            }
8146        }
8147        if (r != null) {
8148            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8149        }
8150
8151        N = pkg.permissions.size();
8152        r = null;
8153        for (i=0; i<N; i++) {
8154            PackageParser.Permission p = pkg.permissions.get(i);
8155            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8156            if (bp == null) {
8157                bp = mSettings.mPermissionTrees.get(p.info.name);
8158            }
8159            if (bp != null && bp.perm == p) {
8160                bp.perm = null;
8161                if (DEBUG_REMOVE && chatty) {
8162                    if (r == null) {
8163                        r = new StringBuilder(256);
8164                    } else {
8165                        r.append(' ');
8166                    }
8167                    r.append(p.info.name);
8168                }
8169            }
8170            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8171                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8172                if (appOpPerms != null) {
8173                    appOpPerms.remove(pkg.packageName);
8174                }
8175            }
8176        }
8177        if (r != null) {
8178            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8179        }
8180
8181        N = pkg.requestedPermissions.size();
8182        r = null;
8183        for (i=0; i<N; i++) {
8184            String perm = pkg.requestedPermissions.get(i);
8185            BasePermission bp = mSettings.mPermissions.get(perm);
8186            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8187                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8188                if (appOpPerms != null) {
8189                    appOpPerms.remove(pkg.packageName);
8190                    if (appOpPerms.isEmpty()) {
8191                        mAppOpPermissionPackages.remove(perm);
8192                    }
8193                }
8194            }
8195        }
8196        if (r != null) {
8197            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8198        }
8199
8200        N = pkg.instrumentation.size();
8201        r = null;
8202        for (i=0; i<N; i++) {
8203            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8204            mInstrumentation.remove(a.getComponentName());
8205            if (DEBUG_REMOVE && chatty) {
8206                if (r == null) {
8207                    r = new StringBuilder(256);
8208                } else {
8209                    r.append(' ');
8210                }
8211                r.append(a.info.name);
8212            }
8213        }
8214        if (r != null) {
8215            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8216        }
8217
8218        r = null;
8219        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8220            // Only system apps can hold shared libraries.
8221            if (pkg.libraryNames != null) {
8222                for (i=0; i<pkg.libraryNames.size(); i++) {
8223                    String name = pkg.libraryNames.get(i);
8224                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8225                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8226                        mSharedLibraries.remove(name);
8227                        if (DEBUG_REMOVE && chatty) {
8228                            if (r == null) {
8229                                r = new StringBuilder(256);
8230                            } else {
8231                                r.append(' ');
8232                            }
8233                            r.append(name);
8234                        }
8235                    }
8236                }
8237            }
8238        }
8239        if (r != null) {
8240            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8241        }
8242    }
8243
8244    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8245        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8246            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8247                return true;
8248            }
8249        }
8250        return false;
8251    }
8252
8253    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8254    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8255    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8256
8257    private void updatePermissionsLPw(String changingPkg,
8258            PackageParser.Package pkgInfo, int flags) {
8259        // Make sure there are no dangling permission trees.
8260        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8261        while (it.hasNext()) {
8262            final BasePermission bp = it.next();
8263            if (bp.packageSetting == null) {
8264                // We may not yet have parsed the package, so just see if
8265                // we still know about its settings.
8266                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8267            }
8268            if (bp.packageSetting == null) {
8269                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8270                        + " from package " + bp.sourcePackage);
8271                it.remove();
8272            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8273                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8274                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8275                            + " from package " + bp.sourcePackage);
8276                    flags |= UPDATE_PERMISSIONS_ALL;
8277                    it.remove();
8278                }
8279            }
8280        }
8281
8282        // Make sure all dynamic permissions have been assigned to a package,
8283        // and make sure there are no dangling permissions.
8284        it = mSettings.mPermissions.values().iterator();
8285        while (it.hasNext()) {
8286            final BasePermission bp = it.next();
8287            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8288                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8289                        + bp.name + " pkg=" + bp.sourcePackage
8290                        + " info=" + bp.pendingInfo);
8291                if (bp.packageSetting == null && bp.pendingInfo != null) {
8292                    final BasePermission tree = findPermissionTreeLP(bp.name);
8293                    if (tree != null && tree.perm != null) {
8294                        bp.packageSetting = tree.packageSetting;
8295                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8296                                new PermissionInfo(bp.pendingInfo));
8297                        bp.perm.info.packageName = tree.perm.info.packageName;
8298                        bp.perm.info.name = bp.name;
8299                        bp.uid = tree.uid;
8300                    }
8301                }
8302            }
8303            if (bp.packageSetting == null) {
8304                // We may not yet have parsed the package, so just see if
8305                // we still know about its settings.
8306                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8307            }
8308            if (bp.packageSetting == null) {
8309                Slog.w(TAG, "Removing dangling permission: " + bp.name
8310                        + " from package " + bp.sourcePackage);
8311                it.remove();
8312            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8313                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8314                    Slog.i(TAG, "Removing old permission: " + bp.name
8315                            + " from package " + bp.sourcePackage);
8316                    flags |= UPDATE_PERMISSIONS_ALL;
8317                    it.remove();
8318                }
8319            }
8320        }
8321
8322        // Now update the permissions for all packages, in particular
8323        // replace the granted permissions of the system packages.
8324        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8325            for (PackageParser.Package pkg : mPackages.values()) {
8326                if (pkg != pkgInfo) {
8327                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8328                            changingPkg);
8329                }
8330            }
8331        }
8332
8333        if (pkgInfo != null) {
8334            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8335        }
8336    }
8337
8338    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8339            String packageOfInterest) {
8340        // IMPORTANT: There are two types of permissions: install and runtime.
8341        // Install time permissions are granted when the app is installed to
8342        // all device users and users added in the future. Runtime permissions
8343        // are granted at runtime explicitly to specific users. Normal and signature
8344        // protected permissions are install time permissions. Dangerous permissions
8345        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8346        // otherwise they are runtime permissions. This function does not manage
8347        // runtime permissions except for the case an app targeting Lollipop MR1
8348        // being upgraded to target a newer SDK, in which case dangerous permissions
8349        // are transformed from install time to runtime ones.
8350
8351        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8352        if (ps == null) {
8353            return;
8354        }
8355
8356        PermissionsState permissionsState = ps.getPermissionsState();
8357        PermissionsState origPermissions = permissionsState;
8358
8359        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8360
8361        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8362
8363        boolean changedInstallPermission = false;
8364
8365        if (replace) {
8366            ps.installPermissionsFixed = false;
8367            if (!ps.isSharedUser()) {
8368                origPermissions = new PermissionsState(permissionsState);
8369                permissionsState.reset();
8370            }
8371        }
8372
8373        permissionsState.setGlobalGids(mGlobalGids);
8374
8375        final int N = pkg.requestedPermissions.size();
8376        for (int i=0; i<N; i++) {
8377            final String name = pkg.requestedPermissions.get(i);
8378            final BasePermission bp = mSettings.mPermissions.get(name);
8379
8380            if (DEBUG_INSTALL) {
8381                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8382            }
8383
8384            if (bp == null || bp.packageSetting == null) {
8385                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8386                    Slog.w(TAG, "Unknown permission " + name
8387                            + " in package " + pkg.packageName);
8388                }
8389                continue;
8390            }
8391
8392            final String perm = bp.name;
8393            boolean allowedSig = false;
8394            int grant = GRANT_DENIED;
8395
8396            // Keep track of app op permissions.
8397            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8398                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8399                if (pkgs == null) {
8400                    pkgs = new ArraySet<>();
8401                    mAppOpPermissionPackages.put(bp.name, pkgs);
8402                }
8403                pkgs.add(pkg.packageName);
8404            }
8405
8406            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8407            switch (level) {
8408                case PermissionInfo.PROTECTION_NORMAL: {
8409                    // For all apps normal permissions are install time ones.
8410                    grant = GRANT_INSTALL;
8411                } break;
8412
8413                case PermissionInfo.PROTECTION_DANGEROUS: {
8414                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8415                        // For legacy apps dangerous permissions are install time ones.
8416                        grant = GRANT_INSTALL_LEGACY;
8417                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8418                        // For legacy apps that became modern, install becomes runtime.
8419                        grant = GRANT_UPGRADE;
8420                    } else if (mPromoteSystemApps
8421                            && isSystemApp(ps)
8422                            && mExistingSystemPackages.contains(ps.name)) {
8423                        // For legacy system apps, install becomes runtime.
8424                        // We cannot check hasInstallPermission() for system apps since those
8425                        // permissions were granted implicitly and not persisted pre-M.
8426                        grant = GRANT_UPGRADE;
8427                    } else {
8428                        // For modern apps keep runtime permissions unchanged.
8429                        grant = GRANT_RUNTIME;
8430                    }
8431                } break;
8432
8433                case PermissionInfo.PROTECTION_SIGNATURE: {
8434                    // For all apps signature permissions are install time ones.
8435                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8436                    if (allowedSig) {
8437                        grant = GRANT_INSTALL;
8438                    }
8439                } break;
8440            }
8441
8442            if (DEBUG_INSTALL) {
8443                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8444            }
8445
8446            if (grant != GRANT_DENIED) {
8447                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8448                    // If this is an existing, non-system package, then
8449                    // we can't add any new permissions to it.
8450                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8451                        // Except...  if this is a permission that was added
8452                        // to the platform (note: need to only do this when
8453                        // updating the platform).
8454                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8455                            grant = GRANT_DENIED;
8456                        }
8457                    }
8458                }
8459
8460                switch (grant) {
8461                    case GRANT_INSTALL: {
8462                        // Revoke this as runtime permission to handle the case of
8463                        // a runtime permission being downgraded to an install one.
8464                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8465                            if (origPermissions.getRuntimePermissionState(
8466                                    bp.name, userId) != null) {
8467                                // Revoke the runtime permission and clear the flags.
8468                                origPermissions.revokeRuntimePermission(bp, userId);
8469                                origPermissions.updatePermissionFlags(bp, userId,
8470                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8471                                // If we revoked a permission permission, we have to write.
8472                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8473                                        changedRuntimePermissionUserIds, userId);
8474                            }
8475                        }
8476                        // Grant an install permission.
8477                        if (permissionsState.grantInstallPermission(bp) !=
8478                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8479                            changedInstallPermission = true;
8480                        }
8481                    } break;
8482
8483                    case GRANT_INSTALL_LEGACY: {
8484                        // Grant an install permission.
8485                        if (permissionsState.grantInstallPermission(bp) !=
8486                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8487                            changedInstallPermission = true;
8488                        }
8489                    } break;
8490
8491                    case GRANT_RUNTIME: {
8492                        // Grant previously granted runtime permissions.
8493                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8494                            PermissionState permissionState = origPermissions
8495                                    .getRuntimePermissionState(bp.name, userId);
8496                            final int flags = permissionState != null
8497                                    ? permissionState.getFlags() : 0;
8498                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8499                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8500                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8501                                    // If we cannot put the permission as it was, we have to write.
8502                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8503                                            changedRuntimePermissionUserIds, userId);
8504                                }
8505                            }
8506                            // Propagate the permission flags.
8507                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8508                        }
8509                    } break;
8510
8511                    case GRANT_UPGRADE: {
8512                        // Grant runtime permissions for a previously held install permission.
8513                        PermissionState permissionState = origPermissions
8514                                .getInstallPermissionState(bp.name);
8515                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8516
8517                        if (origPermissions.revokeInstallPermission(bp)
8518                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8519                            // We will be transferring the permission flags, so clear them.
8520                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8521                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8522                            changedInstallPermission = true;
8523                        }
8524
8525                        // If the permission is not to be promoted to runtime we ignore it and
8526                        // also its other flags as they are not applicable to install permissions.
8527                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8528                            for (int userId : currentUserIds) {
8529                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8530                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8531                                    // Transfer the permission flags.
8532                                    permissionsState.updatePermissionFlags(bp, userId,
8533                                            flags, flags);
8534                                    // If we granted the permission, we have to write.
8535                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8536                                            changedRuntimePermissionUserIds, userId);
8537                                }
8538                            }
8539                        }
8540                    } break;
8541
8542                    default: {
8543                        if (packageOfInterest == null
8544                                || packageOfInterest.equals(pkg.packageName)) {
8545                            Slog.w(TAG, "Not granting permission " + perm
8546                                    + " to package " + pkg.packageName
8547                                    + " because it was previously installed without");
8548                        }
8549                    } break;
8550                }
8551            } else {
8552                if (permissionsState.revokeInstallPermission(bp) !=
8553                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8554                    // Also drop the permission flags.
8555                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8556                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8557                    changedInstallPermission = true;
8558                    Slog.i(TAG, "Un-granting permission " + perm
8559                            + " from package " + pkg.packageName
8560                            + " (protectionLevel=" + bp.protectionLevel
8561                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8562                            + ")");
8563                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8564                    // Don't print warning for app op permissions, since it is fine for them
8565                    // not to be granted, there is a UI for the user to decide.
8566                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8567                        Slog.w(TAG, "Not granting permission " + perm
8568                                + " to package " + pkg.packageName
8569                                + " (protectionLevel=" + bp.protectionLevel
8570                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8571                                + ")");
8572                    }
8573                }
8574            }
8575        }
8576
8577        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8578                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8579            // This is the first that we have heard about this package, so the
8580            // permissions we have now selected are fixed until explicitly
8581            // changed.
8582            ps.installPermissionsFixed = true;
8583        }
8584
8585        // Persist the runtime permissions state for users with changes.
8586        for (int userId : changedRuntimePermissionUserIds) {
8587            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8588        }
8589    }
8590
8591    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8592        boolean allowed = false;
8593        final int NP = PackageParser.NEW_PERMISSIONS.length;
8594        for (int ip=0; ip<NP; ip++) {
8595            final PackageParser.NewPermissionInfo npi
8596                    = PackageParser.NEW_PERMISSIONS[ip];
8597            if (npi.name.equals(perm)
8598                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8599                allowed = true;
8600                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8601                        + pkg.packageName);
8602                break;
8603            }
8604        }
8605        return allowed;
8606    }
8607
8608    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8609            BasePermission bp, PermissionsState origPermissions) {
8610        boolean allowed;
8611        allowed = (compareSignatures(
8612                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8613                        == PackageManager.SIGNATURE_MATCH)
8614                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8615                        == PackageManager.SIGNATURE_MATCH);
8616        if (!allowed && (bp.protectionLevel
8617                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8618            if (isSystemApp(pkg)) {
8619                // For updated system applications, a system permission
8620                // is granted only if it had been defined by the original application.
8621                if (pkg.isUpdatedSystemApp()) {
8622                    final PackageSetting sysPs = mSettings
8623                            .getDisabledSystemPkgLPr(pkg.packageName);
8624                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8625                        // If the original was granted this permission, we take
8626                        // that grant decision as read and propagate it to the
8627                        // update.
8628                        if (sysPs.isPrivileged()) {
8629                            allowed = true;
8630                        }
8631                    } else {
8632                        // The system apk may have been updated with an older
8633                        // version of the one on the data partition, but which
8634                        // granted a new system permission that it didn't have
8635                        // before.  In this case we do want to allow the app to
8636                        // now get the new permission if the ancestral apk is
8637                        // privileged to get it.
8638                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8639                            for (int j=0;
8640                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8641                                if (perm.equals(
8642                                        sysPs.pkg.requestedPermissions.get(j))) {
8643                                    allowed = true;
8644                                    break;
8645                                }
8646                            }
8647                        }
8648                    }
8649                } else {
8650                    allowed = isPrivilegedApp(pkg);
8651                }
8652            }
8653        }
8654        if (!allowed) {
8655            if (!allowed && (bp.protectionLevel
8656                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8657                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8658                // If this was a previously normal/dangerous permission that got moved
8659                // to a system permission as part of the runtime permission redesign, then
8660                // we still want to blindly grant it to old apps.
8661                allowed = true;
8662            }
8663            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8664                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8665                // If this permission is to be granted to the system installer and
8666                // this app is an installer, then it gets the permission.
8667                allowed = true;
8668            }
8669            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8670                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8671                // If this permission is to be granted to the system verifier and
8672                // this app is a verifier, then it gets the permission.
8673                allowed = true;
8674            }
8675            if (!allowed && (bp.protectionLevel
8676                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8677                    && isSystemApp(pkg)) {
8678                // Any pre-installed system app is allowed to get this permission.
8679                allowed = true;
8680            }
8681            if (!allowed && (bp.protectionLevel
8682                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8683                // For development permissions, a development permission
8684                // is granted only if it was already granted.
8685                allowed = origPermissions.hasInstallPermission(perm);
8686            }
8687        }
8688        return allowed;
8689    }
8690
8691    final class ActivityIntentResolver
8692            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8693        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8694                boolean defaultOnly, int userId) {
8695            if (!sUserManager.exists(userId)) return null;
8696            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8697            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8698        }
8699
8700        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8701                int userId) {
8702            if (!sUserManager.exists(userId)) return null;
8703            mFlags = flags;
8704            return super.queryIntent(intent, resolvedType,
8705                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8706        }
8707
8708        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8709                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8710            if (!sUserManager.exists(userId)) return null;
8711            if (packageActivities == null) {
8712                return null;
8713            }
8714            mFlags = flags;
8715            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8716            final int N = packageActivities.size();
8717            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8718                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8719
8720            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8721            for (int i = 0; i < N; ++i) {
8722                intentFilters = packageActivities.get(i).intents;
8723                if (intentFilters != null && intentFilters.size() > 0) {
8724                    PackageParser.ActivityIntentInfo[] array =
8725                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8726                    intentFilters.toArray(array);
8727                    listCut.add(array);
8728                }
8729            }
8730            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8731        }
8732
8733        public final void addActivity(PackageParser.Activity a, String type) {
8734            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8735            mActivities.put(a.getComponentName(), a);
8736            if (DEBUG_SHOW_INFO)
8737                Log.v(
8738                TAG, "  " + type + " " +
8739                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8740            if (DEBUG_SHOW_INFO)
8741                Log.v(TAG, "    Class=" + a.info.name);
8742            final int NI = a.intents.size();
8743            for (int j=0; j<NI; j++) {
8744                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8745                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8746                    intent.setPriority(0);
8747                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8748                            + a.className + " with priority > 0, forcing to 0");
8749                }
8750                if (DEBUG_SHOW_INFO) {
8751                    Log.v(TAG, "    IntentFilter:");
8752                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8753                }
8754                if (!intent.debugCheck()) {
8755                    Log.w(TAG, "==> For Activity " + a.info.name);
8756                }
8757                addFilter(intent);
8758            }
8759        }
8760
8761        public final void removeActivity(PackageParser.Activity a, String type) {
8762            mActivities.remove(a.getComponentName());
8763            if (DEBUG_SHOW_INFO) {
8764                Log.v(TAG, "  " + type + " "
8765                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8766                                : a.info.name) + ":");
8767                Log.v(TAG, "    Class=" + a.info.name);
8768            }
8769            final int NI = a.intents.size();
8770            for (int j=0; j<NI; j++) {
8771                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8772                if (DEBUG_SHOW_INFO) {
8773                    Log.v(TAG, "    IntentFilter:");
8774                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8775                }
8776                removeFilter(intent);
8777            }
8778        }
8779
8780        @Override
8781        protected boolean allowFilterResult(
8782                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8783            ActivityInfo filterAi = filter.activity.info;
8784            for (int i=dest.size()-1; i>=0; i--) {
8785                ActivityInfo destAi = dest.get(i).activityInfo;
8786                if (destAi.name == filterAi.name
8787                        && destAi.packageName == filterAi.packageName) {
8788                    return false;
8789                }
8790            }
8791            return true;
8792        }
8793
8794        @Override
8795        protected ActivityIntentInfo[] newArray(int size) {
8796            return new ActivityIntentInfo[size];
8797        }
8798
8799        @Override
8800        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8801            if (!sUserManager.exists(userId)) return true;
8802            PackageParser.Package p = filter.activity.owner;
8803            if (p != null) {
8804                PackageSetting ps = (PackageSetting)p.mExtras;
8805                if (ps != null) {
8806                    // System apps are never considered stopped for purposes of
8807                    // filtering, because there may be no way for the user to
8808                    // actually re-launch them.
8809                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8810                            && ps.getStopped(userId);
8811                }
8812            }
8813            return false;
8814        }
8815
8816        @Override
8817        protected boolean isPackageForFilter(String packageName,
8818                PackageParser.ActivityIntentInfo info) {
8819            return packageName.equals(info.activity.owner.packageName);
8820        }
8821
8822        @Override
8823        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8824                int match, int userId) {
8825            if (!sUserManager.exists(userId)) return null;
8826            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8827                return null;
8828            }
8829            final PackageParser.Activity activity = info.activity;
8830            if (mSafeMode && (activity.info.applicationInfo.flags
8831                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8832                return null;
8833            }
8834            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8835            if (ps == null) {
8836                return null;
8837            }
8838            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8839                    ps.readUserState(userId), userId);
8840            if (ai == null) {
8841                return null;
8842            }
8843            final ResolveInfo res = new ResolveInfo();
8844            res.activityInfo = ai;
8845            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8846                res.filter = info;
8847            }
8848            if (info != null) {
8849                res.handleAllWebDataURI = info.handleAllWebDataURI();
8850            }
8851            res.priority = info.getPriority();
8852            res.preferredOrder = activity.owner.mPreferredOrder;
8853            //System.out.println("Result: " + res.activityInfo.className +
8854            //                   " = " + res.priority);
8855            res.match = match;
8856            res.isDefault = info.hasDefault;
8857            res.labelRes = info.labelRes;
8858            res.nonLocalizedLabel = info.nonLocalizedLabel;
8859            if (userNeedsBadging(userId)) {
8860                res.noResourceId = true;
8861            } else {
8862                res.icon = info.icon;
8863            }
8864            res.iconResourceId = info.icon;
8865            res.system = res.activityInfo.applicationInfo.isSystemApp();
8866            return res;
8867        }
8868
8869        @Override
8870        protected void sortResults(List<ResolveInfo> results) {
8871            Collections.sort(results, mResolvePrioritySorter);
8872        }
8873
8874        @Override
8875        protected void dumpFilter(PrintWriter out, String prefix,
8876                PackageParser.ActivityIntentInfo filter) {
8877            out.print(prefix); out.print(
8878                    Integer.toHexString(System.identityHashCode(filter.activity)));
8879                    out.print(' ');
8880                    filter.activity.printComponentShortName(out);
8881                    out.print(" filter ");
8882                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8883        }
8884
8885        @Override
8886        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8887            return filter.activity;
8888        }
8889
8890        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8891            PackageParser.Activity activity = (PackageParser.Activity)label;
8892            out.print(prefix); out.print(
8893                    Integer.toHexString(System.identityHashCode(activity)));
8894                    out.print(' ');
8895                    activity.printComponentShortName(out);
8896            if (count > 1) {
8897                out.print(" ("); out.print(count); out.print(" filters)");
8898            }
8899            out.println();
8900        }
8901
8902//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8903//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8904//            final List<ResolveInfo> retList = Lists.newArrayList();
8905//            while (i.hasNext()) {
8906//                final ResolveInfo resolveInfo = i.next();
8907//                if (isEnabledLP(resolveInfo.activityInfo)) {
8908//                    retList.add(resolveInfo);
8909//                }
8910//            }
8911//            return retList;
8912//        }
8913
8914        // Keys are String (activity class name), values are Activity.
8915        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8916                = new ArrayMap<ComponentName, PackageParser.Activity>();
8917        private int mFlags;
8918    }
8919
8920    private final class ServiceIntentResolver
8921            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8922        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8923                boolean defaultOnly, int userId) {
8924            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8925            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8926        }
8927
8928        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8929                int userId) {
8930            if (!sUserManager.exists(userId)) return null;
8931            mFlags = flags;
8932            return super.queryIntent(intent, resolvedType,
8933                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8934        }
8935
8936        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8937                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8938            if (!sUserManager.exists(userId)) return null;
8939            if (packageServices == null) {
8940                return null;
8941            }
8942            mFlags = flags;
8943            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8944            final int N = packageServices.size();
8945            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8946                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8947
8948            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8949            for (int i = 0; i < N; ++i) {
8950                intentFilters = packageServices.get(i).intents;
8951                if (intentFilters != null && intentFilters.size() > 0) {
8952                    PackageParser.ServiceIntentInfo[] array =
8953                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8954                    intentFilters.toArray(array);
8955                    listCut.add(array);
8956                }
8957            }
8958            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8959        }
8960
8961        public final void addService(PackageParser.Service s) {
8962            mServices.put(s.getComponentName(), s);
8963            if (DEBUG_SHOW_INFO) {
8964                Log.v(TAG, "  "
8965                        + (s.info.nonLocalizedLabel != null
8966                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8967                Log.v(TAG, "    Class=" + s.info.name);
8968            }
8969            final int NI = s.intents.size();
8970            int j;
8971            for (j=0; j<NI; j++) {
8972                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8973                if (DEBUG_SHOW_INFO) {
8974                    Log.v(TAG, "    IntentFilter:");
8975                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8976                }
8977                if (!intent.debugCheck()) {
8978                    Log.w(TAG, "==> For Service " + s.info.name);
8979                }
8980                addFilter(intent);
8981            }
8982        }
8983
8984        public final void removeService(PackageParser.Service s) {
8985            mServices.remove(s.getComponentName());
8986            if (DEBUG_SHOW_INFO) {
8987                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8988                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8989                Log.v(TAG, "    Class=" + s.info.name);
8990            }
8991            final int NI = s.intents.size();
8992            int j;
8993            for (j=0; j<NI; j++) {
8994                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8995                if (DEBUG_SHOW_INFO) {
8996                    Log.v(TAG, "    IntentFilter:");
8997                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8998                }
8999                removeFilter(intent);
9000            }
9001        }
9002
9003        @Override
9004        protected boolean allowFilterResult(
9005                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9006            ServiceInfo filterSi = filter.service.info;
9007            for (int i=dest.size()-1; i>=0; i--) {
9008                ServiceInfo destAi = dest.get(i).serviceInfo;
9009                if (destAi.name == filterSi.name
9010                        && destAi.packageName == filterSi.packageName) {
9011                    return false;
9012                }
9013            }
9014            return true;
9015        }
9016
9017        @Override
9018        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9019            return new PackageParser.ServiceIntentInfo[size];
9020        }
9021
9022        @Override
9023        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9024            if (!sUserManager.exists(userId)) return true;
9025            PackageParser.Package p = filter.service.owner;
9026            if (p != null) {
9027                PackageSetting ps = (PackageSetting)p.mExtras;
9028                if (ps != null) {
9029                    // System apps are never considered stopped for purposes of
9030                    // filtering, because there may be no way for the user to
9031                    // actually re-launch them.
9032                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9033                            && ps.getStopped(userId);
9034                }
9035            }
9036            return false;
9037        }
9038
9039        @Override
9040        protected boolean isPackageForFilter(String packageName,
9041                PackageParser.ServiceIntentInfo info) {
9042            return packageName.equals(info.service.owner.packageName);
9043        }
9044
9045        @Override
9046        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9047                int match, int userId) {
9048            if (!sUserManager.exists(userId)) return null;
9049            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9050            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9051                return null;
9052            }
9053            final PackageParser.Service service = info.service;
9054            if (mSafeMode && (service.info.applicationInfo.flags
9055                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9056                return null;
9057            }
9058            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9059            if (ps == null) {
9060                return null;
9061            }
9062            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9063                    ps.readUserState(userId), userId);
9064            if (si == null) {
9065                return null;
9066            }
9067            final ResolveInfo res = new ResolveInfo();
9068            res.serviceInfo = si;
9069            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9070                res.filter = filter;
9071            }
9072            res.priority = info.getPriority();
9073            res.preferredOrder = service.owner.mPreferredOrder;
9074            res.match = match;
9075            res.isDefault = info.hasDefault;
9076            res.labelRes = info.labelRes;
9077            res.nonLocalizedLabel = info.nonLocalizedLabel;
9078            res.icon = info.icon;
9079            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9080            return res;
9081        }
9082
9083        @Override
9084        protected void sortResults(List<ResolveInfo> results) {
9085            Collections.sort(results, mResolvePrioritySorter);
9086        }
9087
9088        @Override
9089        protected void dumpFilter(PrintWriter out, String prefix,
9090                PackageParser.ServiceIntentInfo filter) {
9091            out.print(prefix); out.print(
9092                    Integer.toHexString(System.identityHashCode(filter.service)));
9093                    out.print(' ');
9094                    filter.service.printComponentShortName(out);
9095                    out.print(" filter ");
9096                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9097        }
9098
9099        @Override
9100        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9101            return filter.service;
9102        }
9103
9104        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9105            PackageParser.Service service = (PackageParser.Service)label;
9106            out.print(prefix); out.print(
9107                    Integer.toHexString(System.identityHashCode(service)));
9108                    out.print(' ');
9109                    service.printComponentShortName(out);
9110            if (count > 1) {
9111                out.print(" ("); out.print(count); out.print(" filters)");
9112            }
9113            out.println();
9114        }
9115
9116//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9117//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9118//            final List<ResolveInfo> retList = Lists.newArrayList();
9119//            while (i.hasNext()) {
9120//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9121//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9122//                    retList.add(resolveInfo);
9123//                }
9124//            }
9125//            return retList;
9126//        }
9127
9128        // Keys are String (activity class name), values are Activity.
9129        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9130                = new ArrayMap<ComponentName, PackageParser.Service>();
9131        private int mFlags;
9132    };
9133
9134    private final class ProviderIntentResolver
9135            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9136        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9137                boolean defaultOnly, int userId) {
9138            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9139            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9140        }
9141
9142        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9143                int userId) {
9144            if (!sUserManager.exists(userId))
9145                return null;
9146            mFlags = flags;
9147            return super.queryIntent(intent, resolvedType,
9148                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9149        }
9150
9151        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9152                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9153            if (!sUserManager.exists(userId))
9154                return null;
9155            if (packageProviders == null) {
9156                return null;
9157            }
9158            mFlags = flags;
9159            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9160            final int N = packageProviders.size();
9161            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9162                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9163
9164            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9165            for (int i = 0; i < N; ++i) {
9166                intentFilters = packageProviders.get(i).intents;
9167                if (intentFilters != null && intentFilters.size() > 0) {
9168                    PackageParser.ProviderIntentInfo[] array =
9169                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9170                    intentFilters.toArray(array);
9171                    listCut.add(array);
9172                }
9173            }
9174            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9175        }
9176
9177        public final void addProvider(PackageParser.Provider p) {
9178            if (mProviders.containsKey(p.getComponentName())) {
9179                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9180                return;
9181            }
9182
9183            mProviders.put(p.getComponentName(), p);
9184            if (DEBUG_SHOW_INFO) {
9185                Log.v(TAG, "  "
9186                        + (p.info.nonLocalizedLabel != null
9187                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9188                Log.v(TAG, "    Class=" + p.info.name);
9189            }
9190            final int NI = p.intents.size();
9191            int j;
9192            for (j = 0; j < NI; j++) {
9193                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9194                if (DEBUG_SHOW_INFO) {
9195                    Log.v(TAG, "    IntentFilter:");
9196                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9197                }
9198                if (!intent.debugCheck()) {
9199                    Log.w(TAG, "==> For Provider " + p.info.name);
9200                }
9201                addFilter(intent);
9202            }
9203        }
9204
9205        public final void removeProvider(PackageParser.Provider p) {
9206            mProviders.remove(p.getComponentName());
9207            if (DEBUG_SHOW_INFO) {
9208                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9209                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9210                Log.v(TAG, "    Class=" + p.info.name);
9211            }
9212            final int NI = p.intents.size();
9213            int j;
9214            for (j = 0; j < NI; j++) {
9215                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9216                if (DEBUG_SHOW_INFO) {
9217                    Log.v(TAG, "    IntentFilter:");
9218                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9219                }
9220                removeFilter(intent);
9221            }
9222        }
9223
9224        @Override
9225        protected boolean allowFilterResult(
9226                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9227            ProviderInfo filterPi = filter.provider.info;
9228            for (int i = dest.size() - 1; i >= 0; i--) {
9229                ProviderInfo destPi = dest.get(i).providerInfo;
9230                if (destPi.name == filterPi.name
9231                        && destPi.packageName == filterPi.packageName) {
9232                    return false;
9233                }
9234            }
9235            return true;
9236        }
9237
9238        @Override
9239        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9240            return new PackageParser.ProviderIntentInfo[size];
9241        }
9242
9243        @Override
9244        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9245            if (!sUserManager.exists(userId))
9246                return true;
9247            PackageParser.Package p = filter.provider.owner;
9248            if (p != null) {
9249                PackageSetting ps = (PackageSetting) p.mExtras;
9250                if (ps != null) {
9251                    // System apps are never considered stopped for purposes of
9252                    // filtering, because there may be no way for the user to
9253                    // actually re-launch them.
9254                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9255                            && ps.getStopped(userId);
9256                }
9257            }
9258            return false;
9259        }
9260
9261        @Override
9262        protected boolean isPackageForFilter(String packageName,
9263                PackageParser.ProviderIntentInfo info) {
9264            return packageName.equals(info.provider.owner.packageName);
9265        }
9266
9267        @Override
9268        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9269                int match, int userId) {
9270            if (!sUserManager.exists(userId))
9271                return null;
9272            final PackageParser.ProviderIntentInfo info = filter;
9273            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9274                return null;
9275            }
9276            final PackageParser.Provider provider = info.provider;
9277            if (mSafeMode && (provider.info.applicationInfo.flags
9278                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9279                return null;
9280            }
9281            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9282            if (ps == null) {
9283                return null;
9284            }
9285            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9286                    ps.readUserState(userId), userId);
9287            if (pi == null) {
9288                return null;
9289            }
9290            final ResolveInfo res = new ResolveInfo();
9291            res.providerInfo = pi;
9292            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9293                res.filter = filter;
9294            }
9295            res.priority = info.getPriority();
9296            res.preferredOrder = provider.owner.mPreferredOrder;
9297            res.match = match;
9298            res.isDefault = info.hasDefault;
9299            res.labelRes = info.labelRes;
9300            res.nonLocalizedLabel = info.nonLocalizedLabel;
9301            res.icon = info.icon;
9302            res.system = res.providerInfo.applicationInfo.isSystemApp();
9303            return res;
9304        }
9305
9306        @Override
9307        protected void sortResults(List<ResolveInfo> results) {
9308            Collections.sort(results, mResolvePrioritySorter);
9309        }
9310
9311        @Override
9312        protected void dumpFilter(PrintWriter out, String prefix,
9313                PackageParser.ProviderIntentInfo filter) {
9314            out.print(prefix);
9315            out.print(
9316                    Integer.toHexString(System.identityHashCode(filter.provider)));
9317            out.print(' ');
9318            filter.provider.printComponentShortName(out);
9319            out.print(" filter ");
9320            out.println(Integer.toHexString(System.identityHashCode(filter)));
9321        }
9322
9323        @Override
9324        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9325            return filter.provider;
9326        }
9327
9328        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9329            PackageParser.Provider provider = (PackageParser.Provider)label;
9330            out.print(prefix); out.print(
9331                    Integer.toHexString(System.identityHashCode(provider)));
9332                    out.print(' ');
9333                    provider.printComponentShortName(out);
9334            if (count > 1) {
9335                out.print(" ("); out.print(count); out.print(" filters)");
9336            }
9337            out.println();
9338        }
9339
9340        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9341                = new ArrayMap<ComponentName, PackageParser.Provider>();
9342        private int mFlags;
9343    };
9344
9345    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9346            new Comparator<ResolveInfo>() {
9347        public int compare(ResolveInfo r1, ResolveInfo r2) {
9348            int v1 = r1.priority;
9349            int v2 = r2.priority;
9350            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9351            if (v1 != v2) {
9352                return (v1 > v2) ? -1 : 1;
9353            }
9354            v1 = r1.preferredOrder;
9355            v2 = r2.preferredOrder;
9356            if (v1 != v2) {
9357                return (v1 > v2) ? -1 : 1;
9358            }
9359            if (r1.isDefault != r2.isDefault) {
9360                return r1.isDefault ? -1 : 1;
9361            }
9362            v1 = r1.match;
9363            v2 = r2.match;
9364            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9365            if (v1 != v2) {
9366                return (v1 > v2) ? -1 : 1;
9367            }
9368            if (r1.system != r2.system) {
9369                return r1.system ? -1 : 1;
9370            }
9371            return 0;
9372        }
9373    };
9374
9375    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9376            new Comparator<ProviderInfo>() {
9377        public int compare(ProviderInfo p1, ProviderInfo p2) {
9378            final int v1 = p1.initOrder;
9379            final int v2 = p2.initOrder;
9380            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9381        }
9382    };
9383
9384    final void sendPackageBroadcast(final String action, final String pkg,
9385            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9386            final int[] userIds) {
9387        mHandler.post(new Runnable() {
9388            @Override
9389            public void run() {
9390                try {
9391                    final IActivityManager am = ActivityManagerNative.getDefault();
9392                    if (am == null) return;
9393                    final int[] resolvedUserIds;
9394                    if (userIds == null) {
9395                        resolvedUserIds = am.getRunningUserIds();
9396                    } else {
9397                        resolvedUserIds = userIds;
9398                    }
9399                    for (int id : resolvedUserIds) {
9400                        final Intent intent = new Intent(action,
9401                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9402                        if (extras != null) {
9403                            intent.putExtras(extras);
9404                        }
9405                        if (targetPkg != null) {
9406                            intent.setPackage(targetPkg);
9407                        }
9408                        // Modify the UID when posting to other users
9409                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9410                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9411                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9412                            intent.putExtra(Intent.EXTRA_UID, uid);
9413                        }
9414                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9415                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9416                        if (DEBUG_BROADCASTS) {
9417                            RuntimeException here = new RuntimeException("here");
9418                            here.fillInStackTrace();
9419                            Slog.d(TAG, "Sending to user " + id + ": "
9420                                    + intent.toShortString(false, true, false, false)
9421                                    + " " + intent.getExtras(), here);
9422                        }
9423                        am.broadcastIntent(null, intent, null, finishedReceiver,
9424                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9425                                null, finishedReceiver != null, false, id);
9426                    }
9427                } catch (RemoteException ex) {
9428                }
9429            }
9430        });
9431    }
9432
9433    /**
9434     * Check if the external storage media is available. This is true if there
9435     * is a mounted external storage medium or if the external storage is
9436     * emulated.
9437     */
9438    private boolean isExternalMediaAvailable() {
9439        return mMediaMounted || Environment.isExternalStorageEmulated();
9440    }
9441
9442    @Override
9443    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9444        // writer
9445        synchronized (mPackages) {
9446            if (!isExternalMediaAvailable()) {
9447                // If the external storage is no longer mounted at this point,
9448                // the caller may not have been able to delete all of this
9449                // packages files and can not delete any more.  Bail.
9450                return null;
9451            }
9452            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9453            if (lastPackage != null) {
9454                pkgs.remove(lastPackage);
9455            }
9456            if (pkgs.size() > 0) {
9457                return pkgs.get(0);
9458            }
9459        }
9460        return null;
9461    }
9462
9463    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9464        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9465                userId, andCode ? 1 : 0, packageName);
9466        if (mSystemReady) {
9467            msg.sendToTarget();
9468        } else {
9469            if (mPostSystemReadyMessages == null) {
9470                mPostSystemReadyMessages = new ArrayList<>();
9471            }
9472            mPostSystemReadyMessages.add(msg);
9473        }
9474    }
9475
9476    void startCleaningPackages() {
9477        // reader
9478        synchronized (mPackages) {
9479            if (!isExternalMediaAvailable()) {
9480                return;
9481            }
9482            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9483                return;
9484            }
9485        }
9486        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9487        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9488        IActivityManager am = ActivityManagerNative.getDefault();
9489        if (am != null) {
9490            try {
9491                am.startService(null, intent, null, mContext.getOpPackageName(),
9492                        UserHandle.USER_OWNER);
9493            } catch (RemoteException e) {
9494            }
9495        }
9496    }
9497
9498    @Override
9499    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9500            int installFlags, String installerPackageName, VerificationParams verificationParams,
9501            String packageAbiOverride) {
9502        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9503                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9504    }
9505
9506    @Override
9507    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9508            int installFlags, String installerPackageName, VerificationParams verificationParams,
9509            String packageAbiOverride, int userId) {
9510        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9511
9512        final int callingUid = Binder.getCallingUid();
9513        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9514
9515        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9516            try {
9517                if (observer != null) {
9518                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9519                }
9520            } catch (RemoteException re) {
9521            }
9522            return;
9523        }
9524
9525        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9526            installFlags |= PackageManager.INSTALL_FROM_ADB;
9527
9528        } else {
9529            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9530            // about installerPackageName.
9531
9532            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9533            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9534        }
9535
9536        UserHandle user;
9537        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9538            user = UserHandle.ALL;
9539        } else {
9540            user = new UserHandle(userId);
9541        }
9542
9543        // Only system components can circumvent runtime permissions when installing.
9544        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9545                && mContext.checkCallingOrSelfPermission(Manifest.permission
9546                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9547            throw new SecurityException("You need the "
9548                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9549                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9550        }
9551
9552        verificationParams.setInstallerUid(callingUid);
9553
9554        final File originFile = new File(originPath);
9555        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9556
9557        final Message msg = mHandler.obtainMessage(INIT_COPY);
9558        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9559                null, verificationParams, user, packageAbiOverride, null);
9560        mHandler.sendMessage(msg);
9561    }
9562
9563    void installStage(String packageName, File stagedDir, String stagedCid,
9564            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9565            String installerPackageName, int installerUid, UserHandle user) {
9566        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9567                params.referrerUri, installerUid, null);
9568        verifParams.setInstallerUid(installerUid);
9569
9570        final OriginInfo origin;
9571        if (stagedDir != null) {
9572            origin = OriginInfo.fromStagedFile(stagedDir);
9573        } else {
9574            origin = OriginInfo.fromStagedContainer(stagedCid);
9575        }
9576
9577        final Message msg = mHandler.obtainMessage(INIT_COPY);
9578        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9579                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9580                params.grantedRuntimePermissions);
9581        mHandler.sendMessage(msg);
9582    }
9583
9584    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9585        Bundle extras = new Bundle(1);
9586        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9587
9588        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9589                packageName, extras, null, null, new int[] {userId});
9590        try {
9591            IActivityManager am = ActivityManagerNative.getDefault();
9592            final boolean isSystem =
9593                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9594            if (isSystem && am.isUserRunning(userId, false)) {
9595                // The just-installed/enabled app is bundled on the system, so presumed
9596                // to be able to run automatically without needing an explicit launch.
9597                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9598                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9599                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9600                        .setPackage(packageName);
9601                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9602                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9603            }
9604        } catch (RemoteException e) {
9605            // shouldn't happen
9606            Slog.w(TAG, "Unable to bootstrap installed package", e);
9607        }
9608    }
9609
9610    @Override
9611    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9612            int userId) {
9613        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9614        PackageSetting pkgSetting;
9615        final int uid = Binder.getCallingUid();
9616        enforceCrossUserPermission(uid, userId, true, true,
9617                "setApplicationHiddenSetting for user " + userId);
9618
9619        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9620            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9621            return false;
9622        }
9623
9624        long callingId = Binder.clearCallingIdentity();
9625        try {
9626            boolean sendAdded = false;
9627            boolean sendRemoved = false;
9628            // writer
9629            synchronized (mPackages) {
9630                pkgSetting = mSettings.mPackages.get(packageName);
9631                if (pkgSetting == null) {
9632                    return false;
9633                }
9634                if (pkgSetting.getHidden(userId) != hidden) {
9635                    pkgSetting.setHidden(hidden, userId);
9636                    mSettings.writePackageRestrictionsLPr(userId);
9637                    if (hidden) {
9638                        sendRemoved = true;
9639                    } else {
9640                        sendAdded = true;
9641                    }
9642                }
9643            }
9644            if (sendAdded) {
9645                sendPackageAddedForUser(packageName, pkgSetting, userId);
9646                return true;
9647            }
9648            if (sendRemoved) {
9649                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9650                        "hiding pkg");
9651                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9652                return true;
9653            }
9654        } finally {
9655            Binder.restoreCallingIdentity(callingId);
9656        }
9657        return false;
9658    }
9659
9660    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9661            int userId) {
9662        final PackageRemovedInfo info = new PackageRemovedInfo();
9663        info.removedPackage = packageName;
9664        info.removedUsers = new int[] {userId};
9665        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9666        info.sendBroadcast(false, false, false);
9667    }
9668
9669    /**
9670     * Returns true if application is not found or there was an error. Otherwise it returns
9671     * the hidden state of the package for the given user.
9672     */
9673    @Override
9674    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9675        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9676        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9677                false, "getApplicationHidden for user " + userId);
9678        PackageSetting pkgSetting;
9679        long callingId = Binder.clearCallingIdentity();
9680        try {
9681            // writer
9682            synchronized (mPackages) {
9683                pkgSetting = mSettings.mPackages.get(packageName);
9684                if (pkgSetting == null) {
9685                    return true;
9686                }
9687                return pkgSetting.getHidden(userId);
9688            }
9689        } finally {
9690            Binder.restoreCallingIdentity(callingId);
9691        }
9692    }
9693
9694    /**
9695     * @hide
9696     */
9697    @Override
9698    public int installExistingPackageAsUser(String packageName, int userId) {
9699        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9700                null);
9701        PackageSetting pkgSetting;
9702        final int uid = Binder.getCallingUid();
9703        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9704                + userId);
9705        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9706            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9707        }
9708
9709        long callingId = Binder.clearCallingIdentity();
9710        try {
9711            boolean sendAdded = false;
9712
9713            // writer
9714            synchronized (mPackages) {
9715                pkgSetting = mSettings.mPackages.get(packageName);
9716                if (pkgSetting == null) {
9717                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9718                }
9719                if (!pkgSetting.getInstalled(userId)) {
9720                    pkgSetting.setInstalled(true, userId);
9721                    pkgSetting.setHidden(false, userId);
9722                    mSettings.writePackageRestrictionsLPr(userId);
9723                    sendAdded = true;
9724                }
9725            }
9726
9727            if (sendAdded) {
9728                sendPackageAddedForUser(packageName, pkgSetting, userId);
9729            }
9730        } finally {
9731            Binder.restoreCallingIdentity(callingId);
9732        }
9733
9734        return PackageManager.INSTALL_SUCCEEDED;
9735    }
9736
9737    boolean isUserRestricted(int userId, String restrictionKey) {
9738        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9739        if (restrictions.getBoolean(restrictionKey, false)) {
9740            Log.w(TAG, "User is restricted: " + restrictionKey);
9741            return true;
9742        }
9743        return false;
9744    }
9745
9746    @Override
9747    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9748        mContext.enforceCallingOrSelfPermission(
9749                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9750                "Only package verification agents can verify applications");
9751
9752        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9753        final PackageVerificationResponse response = new PackageVerificationResponse(
9754                verificationCode, Binder.getCallingUid());
9755        msg.arg1 = id;
9756        msg.obj = response;
9757        mHandler.sendMessage(msg);
9758    }
9759
9760    @Override
9761    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9762            long millisecondsToDelay) {
9763        mContext.enforceCallingOrSelfPermission(
9764                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9765                "Only package verification agents can extend verification timeouts");
9766
9767        final PackageVerificationState state = mPendingVerification.get(id);
9768        final PackageVerificationResponse response = new PackageVerificationResponse(
9769                verificationCodeAtTimeout, Binder.getCallingUid());
9770
9771        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9772            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9773        }
9774        if (millisecondsToDelay < 0) {
9775            millisecondsToDelay = 0;
9776        }
9777        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9778                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9779            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9780        }
9781
9782        if ((state != null) && !state.timeoutExtended()) {
9783            state.extendTimeout();
9784
9785            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9786            msg.arg1 = id;
9787            msg.obj = response;
9788            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9789        }
9790    }
9791
9792    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9793            int verificationCode, UserHandle user) {
9794        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9795        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9796        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9797        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9798        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9799
9800        mContext.sendBroadcastAsUser(intent, user,
9801                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9802    }
9803
9804    private ComponentName matchComponentForVerifier(String packageName,
9805            List<ResolveInfo> receivers) {
9806        ActivityInfo targetReceiver = null;
9807
9808        final int NR = receivers.size();
9809        for (int i = 0; i < NR; i++) {
9810            final ResolveInfo info = receivers.get(i);
9811            if (info.activityInfo == null) {
9812                continue;
9813            }
9814
9815            if (packageName.equals(info.activityInfo.packageName)) {
9816                targetReceiver = info.activityInfo;
9817                break;
9818            }
9819        }
9820
9821        if (targetReceiver == null) {
9822            return null;
9823        }
9824
9825        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9826    }
9827
9828    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9829            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9830        if (pkgInfo.verifiers.length == 0) {
9831            return null;
9832        }
9833
9834        final int N = pkgInfo.verifiers.length;
9835        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9836        for (int i = 0; i < N; i++) {
9837            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9838
9839            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9840                    receivers);
9841            if (comp == null) {
9842                continue;
9843            }
9844
9845            final int verifierUid = getUidForVerifier(verifierInfo);
9846            if (verifierUid == -1) {
9847                continue;
9848            }
9849
9850            if (DEBUG_VERIFY) {
9851                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9852                        + " with the correct signature");
9853            }
9854            sufficientVerifiers.add(comp);
9855            verificationState.addSufficientVerifier(verifierUid);
9856        }
9857
9858        return sufficientVerifiers;
9859    }
9860
9861    private int getUidForVerifier(VerifierInfo verifierInfo) {
9862        synchronized (mPackages) {
9863            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9864            if (pkg == null) {
9865                return -1;
9866            } else if (pkg.mSignatures.length != 1) {
9867                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9868                        + " has more than one signature; ignoring");
9869                return -1;
9870            }
9871
9872            /*
9873             * If the public key of the package's signature does not match
9874             * our expected public key, then this is a different package and
9875             * we should skip.
9876             */
9877
9878            final byte[] expectedPublicKey;
9879            try {
9880                final Signature verifierSig = pkg.mSignatures[0];
9881                final PublicKey publicKey = verifierSig.getPublicKey();
9882                expectedPublicKey = publicKey.getEncoded();
9883            } catch (CertificateException e) {
9884                return -1;
9885            }
9886
9887            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9888
9889            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9890                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9891                        + " does not have the expected public key; ignoring");
9892                return -1;
9893            }
9894
9895            return pkg.applicationInfo.uid;
9896        }
9897    }
9898
9899    @Override
9900    public void finishPackageInstall(int token) {
9901        enforceSystemOrRoot("Only the system is allowed to finish installs");
9902
9903        if (DEBUG_INSTALL) {
9904            Slog.v(TAG, "BM finishing package install for " + token);
9905        }
9906
9907        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9908        mHandler.sendMessage(msg);
9909    }
9910
9911    /**
9912     * Get the verification agent timeout.
9913     *
9914     * @return verification timeout in milliseconds
9915     */
9916    private long getVerificationTimeout() {
9917        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9918                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9919                DEFAULT_VERIFICATION_TIMEOUT);
9920    }
9921
9922    /**
9923     * Get the default verification agent response code.
9924     *
9925     * @return default verification response code
9926     */
9927    private int getDefaultVerificationResponse() {
9928        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9929                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9930                DEFAULT_VERIFICATION_RESPONSE);
9931    }
9932
9933    /**
9934     * Check whether or not package verification has been enabled.
9935     *
9936     * @return true if verification should be performed
9937     */
9938    private boolean isVerificationEnabled(int userId, int installFlags) {
9939        if (!DEFAULT_VERIFY_ENABLE) {
9940            return false;
9941        }
9942
9943        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9944
9945        // Check if installing from ADB
9946        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9947            // Do not run verification in a test harness environment
9948            if (ActivityManager.isRunningInTestHarness()) {
9949                return false;
9950            }
9951            if (ensureVerifyAppsEnabled) {
9952                return true;
9953            }
9954            // Check if the developer does not want package verification for ADB installs
9955            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9956                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9957                return false;
9958            }
9959        }
9960
9961        if (ensureVerifyAppsEnabled) {
9962            return true;
9963        }
9964
9965        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9966                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9967    }
9968
9969    @Override
9970    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9971            throws RemoteException {
9972        mContext.enforceCallingOrSelfPermission(
9973                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9974                "Only intentfilter verification agents can verify applications");
9975
9976        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9977        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9978                Binder.getCallingUid(), verificationCode, failedDomains);
9979        msg.arg1 = id;
9980        msg.obj = response;
9981        mHandler.sendMessage(msg);
9982    }
9983
9984    @Override
9985    public int getIntentVerificationStatus(String packageName, int userId) {
9986        synchronized (mPackages) {
9987            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9988        }
9989    }
9990
9991    @Override
9992    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9993        mContext.enforceCallingOrSelfPermission(
9994                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9995
9996        boolean result = false;
9997        synchronized (mPackages) {
9998            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9999        }
10000        if (result) {
10001            scheduleWritePackageRestrictionsLocked(userId);
10002        }
10003        return result;
10004    }
10005
10006    @Override
10007    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10008        synchronized (mPackages) {
10009            return mSettings.getIntentFilterVerificationsLPr(packageName);
10010        }
10011    }
10012
10013    @Override
10014    public List<IntentFilter> getAllIntentFilters(String packageName) {
10015        if (TextUtils.isEmpty(packageName)) {
10016            return Collections.<IntentFilter>emptyList();
10017        }
10018        synchronized (mPackages) {
10019            PackageParser.Package pkg = mPackages.get(packageName);
10020            if (pkg == null || pkg.activities == null) {
10021                return Collections.<IntentFilter>emptyList();
10022            }
10023            final int count = pkg.activities.size();
10024            ArrayList<IntentFilter> result = new ArrayList<>();
10025            for (int n=0; n<count; n++) {
10026                PackageParser.Activity activity = pkg.activities.get(n);
10027                if (activity.intents != null || activity.intents.size() > 0) {
10028                    result.addAll(activity.intents);
10029                }
10030            }
10031            return result;
10032        }
10033    }
10034
10035    @Override
10036    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10037        mContext.enforceCallingOrSelfPermission(
10038                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10039
10040        synchronized (mPackages) {
10041            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10042            if (packageName != null) {
10043                result |= updateIntentVerificationStatus(packageName,
10044                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10045                        userId);
10046                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10047                        packageName, userId);
10048            }
10049            return result;
10050        }
10051    }
10052
10053    @Override
10054    public String getDefaultBrowserPackageName(int userId) {
10055        synchronized (mPackages) {
10056            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10057        }
10058    }
10059
10060    /**
10061     * Get the "allow unknown sources" setting.
10062     *
10063     * @return the current "allow unknown sources" setting
10064     */
10065    private int getUnknownSourcesSettings() {
10066        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10067                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10068                -1);
10069    }
10070
10071    @Override
10072    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10073        final int uid = Binder.getCallingUid();
10074        // writer
10075        synchronized (mPackages) {
10076            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10077            if (targetPackageSetting == null) {
10078                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10079            }
10080
10081            PackageSetting installerPackageSetting;
10082            if (installerPackageName != null) {
10083                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10084                if (installerPackageSetting == null) {
10085                    throw new IllegalArgumentException("Unknown installer package: "
10086                            + installerPackageName);
10087                }
10088            } else {
10089                installerPackageSetting = null;
10090            }
10091
10092            Signature[] callerSignature;
10093            Object obj = mSettings.getUserIdLPr(uid);
10094            if (obj != null) {
10095                if (obj instanceof SharedUserSetting) {
10096                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10097                } else if (obj instanceof PackageSetting) {
10098                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10099                } else {
10100                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10101                }
10102            } else {
10103                throw new SecurityException("Unknown calling uid " + uid);
10104            }
10105
10106            // Verify: can't set installerPackageName to a package that is
10107            // not signed with the same cert as the caller.
10108            if (installerPackageSetting != null) {
10109                if (compareSignatures(callerSignature,
10110                        installerPackageSetting.signatures.mSignatures)
10111                        != PackageManager.SIGNATURE_MATCH) {
10112                    throw new SecurityException(
10113                            "Caller does not have same cert as new installer package "
10114                            + installerPackageName);
10115                }
10116            }
10117
10118            // Verify: if target already has an installer package, it must
10119            // be signed with the same cert as the caller.
10120            if (targetPackageSetting.installerPackageName != null) {
10121                PackageSetting setting = mSettings.mPackages.get(
10122                        targetPackageSetting.installerPackageName);
10123                // If the currently set package isn't valid, then it's always
10124                // okay to change it.
10125                if (setting != null) {
10126                    if (compareSignatures(callerSignature,
10127                            setting.signatures.mSignatures)
10128                            != PackageManager.SIGNATURE_MATCH) {
10129                        throw new SecurityException(
10130                                "Caller does not have same cert as old installer package "
10131                                + targetPackageSetting.installerPackageName);
10132                    }
10133                }
10134            }
10135
10136            // Okay!
10137            targetPackageSetting.installerPackageName = installerPackageName;
10138            scheduleWriteSettingsLocked();
10139        }
10140    }
10141
10142    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10143        // Queue up an async operation since the package installation may take a little while.
10144        mHandler.post(new Runnable() {
10145            public void run() {
10146                mHandler.removeCallbacks(this);
10147                 // Result object to be returned
10148                PackageInstalledInfo res = new PackageInstalledInfo();
10149                res.returnCode = currentStatus;
10150                res.uid = -1;
10151                res.pkg = null;
10152                res.removedInfo = new PackageRemovedInfo();
10153                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10154                    args.doPreInstall(res.returnCode);
10155                    synchronized (mInstallLock) {
10156                        installPackageLI(args, res);
10157                    }
10158                    args.doPostInstall(res.returnCode, res.uid);
10159                }
10160
10161                // A restore should be performed at this point if (a) the install
10162                // succeeded, (b) the operation is not an update, and (c) the new
10163                // package has not opted out of backup participation.
10164                final boolean update = res.removedInfo.removedPackage != null;
10165                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10166                boolean doRestore = !update
10167                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10168
10169                // Set up the post-install work request bookkeeping.  This will be used
10170                // and cleaned up by the post-install event handling regardless of whether
10171                // there's a restore pass performed.  Token values are >= 1.
10172                int token;
10173                if (mNextInstallToken < 0) mNextInstallToken = 1;
10174                token = mNextInstallToken++;
10175
10176                PostInstallData data = new PostInstallData(args, res);
10177                mRunningInstalls.put(token, data);
10178                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10179
10180                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10181                    // Pass responsibility to the Backup Manager.  It will perform a
10182                    // restore if appropriate, then pass responsibility back to the
10183                    // Package Manager to run the post-install observer callbacks
10184                    // and broadcasts.
10185                    IBackupManager bm = IBackupManager.Stub.asInterface(
10186                            ServiceManager.getService(Context.BACKUP_SERVICE));
10187                    if (bm != null) {
10188                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10189                                + " to BM for possible restore");
10190                        try {
10191                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10192                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10193                            } else {
10194                                doRestore = false;
10195                            }
10196                        } catch (RemoteException e) {
10197                            // can't happen; the backup manager is local
10198                        } catch (Exception e) {
10199                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10200                            doRestore = false;
10201                        }
10202                    } else {
10203                        Slog.e(TAG, "Backup Manager not found!");
10204                        doRestore = false;
10205                    }
10206                }
10207
10208                if (!doRestore) {
10209                    // No restore possible, or the Backup Manager was mysteriously not
10210                    // available -- just fire the post-install work request directly.
10211                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10212                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10213                    mHandler.sendMessage(msg);
10214                }
10215            }
10216        });
10217    }
10218
10219    private abstract class HandlerParams {
10220        private static final int MAX_RETRIES = 4;
10221
10222        /**
10223         * Number of times startCopy() has been attempted and had a non-fatal
10224         * error.
10225         */
10226        private int mRetries = 0;
10227
10228        /** User handle for the user requesting the information or installation. */
10229        private final UserHandle mUser;
10230
10231        HandlerParams(UserHandle user) {
10232            mUser = user;
10233        }
10234
10235        UserHandle getUser() {
10236            return mUser;
10237        }
10238
10239        final boolean startCopy() {
10240            boolean res;
10241            try {
10242                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10243
10244                if (++mRetries > MAX_RETRIES) {
10245                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10246                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10247                    handleServiceError();
10248                    return false;
10249                } else {
10250                    handleStartCopy();
10251                    res = true;
10252                }
10253            } catch (RemoteException e) {
10254                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10255                mHandler.sendEmptyMessage(MCS_RECONNECT);
10256                res = false;
10257            }
10258            handleReturnCode();
10259            return res;
10260        }
10261
10262        final void serviceError() {
10263            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10264            handleServiceError();
10265            handleReturnCode();
10266        }
10267
10268        abstract void handleStartCopy() throws RemoteException;
10269        abstract void handleServiceError();
10270        abstract void handleReturnCode();
10271    }
10272
10273    class MeasureParams extends HandlerParams {
10274        private final PackageStats mStats;
10275        private boolean mSuccess;
10276
10277        private final IPackageStatsObserver mObserver;
10278
10279        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10280            super(new UserHandle(stats.userHandle));
10281            mObserver = observer;
10282            mStats = stats;
10283        }
10284
10285        @Override
10286        public String toString() {
10287            return "MeasureParams{"
10288                + Integer.toHexString(System.identityHashCode(this))
10289                + " " + mStats.packageName + "}";
10290        }
10291
10292        @Override
10293        void handleStartCopy() throws RemoteException {
10294            synchronized (mInstallLock) {
10295                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10296            }
10297
10298            if (mSuccess) {
10299                final boolean mounted;
10300                if (Environment.isExternalStorageEmulated()) {
10301                    mounted = true;
10302                } else {
10303                    final String status = Environment.getExternalStorageState();
10304                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10305                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10306                }
10307
10308                if (mounted) {
10309                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10310
10311                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10312                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10313
10314                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10315                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10316
10317                    // Always subtract cache size, since it's a subdirectory
10318                    mStats.externalDataSize -= mStats.externalCacheSize;
10319
10320                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10321                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10322
10323                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10324                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10325                }
10326            }
10327        }
10328
10329        @Override
10330        void handleReturnCode() {
10331            if (mObserver != null) {
10332                try {
10333                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10334                } catch (RemoteException e) {
10335                    Slog.i(TAG, "Observer no longer exists.");
10336                }
10337            }
10338        }
10339
10340        @Override
10341        void handleServiceError() {
10342            Slog.e(TAG, "Could not measure application " + mStats.packageName
10343                            + " external storage");
10344        }
10345    }
10346
10347    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10348            throws RemoteException {
10349        long result = 0;
10350        for (File path : paths) {
10351            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10352        }
10353        return result;
10354    }
10355
10356    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10357        for (File path : paths) {
10358            try {
10359                mcs.clearDirectory(path.getAbsolutePath());
10360            } catch (RemoteException e) {
10361            }
10362        }
10363    }
10364
10365    static class OriginInfo {
10366        /**
10367         * Location where install is coming from, before it has been
10368         * copied/renamed into place. This could be a single monolithic APK
10369         * file, or a cluster directory. This location may be untrusted.
10370         */
10371        final File file;
10372        final String cid;
10373
10374        /**
10375         * Flag indicating that {@link #file} or {@link #cid} has already been
10376         * staged, meaning downstream users don't need to defensively copy the
10377         * contents.
10378         */
10379        final boolean staged;
10380
10381        /**
10382         * Flag indicating that {@link #file} or {@link #cid} is an already
10383         * installed app that is being moved.
10384         */
10385        final boolean existing;
10386
10387        final String resolvedPath;
10388        final File resolvedFile;
10389
10390        static OriginInfo fromNothing() {
10391            return new OriginInfo(null, null, false, false);
10392        }
10393
10394        static OriginInfo fromUntrustedFile(File file) {
10395            return new OriginInfo(file, null, false, false);
10396        }
10397
10398        static OriginInfo fromExistingFile(File file) {
10399            return new OriginInfo(file, null, false, true);
10400        }
10401
10402        static OriginInfo fromStagedFile(File file) {
10403            return new OriginInfo(file, null, true, false);
10404        }
10405
10406        static OriginInfo fromStagedContainer(String cid) {
10407            return new OriginInfo(null, cid, true, false);
10408        }
10409
10410        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10411            this.file = file;
10412            this.cid = cid;
10413            this.staged = staged;
10414            this.existing = existing;
10415
10416            if (cid != null) {
10417                resolvedPath = PackageHelper.getSdDir(cid);
10418                resolvedFile = new File(resolvedPath);
10419            } else if (file != null) {
10420                resolvedPath = file.getAbsolutePath();
10421                resolvedFile = file;
10422            } else {
10423                resolvedPath = null;
10424                resolvedFile = null;
10425            }
10426        }
10427    }
10428
10429    class MoveInfo {
10430        final int moveId;
10431        final String fromUuid;
10432        final String toUuid;
10433        final String packageName;
10434        final String dataAppName;
10435        final int appId;
10436        final String seinfo;
10437
10438        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10439                String dataAppName, int appId, String seinfo) {
10440            this.moveId = moveId;
10441            this.fromUuid = fromUuid;
10442            this.toUuid = toUuid;
10443            this.packageName = packageName;
10444            this.dataAppName = dataAppName;
10445            this.appId = appId;
10446            this.seinfo = seinfo;
10447        }
10448    }
10449
10450    class InstallParams extends HandlerParams {
10451        final OriginInfo origin;
10452        final MoveInfo move;
10453        final IPackageInstallObserver2 observer;
10454        int installFlags;
10455        final String installerPackageName;
10456        final String volumeUuid;
10457        final VerificationParams verificationParams;
10458        private InstallArgs mArgs;
10459        private int mRet;
10460        final String packageAbiOverride;
10461        final String[] grantedRuntimePermissions;
10462
10463
10464        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10465                int installFlags, String installerPackageName, String volumeUuid,
10466                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10467                String[] grantedPermissions) {
10468            super(user);
10469            this.origin = origin;
10470            this.move = move;
10471            this.observer = observer;
10472            this.installFlags = installFlags;
10473            this.installerPackageName = installerPackageName;
10474            this.volumeUuid = volumeUuid;
10475            this.verificationParams = verificationParams;
10476            this.packageAbiOverride = packageAbiOverride;
10477            this.grantedRuntimePermissions = grantedPermissions;
10478        }
10479
10480        @Override
10481        public String toString() {
10482            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10483                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10484        }
10485
10486        public ManifestDigest getManifestDigest() {
10487            if (verificationParams == null) {
10488                return null;
10489            }
10490            return verificationParams.getManifestDigest();
10491        }
10492
10493        private int installLocationPolicy(PackageInfoLite pkgLite) {
10494            String packageName = pkgLite.packageName;
10495            int installLocation = pkgLite.installLocation;
10496            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10497            // reader
10498            synchronized (mPackages) {
10499                PackageParser.Package pkg = mPackages.get(packageName);
10500                if (pkg != null) {
10501                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10502                        // Check for downgrading.
10503                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10504                            try {
10505                                checkDowngrade(pkg, pkgLite);
10506                            } catch (PackageManagerException e) {
10507                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10508                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10509                            }
10510                        }
10511                        // Check for updated system application.
10512                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10513                            if (onSd) {
10514                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10515                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10516                            }
10517                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10518                        } else {
10519                            if (onSd) {
10520                                // Install flag overrides everything.
10521                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10522                            }
10523                            // If current upgrade specifies particular preference
10524                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10525                                // Application explicitly specified internal.
10526                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10527                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10528                                // App explictly prefers external. Let policy decide
10529                            } else {
10530                                // Prefer previous location
10531                                if (isExternal(pkg)) {
10532                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10533                                }
10534                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10535                            }
10536                        }
10537                    } else {
10538                        // Invalid install. Return error code
10539                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10540                    }
10541                }
10542            }
10543            // All the special cases have been taken care of.
10544            // Return result based on recommended install location.
10545            if (onSd) {
10546                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10547            }
10548            return pkgLite.recommendedInstallLocation;
10549        }
10550
10551        /*
10552         * Invoke remote method to get package information and install
10553         * location values. Override install location based on default
10554         * policy if needed and then create install arguments based
10555         * on the install location.
10556         */
10557        public void handleStartCopy() throws RemoteException {
10558            int ret = PackageManager.INSTALL_SUCCEEDED;
10559
10560            // If we're already staged, we've firmly committed to an install location
10561            if (origin.staged) {
10562                if (origin.file != null) {
10563                    installFlags |= PackageManager.INSTALL_INTERNAL;
10564                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10565                } else if (origin.cid != null) {
10566                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10567                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10568                } else {
10569                    throw new IllegalStateException("Invalid stage location");
10570                }
10571            }
10572
10573            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10574            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10575
10576            PackageInfoLite pkgLite = null;
10577
10578            if (onInt && onSd) {
10579                // Check if both bits are set.
10580                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10581                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10582            } else {
10583                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10584                        packageAbiOverride);
10585
10586                /*
10587                 * If we have too little free space, try to free cache
10588                 * before giving up.
10589                 */
10590                if (!origin.staged && pkgLite.recommendedInstallLocation
10591                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10592                    // TODO: focus freeing disk space on the target device
10593                    final StorageManager storage = StorageManager.from(mContext);
10594                    final long lowThreshold = storage.getStorageLowBytes(
10595                            Environment.getDataDirectory());
10596
10597                    final long sizeBytes = mContainerService.calculateInstalledSize(
10598                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10599
10600                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10601                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10602                                installFlags, packageAbiOverride);
10603                    }
10604
10605                    /*
10606                     * The cache free must have deleted the file we
10607                     * downloaded to install.
10608                     *
10609                     * TODO: fix the "freeCache" call to not delete
10610                     *       the file we care about.
10611                     */
10612                    if (pkgLite.recommendedInstallLocation
10613                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10614                        pkgLite.recommendedInstallLocation
10615                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10616                    }
10617                }
10618            }
10619
10620            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10621                int loc = pkgLite.recommendedInstallLocation;
10622                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10623                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10624                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10625                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10626                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10627                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10628                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10629                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10630                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10631                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10632                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10633                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10634                } else {
10635                    // Override with defaults if needed.
10636                    loc = installLocationPolicy(pkgLite);
10637                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10638                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10639                    } else if (!onSd && !onInt) {
10640                        // Override install location with flags
10641                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10642                            // Set the flag to install on external media.
10643                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10644                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10645                        } else {
10646                            // Make sure the flag for installing on external
10647                            // media is unset
10648                            installFlags |= PackageManager.INSTALL_INTERNAL;
10649                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10650                        }
10651                    }
10652                }
10653            }
10654
10655            final InstallArgs args = createInstallArgs(this);
10656            mArgs = args;
10657
10658            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10659                 /*
10660                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10661                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10662                 */
10663                int userIdentifier = getUser().getIdentifier();
10664                if (userIdentifier == UserHandle.USER_ALL
10665                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10666                    userIdentifier = UserHandle.USER_OWNER;
10667                }
10668
10669                /*
10670                 * Determine if we have any installed package verifiers. If we
10671                 * do, then we'll defer to them to verify the packages.
10672                 */
10673                final int requiredUid = mRequiredVerifierPackage == null ? -1
10674                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10675                if (!origin.existing && requiredUid != -1
10676                        && isVerificationEnabled(userIdentifier, installFlags)) {
10677                    final Intent verification = new Intent(
10678                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10679                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10680                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10681                            PACKAGE_MIME_TYPE);
10682                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10683
10684                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10685                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10686                            0 /* TODO: Which userId? */);
10687
10688                    if (DEBUG_VERIFY) {
10689                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10690                                + verification.toString() + " with " + pkgLite.verifiers.length
10691                                + " optional verifiers");
10692                    }
10693
10694                    final int verificationId = mPendingVerificationToken++;
10695
10696                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10697
10698                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10699                            installerPackageName);
10700
10701                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10702                            installFlags);
10703
10704                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10705                            pkgLite.packageName);
10706
10707                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10708                            pkgLite.versionCode);
10709
10710                    if (verificationParams != null) {
10711                        if (verificationParams.getVerificationURI() != null) {
10712                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10713                                 verificationParams.getVerificationURI());
10714                        }
10715                        if (verificationParams.getOriginatingURI() != null) {
10716                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10717                                  verificationParams.getOriginatingURI());
10718                        }
10719                        if (verificationParams.getReferrer() != null) {
10720                            verification.putExtra(Intent.EXTRA_REFERRER,
10721                                  verificationParams.getReferrer());
10722                        }
10723                        if (verificationParams.getOriginatingUid() >= 0) {
10724                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10725                                  verificationParams.getOriginatingUid());
10726                        }
10727                        if (verificationParams.getInstallerUid() >= 0) {
10728                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10729                                  verificationParams.getInstallerUid());
10730                        }
10731                    }
10732
10733                    final PackageVerificationState verificationState = new PackageVerificationState(
10734                            requiredUid, args);
10735
10736                    mPendingVerification.append(verificationId, verificationState);
10737
10738                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10739                            receivers, verificationState);
10740
10741                    // Apps installed for "all" users use the device owner to verify the app
10742                    UserHandle verifierUser = getUser();
10743                    if (verifierUser == UserHandle.ALL) {
10744                        verifierUser = UserHandle.OWNER;
10745                    }
10746
10747                    /*
10748                     * If any sufficient verifiers were listed in the package
10749                     * manifest, attempt to ask them.
10750                     */
10751                    if (sufficientVerifiers != null) {
10752                        final int N = sufficientVerifiers.size();
10753                        if (N == 0) {
10754                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10755                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10756                        } else {
10757                            for (int i = 0; i < N; i++) {
10758                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10759
10760                                final Intent sufficientIntent = new Intent(verification);
10761                                sufficientIntent.setComponent(verifierComponent);
10762                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10763                            }
10764                        }
10765                    }
10766
10767                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10768                            mRequiredVerifierPackage, receivers);
10769                    if (ret == PackageManager.INSTALL_SUCCEEDED
10770                            && mRequiredVerifierPackage != null) {
10771                        /*
10772                         * Send the intent to the required verification agent,
10773                         * but only start the verification timeout after the
10774                         * target BroadcastReceivers have run.
10775                         */
10776                        verification.setComponent(requiredVerifierComponent);
10777                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10778                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10779                                new BroadcastReceiver() {
10780                                    @Override
10781                                    public void onReceive(Context context, Intent intent) {
10782                                        final Message msg = mHandler
10783                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10784                                        msg.arg1 = verificationId;
10785                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10786                                    }
10787                                }, null, 0, null, null);
10788
10789                        /*
10790                         * We don't want the copy to proceed until verification
10791                         * succeeds, so null out this field.
10792                         */
10793                        mArgs = null;
10794                    }
10795                } else {
10796                    /*
10797                     * No package verification is enabled, so immediately start
10798                     * the remote call to initiate copy using temporary file.
10799                     */
10800                    ret = args.copyApk(mContainerService, true);
10801                }
10802            }
10803
10804            mRet = ret;
10805        }
10806
10807        @Override
10808        void handleReturnCode() {
10809            // If mArgs is null, then MCS couldn't be reached. When it
10810            // reconnects, it will try again to install. At that point, this
10811            // will succeed.
10812            if (mArgs != null) {
10813                processPendingInstall(mArgs, mRet);
10814            }
10815        }
10816
10817        @Override
10818        void handleServiceError() {
10819            mArgs = createInstallArgs(this);
10820            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10821        }
10822
10823        public boolean isForwardLocked() {
10824            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10825        }
10826    }
10827
10828    /**
10829     * Used during creation of InstallArgs
10830     *
10831     * @param installFlags package installation flags
10832     * @return true if should be installed on external storage
10833     */
10834    private static boolean installOnExternalAsec(int installFlags) {
10835        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10836            return false;
10837        }
10838        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10839            return true;
10840        }
10841        return false;
10842    }
10843
10844    /**
10845     * Used during creation of InstallArgs
10846     *
10847     * @param installFlags package installation flags
10848     * @return true if should be installed as forward locked
10849     */
10850    private static boolean installForwardLocked(int installFlags) {
10851        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10852    }
10853
10854    private InstallArgs createInstallArgs(InstallParams params) {
10855        if (params.move != null) {
10856            return new MoveInstallArgs(params);
10857        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10858            return new AsecInstallArgs(params);
10859        } else {
10860            return new FileInstallArgs(params);
10861        }
10862    }
10863
10864    /**
10865     * Create args that describe an existing installed package. Typically used
10866     * when cleaning up old installs, or used as a move source.
10867     */
10868    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10869            String resourcePath, String[] instructionSets) {
10870        final boolean isInAsec;
10871        if (installOnExternalAsec(installFlags)) {
10872            /* Apps on SD card are always in ASEC containers. */
10873            isInAsec = true;
10874        } else if (installForwardLocked(installFlags)
10875                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10876            /*
10877             * Forward-locked apps are only in ASEC containers if they're the
10878             * new style
10879             */
10880            isInAsec = true;
10881        } else {
10882            isInAsec = false;
10883        }
10884
10885        if (isInAsec) {
10886            return new AsecInstallArgs(codePath, instructionSets,
10887                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10888        } else {
10889            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10890        }
10891    }
10892
10893    static abstract class InstallArgs {
10894        /** @see InstallParams#origin */
10895        final OriginInfo origin;
10896        /** @see InstallParams#move */
10897        final MoveInfo move;
10898
10899        final IPackageInstallObserver2 observer;
10900        // Always refers to PackageManager flags only
10901        final int installFlags;
10902        final String installerPackageName;
10903        final String volumeUuid;
10904        final ManifestDigest manifestDigest;
10905        final UserHandle user;
10906        final String abiOverride;
10907        final String[] installGrantPermissions;
10908
10909        // The list of instruction sets supported by this app. This is currently
10910        // only used during the rmdex() phase to clean up resources. We can get rid of this
10911        // if we move dex files under the common app path.
10912        /* nullable */ String[] instructionSets;
10913
10914        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10915                int installFlags, String installerPackageName, String volumeUuid,
10916                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10917                String abiOverride, String[] installGrantPermissions) {
10918            this.origin = origin;
10919            this.move = move;
10920            this.installFlags = installFlags;
10921            this.observer = observer;
10922            this.installerPackageName = installerPackageName;
10923            this.volumeUuid = volumeUuid;
10924            this.manifestDigest = manifestDigest;
10925            this.user = user;
10926            this.instructionSets = instructionSets;
10927            this.abiOverride = abiOverride;
10928            this.installGrantPermissions = installGrantPermissions;
10929        }
10930
10931        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10932        abstract int doPreInstall(int status);
10933
10934        /**
10935         * Rename package into final resting place. All paths on the given
10936         * scanned package should be updated to reflect the rename.
10937         */
10938        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10939        abstract int doPostInstall(int status, int uid);
10940
10941        /** @see PackageSettingBase#codePathString */
10942        abstract String getCodePath();
10943        /** @see PackageSettingBase#resourcePathString */
10944        abstract String getResourcePath();
10945
10946        // Need installer lock especially for dex file removal.
10947        abstract void cleanUpResourcesLI();
10948        abstract boolean doPostDeleteLI(boolean delete);
10949
10950        /**
10951         * Called before the source arguments are copied. This is used mostly
10952         * for MoveParams when it needs to read the source file to put it in the
10953         * destination.
10954         */
10955        int doPreCopy() {
10956            return PackageManager.INSTALL_SUCCEEDED;
10957        }
10958
10959        /**
10960         * Called after the source arguments are copied. This is used mostly for
10961         * MoveParams when it needs to read the source file to put it in the
10962         * destination.
10963         *
10964         * @return
10965         */
10966        int doPostCopy(int uid) {
10967            return PackageManager.INSTALL_SUCCEEDED;
10968        }
10969
10970        protected boolean isFwdLocked() {
10971            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10972        }
10973
10974        protected boolean isExternalAsec() {
10975            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10976        }
10977
10978        UserHandle getUser() {
10979            return user;
10980        }
10981    }
10982
10983    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10984        if (!allCodePaths.isEmpty()) {
10985            if (instructionSets == null) {
10986                throw new IllegalStateException("instructionSet == null");
10987            }
10988            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10989            for (String codePath : allCodePaths) {
10990                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10991                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10992                    if (retCode < 0) {
10993                        Slog.w(TAG, "Couldn't remove dex file for package: "
10994                                + " at location " + codePath + ", retcode=" + retCode);
10995                        // we don't consider this to be a failure of the core package deletion
10996                    }
10997                }
10998            }
10999        }
11000    }
11001
11002    /**
11003     * Logic to handle installation of non-ASEC applications, including copying
11004     * and renaming logic.
11005     */
11006    class FileInstallArgs extends InstallArgs {
11007        private File codeFile;
11008        private File resourceFile;
11009
11010        // Example topology:
11011        // /data/app/com.example/base.apk
11012        // /data/app/com.example/split_foo.apk
11013        // /data/app/com.example/lib/arm/libfoo.so
11014        // /data/app/com.example/lib/arm64/libfoo.so
11015        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11016
11017        /** New install */
11018        FileInstallArgs(InstallParams params) {
11019            super(params.origin, params.move, params.observer, params.installFlags,
11020                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11021                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11022                    params.grantedRuntimePermissions);
11023            if (isFwdLocked()) {
11024                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11025            }
11026        }
11027
11028        /** Existing install */
11029        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11030            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11031                    null, null);
11032            this.codeFile = (codePath != null) ? new File(codePath) : null;
11033            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11034        }
11035
11036        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11037            if (origin.staged) {
11038                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11039                codeFile = origin.file;
11040                resourceFile = origin.file;
11041                return PackageManager.INSTALL_SUCCEEDED;
11042            }
11043
11044            try {
11045                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11046                codeFile = tempDir;
11047                resourceFile = tempDir;
11048            } catch (IOException e) {
11049                Slog.w(TAG, "Failed to create copy file: " + e);
11050                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11051            }
11052
11053            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11054                @Override
11055                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11056                    if (!FileUtils.isValidExtFilename(name)) {
11057                        throw new IllegalArgumentException("Invalid filename: " + name);
11058                    }
11059                    try {
11060                        final File file = new File(codeFile, name);
11061                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11062                                O_RDWR | O_CREAT, 0644);
11063                        Os.chmod(file.getAbsolutePath(), 0644);
11064                        return new ParcelFileDescriptor(fd);
11065                    } catch (ErrnoException e) {
11066                        throw new RemoteException("Failed to open: " + e.getMessage());
11067                    }
11068                }
11069            };
11070
11071            int ret = PackageManager.INSTALL_SUCCEEDED;
11072            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11073            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11074                Slog.e(TAG, "Failed to copy package");
11075                return ret;
11076            }
11077
11078            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11079            NativeLibraryHelper.Handle handle = null;
11080            try {
11081                handle = NativeLibraryHelper.Handle.create(codeFile);
11082                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11083                        abiOverride);
11084            } catch (IOException e) {
11085                Slog.e(TAG, "Copying native libraries failed", e);
11086                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11087            } finally {
11088                IoUtils.closeQuietly(handle);
11089            }
11090
11091            return ret;
11092        }
11093
11094        int doPreInstall(int status) {
11095            if (status != PackageManager.INSTALL_SUCCEEDED) {
11096                cleanUp();
11097            }
11098            return status;
11099        }
11100
11101        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11102            if (status != PackageManager.INSTALL_SUCCEEDED) {
11103                cleanUp();
11104                return false;
11105            }
11106
11107            final File targetDir = codeFile.getParentFile();
11108            final File beforeCodeFile = codeFile;
11109            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11110
11111            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11112            try {
11113                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11114            } catch (ErrnoException e) {
11115                Slog.w(TAG, "Failed to rename", e);
11116                return false;
11117            }
11118
11119            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11120                Slog.w(TAG, "Failed to restorecon");
11121                return false;
11122            }
11123
11124            // Reflect the rename internally
11125            codeFile = afterCodeFile;
11126            resourceFile = afterCodeFile;
11127
11128            // Reflect the rename in scanned details
11129            pkg.codePath = afterCodeFile.getAbsolutePath();
11130            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11131                    pkg.baseCodePath);
11132            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11133                    pkg.splitCodePaths);
11134
11135            // Reflect the rename in app info
11136            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11137            pkg.applicationInfo.setCodePath(pkg.codePath);
11138            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11139            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11140            pkg.applicationInfo.setResourcePath(pkg.codePath);
11141            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11142            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11143
11144            return true;
11145        }
11146
11147        int doPostInstall(int status, int uid) {
11148            if (status != PackageManager.INSTALL_SUCCEEDED) {
11149                cleanUp();
11150            }
11151            return status;
11152        }
11153
11154        @Override
11155        String getCodePath() {
11156            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11157        }
11158
11159        @Override
11160        String getResourcePath() {
11161            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11162        }
11163
11164        private boolean cleanUp() {
11165            if (codeFile == null || !codeFile.exists()) {
11166                return false;
11167            }
11168
11169            if (codeFile.isDirectory()) {
11170                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11171            } else {
11172                codeFile.delete();
11173            }
11174
11175            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11176                resourceFile.delete();
11177            }
11178
11179            return true;
11180        }
11181
11182        void cleanUpResourcesLI() {
11183            // Try enumerating all code paths before deleting
11184            List<String> allCodePaths = Collections.EMPTY_LIST;
11185            if (codeFile != null && codeFile.exists()) {
11186                try {
11187                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11188                    allCodePaths = pkg.getAllCodePaths();
11189                } catch (PackageParserException e) {
11190                    // Ignored; we tried our best
11191                }
11192            }
11193
11194            cleanUp();
11195            removeDexFiles(allCodePaths, instructionSets);
11196        }
11197
11198        boolean doPostDeleteLI(boolean delete) {
11199            // XXX err, shouldn't we respect the delete flag?
11200            cleanUpResourcesLI();
11201            return true;
11202        }
11203    }
11204
11205    private boolean isAsecExternal(String cid) {
11206        final String asecPath = PackageHelper.getSdFilesystem(cid);
11207        return !asecPath.startsWith(mAsecInternalPath);
11208    }
11209
11210    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11211            PackageManagerException {
11212        if (copyRet < 0) {
11213            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11214                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11215                throw new PackageManagerException(copyRet, message);
11216            }
11217        }
11218    }
11219
11220    /**
11221     * Extract the MountService "container ID" from the full code path of an
11222     * .apk.
11223     */
11224    static String cidFromCodePath(String fullCodePath) {
11225        int eidx = fullCodePath.lastIndexOf("/");
11226        String subStr1 = fullCodePath.substring(0, eidx);
11227        int sidx = subStr1.lastIndexOf("/");
11228        return subStr1.substring(sidx+1, eidx);
11229    }
11230
11231    /**
11232     * Logic to handle installation of ASEC applications, including copying and
11233     * renaming logic.
11234     */
11235    class AsecInstallArgs extends InstallArgs {
11236        static final String RES_FILE_NAME = "pkg.apk";
11237        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11238
11239        String cid;
11240        String packagePath;
11241        String resourcePath;
11242
11243        /** New install */
11244        AsecInstallArgs(InstallParams params) {
11245            super(params.origin, params.move, params.observer, params.installFlags,
11246                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11247                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11248                    params.grantedRuntimePermissions);
11249        }
11250
11251        /** Existing install */
11252        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11253                        boolean isExternal, boolean isForwardLocked) {
11254            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11255                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11256                    instructionSets, null, null);
11257            // Hackily pretend we're still looking at a full code path
11258            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11259                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11260            }
11261
11262            // Extract cid from fullCodePath
11263            int eidx = fullCodePath.lastIndexOf("/");
11264            String subStr1 = fullCodePath.substring(0, eidx);
11265            int sidx = subStr1.lastIndexOf("/");
11266            cid = subStr1.substring(sidx+1, eidx);
11267            setMountPath(subStr1);
11268        }
11269
11270        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11271            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11272                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11273                    instructionSets, null, null);
11274            this.cid = cid;
11275            setMountPath(PackageHelper.getSdDir(cid));
11276        }
11277
11278        void createCopyFile() {
11279            cid = mInstallerService.allocateExternalStageCidLegacy();
11280        }
11281
11282        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11283            if (origin.staged) {
11284                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11285                cid = origin.cid;
11286                setMountPath(PackageHelper.getSdDir(cid));
11287                return PackageManager.INSTALL_SUCCEEDED;
11288            }
11289
11290            if (temp) {
11291                createCopyFile();
11292            } else {
11293                /*
11294                 * Pre-emptively destroy the container since it's destroyed if
11295                 * copying fails due to it existing anyway.
11296                 */
11297                PackageHelper.destroySdDir(cid);
11298            }
11299
11300            final String newMountPath = imcs.copyPackageToContainer(
11301                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11302                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11303
11304            if (newMountPath != null) {
11305                setMountPath(newMountPath);
11306                return PackageManager.INSTALL_SUCCEEDED;
11307            } else {
11308                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11309            }
11310        }
11311
11312        @Override
11313        String getCodePath() {
11314            return packagePath;
11315        }
11316
11317        @Override
11318        String getResourcePath() {
11319            return resourcePath;
11320        }
11321
11322        int doPreInstall(int status) {
11323            if (status != PackageManager.INSTALL_SUCCEEDED) {
11324                // Destroy container
11325                PackageHelper.destroySdDir(cid);
11326            } else {
11327                boolean mounted = PackageHelper.isContainerMounted(cid);
11328                if (!mounted) {
11329                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11330                            Process.SYSTEM_UID);
11331                    if (newMountPath != null) {
11332                        setMountPath(newMountPath);
11333                    } else {
11334                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11335                    }
11336                }
11337            }
11338            return status;
11339        }
11340
11341        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11342            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11343            String newMountPath = null;
11344            if (PackageHelper.isContainerMounted(cid)) {
11345                // Unmount the container
11346                if (!PackageHelper.unMountSdDir(cid)) {
11347                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11348                    return false;
11349                }
11350            }
11351            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11352                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11353                        " which might be stale. Will try to clean up.");
11354                // Clean up the stale container and proceed to recreate.
11355                if (!PackageHelper.destroySdDir(newCacheId)) {
11356                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11357                    return false;
11358                }
11359                // Successfully cleaned up stale container. Try to rename again.
11360                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11361                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11362                            + " inspite of cleaning it up.");
11363                    return false;
11364                }
11365            }
11366            if (!PackageHelper.isContainerMounted(newCacheId)) {
11367                Slog.w(TAG, "Mounting container " + newCacheId);
11368                newMountPath = PackageHelper.mountSdDir(newCacheId,
11369                        getEncryptKey(), Process.SYSTEM_UID);
11370            } else {
11371                newMountPath = PackageHelper.getSdDir(newCacheId);
11372            }
11373            if (newMountPath == null) {
11374                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11375                return false;
11376            }
11377            Log.i(TAG, "Succesfully renamed " + cid +
11378                    " to " + newCacheId +
11379                    " at new path: " + newMountPath);
11380            cid = newCacheId;
11381
11382            final File beforeCodeFile = new File(packagePath);
11383            setMountPath(newMountPath);
11384            final File afterCodeFile = new File(packagePath);
11385
11386            // Reflect the rename in scanned details
11387            pkg.codePath = afterCodeFile.getAbsolutePath();
11388            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11389                    pkg.baseCodePath);
11390            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11391                    pkg.splitCodePaths);
11392
11393            // Reflect the rename in app info
11394            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11395            pkg.applicationInfo.setCodePath(pkg.codePath);
11396            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11397            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11398            pkg.applicationInfo.setResourcePath(pkg.codePath);
11399            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11400            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11401
11402            return true;
11403        }
11404
11405        private void setMountPath(String mountPath) {
11406            final File mountFile = new File(mountPath);
11407
11408            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11409            if (monolithicFile.exists()) {
11410                packagePath = monolithicFile.getAbsolutePath();
11411                if (isFwdLocked()) {
11412                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11413                } else {
11414                    resourcePath = packagePath;
11415                }
11416            } else {
11417                packagePath = mountFile.getAbsolutePath();
11418                resourcePath = packagePath;
11419            }
11420        }
11421
11422        int doPostInstall(int status, int uid) {
11423            if (status != PackageManager.INSTALL_SUCCEEDED) {
11424                cleanUp();
11425            } else {
11426                final int groupOwner;
11427                final String protectedFile;
11428                if (isFwdLocked()) {
11429                    groupOwner = UserHandle.getSharedAppGid(uid);
11430                    protectedFile = RES_FILE_NAME;
11431                } else {
11432                    groupOwner = -1;
11433                    protectedFile = null;
11434                }
11435
11436                if (uid < Process.FIRST_APPLICATION_UID
11437                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11438                    Slog.e(TAG, "Failed to finalize " + cid);
11439                    PackageHelper.destroySdDir(cid);
11440                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11441                }
11442
11443                boolean mounted = PackageHelper.isContainerMounted(cid);
11444                if (!mounted) {
11445                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11446                }
11447            }
11448            return status;
11449        }
11450
11451        private void cleanUp() {
11452            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11453
11454            // Destroy secure container
11455            PackageHelper.destroySdDir(cid);
11456        }
11457
11458        private List<String> getAllCodePaths() {
11459            final File codeFile = new File(getCodePath());
11460            if (codeFile != null && codeFile.exists()) {
11461                try {
11462                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11463                    return pkg.getAllCodePaths();
11464                } catch (PackageParserException e) {
11465                    // Ignored; we tried our best
11466                }
11467            }
11468            return Collections.EMPTY_LIST;
11469        }
11470
11471        void cleanUpResourcesLI() {
11472            // Enumerate all code paths before deleting
11473            cleanUpResourcesLI(getAllCodePaths());
11474        }
11475
11476        private void cleanUpResourcesLI(List<String> allCodePaths) {
11477            cleanUp();
11478            removeDexFiles(allCodePaths, instructionSets);
11479        }
11480
11481        String getPackageName() {
11482            return getAsecPackageName(cid);
11483        }
11484
11485        boolean doPostDeleteLI(boolean delete) {
11486            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11487            final List<String> allCodePaths = getAllCodePaths();
11488            boolean mounted = PackageHelper.isContainerMounted(cid);
11489            if (mounted) {
11490                // Unmount first
11491                if (PackageHelper.unMountSdDir(cid)) {
11492                    mounted = false;
11493                }
11494            }
11495            if (!mounted && delete) {
11496                cleanUpResourcesLI(allCodePaths);
11497            }
11498            return !mounted;
11499        }
11500
11501        @Override
11502        int doPreCopy() {
11503            if (isFwdLocked()) {
11504                if (!PackageHelper.fixSdPermissions(cid,
11505                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11506                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11507                }
11508            }
11509
11510            return PackageManager.INSTALL_SUCCEEDED;
11511        }
11512
11513        @Override
11514        int doPostCopy(int uid) {
11515            if (isFwdLocked()) {
11516                if (uid < Process.FIRST_APPLICATION_UID
11517                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11518                                RES_FILE_NAME)) {
11519                    Slog.e(TAG, "Failed to finalize " + cid);
11520                    PackageHelper.destroySdDir(cid);
11521                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11522                }
11523            }
11524
11525            return PackageManager.INSTALL_SUCCEEDED;
11526        }
11527    }
11528
11529    /**
11530     * Logic to handle movement of existing installed applications.
11531     */
11532    class MoveInstallArgs extends InstallArgs {
11533        private File codeFile;
11534        private File resourceFile;
11535
11536        /** New install */
11537        MoveInstallArgs(InstallParams params) {
11538            super(params.origin, params.move, params.observer, params.installFlags,
11539                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11540                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11541                    params.grantedRuntimePermissions);
11542        }
11543
11544        int copyApk(IMediaContainerService imcs, boolean temp) {
11545            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11546                    + move.fromUuid + " to " + move.toUuid);
11547            synchronized (mInstaller) {
11548                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11549                        move.dataAppName, move.appId, move.seinfo) != 0) {
11550                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11551                }
11552            }
11553
11554            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11555            resourceFile = codeFile;
11556            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11557
11558            return PackageManager.INSTALL_SUCCEEDED;
11559        }
11560
11561        int doPreInstall(int status) {
11562            if (status != PackageManager.INSTALL_SUCCEEDED) {
11563                cleanUp(move.toUuid);
11564            }
11565            return status;
11566        }
11567
11568        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11569            if (status != PackageManager.INSTALL_SUCCEEDED) {
11570                cleanUp(move.toUuid);
11571                return false;
11572            }
11573
11574            // Reflect the move in app info
11575            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11576            pkg.applicationInfo.setCodePath(pkg.codePath);
11577            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11578            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11579            pkg.applicationInfo.setResourcePath(pkg.codePath);
11580            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11581            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11582
11583            return true;
11584        }
11585
11586        int doPostInstall(int status, int uid) {
11587            if (status == PackageManager.INSTALL_SUCCEEDED) {
11588                cleanUp(move.fromUuid);
11589            } else {
11590                cleanUp(move.toUuid);
11591            }
11592            return status;
11593        }
11594
11595        @Override
11596        String getCodePath() {
11597            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11598        }
11599
11600        @Override
11601        String getResourcePath() {
11602            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11603        }
11604
11605        private boolean cleanUp(String volumeUuid) {
11606            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11607                    move.dataAppName);
11608            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11609            synchronized (mInstallLock) {
11610                // Clean up both app data and code
11611                removeDataDirsLI(volumeUuid, move.packageName);
11612                if (codeFile.isDirectory()) {
11613                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11614                } else {
11615                    codeFile.delete();
11616                }
11617            }
11618            return true;
11619        }
11620
11621        void cleanUpResourcesLI() {
11622            throw new UnsupportedOperationException();
11623        }
11624
11625        boolean doPostDeleteLI(boolean delete) {
11626            throw new UnsupportedOperationException();
11627        }
11628    }
11629
11630    static String getAsecPackageName(String packageCid) {
11631        int idx = packageCid.lastIndexOf("-");
11632        if (idx == -1) {
11633            return packageCid;
11634        }
11635        return packageCid.substring(0, idx);
11636    }
11637
11638    // Utility method used to create code paths based on package name and available index.
11639    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11640        String idxStr = "";
11641        int idx = 1;
11642        // Fall back to default value of idx=1 if prefix is not
11643        // part of oldCodePath
11644        if (oldCodePath != null) {
11645            String subStr = oldCodePath;
11646            // Drop the suffix right away
11647            if (suffix != null && subStr.endsWith(suffix)) {
11648                subStr = subStr.substring(0, subStr.length() - suffix.length());
11649            }
11650            // If oldCodePath already contains prefix find out the
11651            // ending index to either increment or decrement.
11652            int sidx = subStr.lastIndexOf(prefix);
11653            if (sidx != -1) {
11654                subStr = subStr.substring(sidx + prefix.length());
11655                if (subStr != null) {
11656                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11657                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11658                    }
11659                    try {
11660                        idx = Integer.parseInt(subStr);
11661                        if (idx <= 1) {
11662                            idx++;
11663                        } else {
11664                            idx--;
11665                        }
11666                    } catch(NumberFormatException e) {
11667                    }
11668                }
11669            }
11670        }
11671        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11672        return prefix + idxStr;
11673    }
11674
11675    private File getNextCodePath(File targetDir, String packageName) {
11676        int suffix = 1;
11677        File result;
11678        do {
11679            result = new File(targetDir, packageName + "-" + suffix);
11680            suffix++;
11681        } while (result.exists());
11682        return result;
11683    }
11684
11685    // Utility method that returns the relative package path with respect
11686    // to the installation directory. Like say for /data/data/com.test-1.apk
11687    // string com.test-1 is returned.
11688    static String deriveCodePathName(String codePath) {
11689        if (codePath == null) {
11690            return null;
11691        }
11692        final File codeFile = new File(codePath);
11693        final String name = codeFile.getName();
11694        if (codeFile.isDirectory()) {
11695            return name;
11696        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11697            final int lastDot = name.lastIndexOf('.');
11698            return name.substring(0, lastDot);
11699        } else {
11700            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11701            return null;
11702        }
11703    }
11704
11705    class PackageInstalledInfo {
11706        String name;
11707        int uid;
11708        // The set of users that originally had this package installed.
11709        int[] origUsers;
11710        // The set of users that now have this package installed.
11711        int[] newUsers;
11712        PackageParser.Package pkg;
11713        int returnCode;
11714        String returnMsg;
11715        PackageRemovedInfo removedInfo;
11716
11717        public void setError(int code, String msg) {
11718            returnCode = code;
11719            returnMsg = msg;
11720            Slog.w(TAG, msg);
11721        }
11722
11723        public void setError(String msg, PackageParserException e) {
11724            returnCode = e.error;
11725            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11726            Slog.w(TAG, msg, e);
11727        }
11728
11729        public void setError(String msg, PackageManagerException e) {
11730            returnCode = e.error;
11731            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11732            Slog.w(TAG, msg, e);
11733        }
11734
11735        // In some error cases we want to convey more info back to the observer
11736        String origPackage;
11737        String origPermission;
11738    }
11739
11740    /*
11741     * Install a non-existing package.
11742     */
11743    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11744            UserHandle user, String installerPackageName, String volumeUuid,
11745            PackageInstalledInfo res) {
11746        // Remember this for later, in case we need to rollback this install
11747        String pkgName = pkg.packageName;
11748
11749        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11750        final boolean dataDirExists = Environment
11751                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11752        synchronized(mPackages) {
11753            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11754                // A package with the same name is already installed, though
11755                // it has been renamed to an older name.  The package we
11756                // are trying to install should be installed as an update to
11757                // the existing one, but that has not been requested, so bail.
11758                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11759                        + " without first uninstalling package running as "
11760                        + mSettings.mRenamedPackages.get(pkgName));
11761                return;
11762            }
11763            if (mPackages.containsKey(pkgName)) {
11764                // Don't allow installation over an existing package with the same name.
11765                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11766                        + " without first uninstalling.");
11767                return;
11768            }
11769        }
11770
11771        try {
11772            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11773                    System.currentTimeMillis(), user);
11774
11775            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11776            // delete the partially installed application. the data directory will have to be
11777            // restored if it was already existing
11778            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11779                // remove package from internal structures.  Note that we want deletePackageX to
11780                // delete the package data and cache directories that it created in
11781                // scanPackageLocked, unless those directories existed before we even tried to
11782                // install.
11783                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11784                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11785                                res.removedInfo, true);
11786            }
11787
11788        } catch (PackageManagerException e) {
11789            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11790        }
11791    }
11792
11793    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11794        // Can't rotate keys during boot or if sharedUser.
11795        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11796                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11797            return false;
11798        }
11799        // app is using upgradeKeySets; make sure all are valid
11800        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11801        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11802        for (int i = 0; i < upgradeKeySets.length; i++) {
11803            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11804                Slog.wtf(TAG, "Package "
11805                         + (oldPs.name != null ? oldPs.name : "<null>")
11806                         + " contains upgrade-key-set reference to unknown key-set: "
11807                         + upgradeKeySets[i]
11808                         + " reverting to signatures check.");
11809                return false;
11810            }
11811        }
11812        return true;
11813    }
11814
11815    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11816        // Upgrade keysets are being used.  Determine if new package has a superset of the
11817        // required keys.
11818        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11819        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11820        for (int i = 0; i < upgradeKeySets.length; i++) {
11821            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11822            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11823                return true;
11824            }
11825        }
11826        return false;
11827    }
11828
11829    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11830            UserHandle user, String installerPackageName, String volumeUuid,
11831            PackageInstalledInfo res) {
11832        final PackageParser.Package oldPackage;
11833        final String pkgName = pkg.packageName;
11834        final int[] allUsers;
11835        final boolean[] perUserInstalled;
11836
11837        // First find the old package info and check signatures
11838        synchronized(mPackages) {
11839            oldPackage = mPackages.get(pkgName);
11840            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11841            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11842            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11843                if(!checkUpgradeKeySetLP(ps, pkg)) {
11844                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11845                            "New package not signed by keys specified by upgrade-keysets: "
11846                            + pkgName);
11847                    return;
11848                }
11849            } else {
11850                // default to original signature matching
11851                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11852                    != PackageManager.SIGNATURE_MATCH) {
11853                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11854                            "New package has a different signature: " + pkgName);
11855                    return;
11856                }
11857            }
11858
11859            // In case of rollback, remember per-user/profile install state
11860            allUsers = sUserManager.getUserIds();
11861            perUserInstalled = new boolean[allUsers.length];
11862            for (int i = 0; i < allUsers.length; i++) {
11863                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11864            }
11865        }
11866
11867        boolean sysPkg = (isSystemApp(oldPackage));
11868        if (sysPkg) {
11869            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11870                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11871        } else {
11872            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11873                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11874        }
11875    }
11876
11877    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11878            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11879            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11880            String volumeUuid, PackageInstalledInfo res) {
11881        String pkgName = deletedPackage.packageName;
11882        boolean deletedPkg = true;
11883        boolean updatedSettings = false;
11884
11885        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11886                + deletedPackage);
11887        long origUpdateTime;
11888        if (pkg.mExtras != null) {
11889            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11890        } else {
11891            origUpdateTime = 0;
11892        }
11893
11894        // First delete the existing package while retaining the data directory
11895        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11896                res.removedInfo, true)) {
11897            // If the existing package wasn't successfully deleted
11898            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11899            deletedPkg = false;
11900        } else {
11901            // Successfully deleted the old package; proceed with replace.
11902
11903            // If deleted package lived in a container, give users a chance to
11904            // relinquish resources before killing.
11905            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11906                if (DEBUG_INSTALL) {
11907                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11908                }
11909                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11910                final ArrayList<String> pkgList = new ArrayList<String>(1);
11911                pkgList.add(deletedPackage.applicationInfo.packageName);
11912                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11913            }
11914
11915            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11916            try {
11917                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11918                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11919                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11920                        perUserInstalled, res, user);
11921                updatedSettings = true;
11922            } catch (PackageManagerException e) {
11923                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11924            }
11925        }
11926
11927        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11928            // remove package from internal structures.  Note that we want deletePackageX to
11929            // delete the package data and cache directories that it created in
11930            // scanPackageLocked, unless those directories existed before we even tried to
11931            // install.
11932            if(updatedSettings) {
11933                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11934                deletePackageLI(
11935                        pkgName, null, true, allUsers, perUserInstalled,
11936                        PackageManager.DELETE_KEEP_DATA,
11937                                res.removedInfo, true);
11938            }
11939            // Since we failed to install the new package we need to restore the old
11940            // package that we deleted.
11941            if (deletedPkg) {
11942                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11943                File restoreFile = new File(deletedPackage.codePath);
11944                // Parse old package
11945                boolean oldExternal = isExternal(deletedPackage);
11946                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11947                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11948                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11949                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11950                try {
11951                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11952                } catch (PackageManagerException e) {
11953                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11954                            + e.getMessage());
11955                    return;
11956                }
11957                // Restore of old package succeeded. Update permissions.
11958                // writer
11959                synchronized (mPackages) {
11960                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11961                            UPDATE_PERMISSIONS_ALL);
11962                    // can downgrade to reader
11963                    mSettings.writeLPr();
11964                }
11965                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11966            }
11967        }
11968    }
11969
11970    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11971            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11972            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11973            String volumeUuid, PackageInstalledInfo res) {
11974        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11975                + ", old=" + deletedPackage);
11976        boolean disabledSystem = false;
11977        boolean updatedSettings = false;
11978        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11979        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11980                != 0) {
11981            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11982        }
11983        String packageName = deletedPackage.packageName;
11984        if (packageName == null) {
11985            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11986                    "Attempt to delete null packageName.");
11987            return;
11988        }
11989        PackageParser.Package oldPkg;
11990        PackageSetting oldPkgSetting;
11991        // reader
11992        synchronized (mPackages) {
11993            oldPkg = mPackages.get(packageName);
11994            oldPkgSetting = mSettings.mPackages.get(packageName);
11995            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11996                    (oldPkgSetting == null)) {
11997                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11998                        "Couldn't find package:" + packageName + " information");
11999                return;
12000            }
12001        }
12002
12003        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12004
12005        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12006        res.removedInfo.removedPackage = packageName;
12007        // Remove existing system package
12008        removePackageLI(oldPkgSetting, true);
12009        // writer
12010        synchronized (mPackages) {
12011            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12012            if (!disabledSystem && deletedPackage != null) {
12013                // We didn't need to disable the .apk as a current system package,
12014                // which means we are replacing another update that is already
12015                // installed.  We need to make sure to delete the older one's .apk.
12016                res.removedInfo.args = createInstallArgsForExisting(0,
12017                        deletedPackage.applicationInfo.getCodePath(),
12018                        deletedPackage.applicationInfo.getResourcePath(),
12019                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12020            } else {
12021                res.removedInfo.args = null;
12022            }
12023        }
12024
12025        // Successfully disabled the old package. Now proceed with re-installation
12026        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12027
12028        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12029        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12030
12031        PackageParser.Package newPackage = null;
12032        try {
12033            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12034            if (newPackage.mExtras != null) {
12035                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12036                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12037                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12038
12039                // is the update attempting to change shared user? that isn't going to work...
12040                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12041                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12042                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12043                            + " to " + newPkgSetting.sharedUser);
12044                    updatedSettings = true;
12045                }
12046            }
12047
12048            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12049                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12050                        perUserInstalled, res, user);
12051                updatedSettings = true;
12052            }
12053
12054        } catch (PackageManagerException e) {
12055            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12056        }
12057
12058        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12059            // Re installation failed. Restore old information
12060            // Remove new pkg information
12061            if (newPackage != null) {
12062                removeInstalledPackageLI(newPackage, true);
12063            }
12064            // Add back the old system package
12065            try {
12066                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12067            } catch (PackageManagerException e) {
12068                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12069            }
12070            // Restore the old system information in Settings
12071            synchronized (mPackages) {
12072                if (disabledSystem) {
12073                    mSettings.enableSystemPackageLPw(packageName);
12074                }
12075                if (updatedSettings) {
12076                    mSettings.setInstallerPackageName(packageName,
12077                            oldPkgSetting.installerPackageName);
12078                }
12079                mSettings.writeLPr();
12080            }
12081        }
12082    }
12083
12084    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12085            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12086            UserHandle user) {
12087        String pkgName = newPackage.packageName;
12088        synchronized (mPackages) {
12089            //write settings. the installStatus will be incomplete at this stage.
12090            //note that the new package setting would have already been
12091            //added to mPackages. It hasn't been persisted yet.
12092            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12093            mSettings.writeLPr();
12094        }
12095
12096        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12097
12098        synchronized (mPackages) {
12099            updatePermissionsLPw(newPackage.packageName, newPackage,
12100                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12101                            ? UPDATE_PERMISSIONS_ALL : 0));
12102            // For system-bundled packages, we assume that installing an upgraded version
12103            // of the package implies that the user actually wants to run that new code,
12104            // so we enable the package.
12105            PackageSetting ps = mSettings.mPackages.get(pkgName);
12106            if (ps != null) {
12107                if (isSystemApp(newPackage)) {
12108                    // NB: implicit assumption that system package upgrades apply to all users
12109                    if (DEBUG_INSTALL) {
12110                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12111                    }
12112                    if (res.origUsers != null) {
12113                        for (int userHandle : res.origUsers) {
12114                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12115                                    userHandle, installerPackageName);
12116                        }
12117                    }
12118                    // Also convey the prior install/uninstall state
12119                    if (allUsers != null && perUserInstalled != null) {
12120                        for (int i = 0; i < allUsers.length; i++) {
12121                            if (DEBUG_INSTALL) {
12122                                Slog.d(TAG, "    user " + allUsers[i]
12123                                        + " => " + perUserInstalled[i]);
12124                            }
12125                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12126                        }
12127                        // these install state changes will be persisted in the
12128                        // upcoming call to mSettings.writeLPr().
12129                    }
12130                }
12131                // It's implied that when a user requests installation, they want the app to be
12132                // installed and enabled.
12133                int userId = user.getIdentifier();
12134                if (userId != UserHandle.USER_ALL) {
12135                    ps.setInstalled(true, userId);
12136                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12137                }
12138            }
12139            res.name = pkgName;
12140            res.uid = newPackage.applicationInfo.uid;
12141            res.pkg = newPackage;
12142            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12143            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12144            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12145            //to update install status
12146            mSettings.writeLPr();
12147        }
12148    }
12149
12150    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12151        final int installFlags = args.installFlags;
12152        final String installerPackageName = args.installerPackageName;
12153        final String volumeUuid = args.volumeUuid;
12154        final File tmpPackageFile = new File(args.getCodePath());
12155        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12156        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12157                || (args.volumeUuid != null));
12158        boolean replace = false;
12159        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12160        if (args.move != null) {
12161            // moving a complete application; perfom an initial scan on the new install location
12162            scanFlags |= SCAN_INITIAL;
12163        }
12164        // Result object to be returned
12165        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12166
12167        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12168        // Retrieve PackageSettings and parse package
12169        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12170                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12171                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12172        PackageParser pp = new PackageParser();
12173        pp.setSeparateProcesses(mSeparateProcesses);
12174        pp.setDisplayMetrics(mMetrics);
12175
12176        final PackageParser.Package pkg;
12177        try {
12178            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12179        } catch (PackageParserException e) {
12180            res.setError("Failed parse during installPackageLI", e);
12181            return;
12182        }
12183
12184        // Mark that we have an install time CPU ABI override.
12185        pkg.cpuAbiOverride = args.abiOverride;
12186
12187        String pkgName = res.name = pkg.packageName;
12188        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12189            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12190                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12191                return;
12192            }
12193        }
12194
12195        try {
12196            pp.collectCertificates(pkg, parseFlags);
12197            pp.collectManifestDigest(pkg);
12198        } catch (PackageParserException e) {
12199            res.setError("Failed collect during installPackageLI", e);
12200            return;
12201        }
12202
12203        /* If the installer passed in a manifest digest, compare it now. */
12204        if (args.manifestDigest != null) {
12205            if (DEBUG_INSTALL) {
12206                final String parsedManifest = pkg.manifestDigest == null ? "null"
12207                        : pkg.manifestDigest.toString();
12208                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12209                        + parsedManifest);
12210            }
12211
12212            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12213                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12214                return;
12215            }
12216        } else if (DEBUG_INSTALL) {
12217            final String parsedManifest = pkg.manifestDigest == null
12218                    ? "null" : pkg.manifestDigest.toString();
12219            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12220        }
12221
12222        // Get rid of all references to package scan path via parser.
12223        pp = null;
12224        String oldCodePath = null;
12225        boolean systemApp = false;
12226        synchronized (mPackages) {
12227            // Check if installing already existing package
12228            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12229                String oldName = mSettings.mRenamedPackages.get(pkgName);
12230                if (pkg.mOriginalPackages != null
12231                        && pkg.mOriginalPackages.contains(oldName)
12232                        && mPackages.containsKey(oldName)) {
12233                    // This package is derived from an original package,
12234                    // and this device has been updating from that original
12235                    // name.  We must continue using the original name, so
12236                    // rename the new package here.
12237                    pkg.setPackageName(oldName);
12238                    pkgName = pkg.packageName;
12239                    replace = true;
12240                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12241                            + oldName + " pkgName=" + pkgName);
12242                } else if (mPackages.containsKey(pkgName)) {
12243                    // This package, under its official name, already exists
12244                    // on the device; we should replace it.
12245                    replace = true;
12246                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12247                }
12248
12249                // Prevent apps opting out from runtime permissions
12250                if (replace) {
12251                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12252                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12253                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12254                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12255                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12256                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12257                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12258                                        + " doesn't support runtime permissions but the old"
12259                                        + " target SDK " + oldTargetSdk + " does.");
12260                        return;
12261                    }
12262                }
12263            }
12264
12265            PackageSetting ps = mSettings.mPackages.get(pkgName);
12266            if (ps != null) {
12267                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12268
12269                // Quick sanity check that we're signed correctly if updating;
12270                // we'll check this again later when scanning, but we want to
12271                // bail early here before tripping over redefined permissions.
12272                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12273                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12274                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12275                                + pkg.packageName + " upgrade keys do not match the "
12276                                + "previously installed version");
12277                        return;
12278                    }
12279                } else {
12280                    try {
12281                        verifySignaturesLP(ps, pkg);
12282                    } catch (PackageManagerException e) {
12283                        res.setError(e.error, e.getMessage());
12284                        return;
12285                    }
12286                }
12287
12288                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12289                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12290                    systemApp = (ps.pkg.applicationInfo.flags &
12291                            ApplicationInfo.FLAG_SYSTEM) != 0;
12292                }
12293                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12294            }
12295
12296            // Check whether the newly-scanned package wants to define an already-defined perm
12297            int N = pkg.permissions.size();
12298            for (int i = N-1; i >= 0; i--) {
12299                PackageParser.Permission perm = pkg.permissions.get(i);
12300                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12301                if (bp != null) {
12302                    // If the defining package is signed with our cert, it's okay.  This
12303                    // also includes the "updating the same package" case, of course.
12304                    // "updating same package" could also involve key-rotation.
12305                    final boolean sigsOk;
12306                    if (bp.sourcePackage.equals(pkg.packageName)
12307                            && (bp.packageSetting instanceof PackageSetting)
12308                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12309                                    scanFlags))) {
12310                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12311                    } else {
12312                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12313                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12314                    }
12315                    if (!sigsOk) {
12316                        // If the owning package is the system itself, we log but allow
12317                        // install to proceed; we fail the install on all other permission
12318                        // redefinitions.
12319                        if (!bp.sourcePackage.equals("android")) {
12320                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12321                                    + pkg.packageName + " attempting to redeclare permission "
12322                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12323                            res.origPermission = perm.info.name;
12324                            res.origPackage = bp.sourcePackage;
12325                            return;
12326                        } else {
12327                            Slog.w(TAG, "Package " + pkg.packageName
12328                                    + " attempting to redeclare system permission "
12329                                    + perm.info.name + "; ignoring new declaration");
12330                            pkg.permissions.remove(i);
12331                        }
12332                    }
12333                }
12334            }
12335
12336        }
12337
12338        if (systemApp && onExternal) {
12339            // Disable updates to system apps on sdcard
12340            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12341                    "Cannot install updates to system apps on sdcard");
12342            return;
12343        }
12344
12345        if (args.move != null) {
12346            // We did an in-place move, so dex is ready to roll
12347            scanFlags |= SCAN_NO_DEX;
12348            scanFlags |= SCAN_MOVE;
12349
12350            synchronized (mPackages) {
12351                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12352                if (ps == null) {
12353                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12354                            "Missing settings for moved package " + pkgName);
12355                }
12356
12357                // We moved the entire application as-is, so bring over the
12358                // previously derived ABI information.
12359                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12360                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12361            }
12362
12363        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12364            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12365            scanFlags |= SCAN_NO_DEX;
12366
12367            try {
12368                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12369                        true /* extract libs */);
12370            } catch (PackageManagerException pme) {
12371                Slog.e(TAG, "Error deriving application ABI", pme);
12372                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12373                return;
12374            }
12375
12376            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12377            int result = mPackageDexOptimizer
12378                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12379                            false /* defer */, false /* inclDependencies */);
12380            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12381                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12382                return;
12383            }
12384        }
12385
12386        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12387            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12388            return;
12389        }
12390
12391        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12392
12393        if (replace) {
12394            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12395                    installerPackageName, volumeUuid, res);
12396        } else {
12397            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12398                    args.user, installerPackageName, volumeUuid, res);
12399        }
12400        synchronized (mPackages) {
12401            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12402            if (ps != null) {
12403                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12404            }
12405        }
12406    }
12407
12408    private void startIntentFilterVerifications(int userId, boolean replacing,
12409            PackageParser.Package pkg) {
12410        if (mIntentFilterVerifierComponent == null) {
12411            Slog.w(TAG, "No IntentFilter verification will not be done as "
12412                    + "there is no IntentFilterVerifier available!");
12413            return;
12414        }
12415
12416        final int verifierUid = getPackageUid(
12417                mIntentFilterVerifierComponent.getPackageName(),
12418                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12419
12420        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12421        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12422        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12423        mHandler.sendMessage(msg);
12424    }
12425
12426    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12427            PackageParser.Package pkg) {
12428        int size = pkg.activities.size();
12429        if (size == 0) {
12430            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12431                    "No activity, so no need to verify any IntentFilter!");
12432            return;
12433        }
12434
12435        final boolean hasDomainURLs = hasDomainURLs(pkg);
12436        if (!hasDomainURLs) {
12437            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12438                    "No domain URLs, so no need to verify any IntentFilter!");
12439            return;
12440        }
12441
12442        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12443                + " if any IntentFilter from the " + size
12444                + " Activities needs verification ...");
12445
12446        int count = 0;
12447        final String packageName = pkg.packageName;
12448
12449        synchronized (mPackages) {
12450            // If this is a new install and we see that we've already run verification for this
12451            // package, we have nothing to do: it means the state was restored from backup.
12452            if (!replacing) {
12453                IntentFilterVerificationInfo ivi =
12454                        mSettings.getIntentFilterVerificationLPr(packageName);
12455                if (ivi != null) {
12456                    if (DEBUG_DOMAIN_VERIFICATION) {
12457                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12458                                + ivi.getStatusString());
12459                    }
12460                    return;
12461                }
12462            }
12463
12464            // If any filters need to be verified, then all need to be.
12465            boolean needToVerify = false;
12466            for (PackageParser.Activity a : pkg.activities) {
12467                for (ActivityIntentInfo filter : a.intents) {
12468                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12469                        if (DEBUG_DOMAIN_VERIFICATION) {
12470                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12471                        }
12472                        needToVerify = true;
12473                        break;
12474                    }
12475                }
12476            }
12477
12478            if (needToVerify) {
12479                final int verificationId = mIntentFilterVerificationToken++;
12480                for (PackageParser.Activity a : pkg.activities) {
12481                    for (ActivityIntentInfo filter : a.intents) {
12482                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12483                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12484                                    "Verification needed for IntentFilter:" + filter.toString());
12485                            mIntentFilterVerifier.addOneIntentFilterVerification(
12486                                    verifierUid, userId, verificationId, filter, packageName);
12487                            count++;
12488                        }
12489                    }
12490                }
12491            }
12492        }
12493
12494        if (count > 0) {
12495            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12496                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12497                    +  " for userId:" + userId);
12498            mIntentFilterVerifier.startVerifications(userId);
12499        } else {
12500            if (DEBUG_DOMAIN_VERIFICATION) {
12501                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12502            }
12503        }
12504    }
12505
12506    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12507        final ComponentName cn  = filter.activity.getComponentName();
12508        final String packageName = cn.getPackageName();
12509
12510        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12511                packageName);
12512        if (ivi == null) {
12513            return true;
12514        }
12515        int status = ivi.getStatus();
12516        switch (status) {
12517            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12518            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12519                return true;
12520
12521            default:
12522                // Nothing to do
12523                return false;
12524        }
12525    }
12526
12527    private static boolean isMultiArch(PackageSetting ps) {
12528        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12529    }
12530
12531    private static boolean isMultiArch(ApplicationInfo info) {
12532        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12533    }
12534
12535    private static boolean isExternal(PackageParser.Package pkg) {
12536        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12537    }
12538
12539    private static boolean isExternal(PackageSetting ps) {
12540        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12541    }
12542
12543    private static boolean isExternal(ApplicationInfo info) {
12544        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12545    }
12546
12547    private static boolean isSystemApp(PackageParser.Package pkg) {
12548        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12549    }
12550
12551    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12552        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12553    }
12554
12555    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12556        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12557    }
12558
12559    private static boolean isSystemApp(PackageSetting ps) {
12560        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12561    }
12562
12563    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12564        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12565    }
12566
12567    private int packageFlagsToInstallFlags(PackageSetting ps) {
12568        int installFlags = 0;
12569        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12570            // This existing package was an external ASEC install when we have
12571            // the external flag without a UUID
12572            installFlags |= PackageManager.INSTALL_EXTERNAL;
12573        }
12574        if (ps.isForwardLocked()) {
12575            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12576        }
12577        return installFlags;
12578    }
12579
12580    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12581        if (isExternal(pkg)) {
12582            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12583                return mSettings.getExternalVersion();
12584            } else {
12585                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12586            }
12587        } else {
12588            return mSettings.getInternalVersion();
12589        }
12590    }
12591
12592    private void deleteTempPackageFiles() {
12593        final FilenameFilter filter = new FilenameFilter() {
12594            public boolean accept(File dir, String name) {
12595                return name.startsWith("vmdl") && name.endsWith(".tmp");
12596            }
12597        };
12598        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12599            file.delete();
12600        }
12601    }
12602
12603    @Override
12604    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12605            int flags) {
12606        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12607                flags);
12608    }
12609
12610    @Override
12611    public void deletePackage(final String packageName,
12612            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12613        mContext.enforceCallingOrSelfPermission(
12614                android.Manifest.permission.DELETE_PACKAGES, null);
12615        Preconditions.checkNotNull(packageName);
12616        Preconditions.checkNotNull(observer);
12617        final int uid = Binder.getCallingUid();
12618        if (UserHandle.getUserId(uid) != userId) {
12619            mContext.enforceCallingPermission(
12620                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12621                    "deletePackage for user " + userId);
12622        }
12623        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12624            try {
12625                observer.onPackageDeleted(packageName,
12626                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12627            } catch (RemoteException re) {
12628            }
12629            return;
12630        }
12631
12632        boolean uninstallBlocked = false;
12633        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12634            int[] users = sUserManager.getUserIds();
12635            for (int i = 0; i < users.length; ++i) {
12636                if (getBlockUninstallForUser(packageName, users[i])) {
12637                    uninstallBlocked = true;
12638                    break;
12639                }
12640            }
12641        } else {
12642            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12643        }
12644        if (uninstallBlocked) {
12645            try {
12646                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12647                        null);
12648            } catch (RemoteException re) {
12649            }
12650            return;
12651        }
12652
12653        if (DEBUG_REMOVE) {
12654            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12655        }
12656        // Queue up an async operation since the package deletion may take a little while.
12657        mHandler.post(new Runnable() {
12658            public void run() {
12659                mHandler.removeCallbacks(this);
12660                final int returnCode = deletePackageX(packageName, userId, flags);
12661                if (observer != null) {
12662                    try {
12663                        observer.onPackageDeleted(packageName, returnCode, null);
12664                    } catch (RemoteException e) {
12665                        Log.i(TAG, "Observer no longer exists.");
12666                    } //end catch
12667                } //end if
12668            } //end run
12669        });
12670    }
12671
12672    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12673        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12674                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12675        try {
12676            if (dpm != null) {
12677                if (dpm.isDeviceOwner(packageName)) {
12678                    return true;
12679                }
12680                int[] users;
12681                if (userId == UserHandle.USER_ALL) {
12682                    users = sUserManager.getUserIds();
12683                } else {
12684                    users = new int[]{userId};
12685                }
12686                for (int i = 0; i < users.length; ++i) {
12687                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12688                        return true;
12689                    }
12690                }
12691            }
12692        } catch (RemoteException e) {
12693        }
12694        return false;
12695    }
12696
12697    /**
12698     *  This method is an internal method that could be get invoked either
12699     *  to delete an installed package or to clean up a failed installation.
12700     *  After deleting an installed package, a broadcast is sent to notify any
12701     *  listeners that the package has been installed. For cleaning up a failed
12702     *  installation, the broadcast is not necessary since the package's
12703     *  installation wouldn't have sent the initial broadcast either
12704     *  The key steps in deleting a package are
12705     *  deleting the package information in internal structures like mPackages,
12706     *  deleting the packages base directories through installd
12707     *  updating mSettings to reflect current status
12708     *  persisting settings for later use
12709     *  sending a broadcast if necessary
12710     */
12711    private int deletePackageX(String packageName, int userId, int flags) {
12712        final PackageRemovedInfo info = new PackageRemovedInfo();
12713        final boolean res;
12714
12715        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12716                ? UserHandle.ALL : new UserHandle(userId);
12717
12718        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12719            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12720            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12721        }
12722
12723        boolean removedForAllUsers = false;
12724        boolean systemUpdate = false;
12725
12726        // for the uninstall-updates case and restricted profiles, remember the per-
12727        // userhandle installed state
12728        int[] allUsers;
12729        boolean[] perUserInstalled;
12730        synchronized (mPackages) {
12731            PackageSetting ps = mSettings.mPackages.get(packageName);
12732            allUsers = sUserManager.getUserIds();
12733            perUserInstalled = new boolean[allUsers.length];
12734            for (int i = 0; i < allUsers.length; i++) {
12735                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12736            }
12737        }
12738
12739        synchronized (mInstallLock) {
12740            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12741            res = deletePackageLI(packageName, removeForUser,
12742                    true, allUsers, perUserInstalled,
12743                    flags | REMOVE_CHATTY, info, true);
12744            systemUpdate = info.isRemovedPackageSystemUpdate;
12745            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12746                removedForAllUsers = true;
12747            }
12748            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12749                    + " removedForAllUsers=" + removedForAllUsers);
12750        }
12751
12752        if (res) {
12753            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12754
12755            // If the removed package was a system update, the old system package
12756            // was re-enabled; we need to broadcast this information
12757            if (systemUpdate) {
12758                Bundle extras = new Bundle(1);
12759                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12760                        ? info.removedAppId : info.uid);
12761                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12762
12763                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12764                        extras, null, null, null);
12765                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12766                        extras, null, null, null);
12767                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12768                        null, packageName, null, null);
12769            }
12770        }
12771        // Force a gc here.
12772        Runtime.getRuntime().gc();
12773        // Delete the resources here after sending the broadcast to let
12774        // other processes clean up before deleting resources.
12775        if (info.args != null) {
12776            synchronized (mInstallLock) {
12777                info.args.doPostDeleteLI(true);
12778            }
12779        }
12780
12781        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12782    }
12783
12784    class PackageRemovedInfo {
12785        String removedPackage;
12786        int uid = -1;
12787        int removedAppId = -1;
12788        int[] removedUsers = null;
12789        boolean isRemovedPackageSystemUpdate = false;
12790        // Clean up resources deleted packages.
12791        InstallArgs args = null;
12792
12793        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12794            Bundle extras = new Bundle(1);
12795            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12796            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12797            if (replacing) {
12798                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12799            }
12800            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12801            if (removedPackage != null) {
12802                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12803                        extras, null, null, removedUsers);
12804                if (fullRemove && !replacing) {
12805                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12806                            extras, null, null, removedUsers);
12807                }
12808            }
12809            if (removedAppId >= 0) {
12810                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12811                        removedUsers);
12812            }
12813        }
12814    }
12815
12816    /*
12817     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12818     * flag is not set, the data directory is removed as well.
12819     * make sure this flag is set for partially installed apps. If not its meaningless to
12820     * delete a partially installed application.
12821     */
12822    private void removePackageDataLI(PackageSetting ps,
12823            int[] allUserHandles, boolean[] perUserInstalled,
12824            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12825        String packageName = ps.name;
12826        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12827        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12828        // Retrieve object to delete permissions for shared user later on
12829        final PackageSetting deletedPs;
12830        // reader
12831        synchronized (mPackages) {
12832            deletedPs = mSettings.mPackages.get(packageName);
12833            if (outInfo != null) {
12834                outInfo.removedPackage = packageName;
12835                outInfo.removedUsers = deletedPs != null
12836                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12837                        : null;
12838            }
12839        }
12840        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12841            removeDataDirsLI(ps.volumeUuid, packageName);
12842            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12843        }
12844        // writer
12845        synchronized (mPackages) {
12846            if (deletedPs != null) {
12847                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12848                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12849                    clearDefaultBrowserIfNeeded(packageName);
12850                    if (outInfo != null) {
12851                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12852                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12853                    }
12854                    updatePermissionsLPw(deletedPs.name, null, 0);
12855                    if (deletedPs.sharedUser != null) {
12856                        // Remove permissions associated with package. Since runtime
12857                        // permissions are per user we have to kill the removed package
12858                        // or packages running under the shared user of the removed
12859                        // package if revoking the permissions requested only by the removed
12860                        // package is successful and this causes a change in gids.
12861                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12862                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12863                                    userId);
12864                            if (userIdToKill == UserHandle.USER_ALL
12865                                    || userIdToKill >= UserHandle.USER_OWNER) {
12866                                // If gids changed for this user, kill all affected packages.
12867                                mHandler.post(new Runnable() {
12868                                    @Override
12869                                    public void run() {
12870                                        // This has to happen with no lock held.
12871                                        killApplication(deletedPs.name, deletedPs.appId,
12872                                                KILL_APP_REASON_GIDS_CHANGED);
12873                                    }
12874                                });
12875                                break;
12876                            }
12877                        }
12878                    }
12879                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12880                }
12881                // make sure to preserve per-user disabled state if this removal was just
12882                // a downgrade of a system app to the factory package
12883                if (allUserHandles != null && perUserInstalled != null) {
12884                    if (DEBUG_REMOVE) {
12885                        Slog.d(TAG, "Propagating install state across downgrade");
12886                    }
12887                    for (int i = 0; i < allUserHandles.length; i++) {
12888                        if (DEBUG_REMOVE) {
12889                            Slog.d(TAG, "    user " + allUserHandles[i]
12890                                    + " => " + perUserInstalled[i]);
12891                        }
12892                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12893                    }
12894                }
12895            }
12896            // can downgrade to reader
12897            if (writeSettings) {
12898                // Save settings now
12899                mSettings.writeLPr();
12900            }
12901        }
12902        if (outInfo != null) {
12903            // A user ID was deleted here. Go through all users and remove it
12904            // from KeyStore.
12905            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12906        }
12907    }
12908
12909    static boolean locationIsPrivileged(File path) {
12910        try {
12911            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12912                    .getCanonicalPath();
12913            return path.getCanonicalPath().startsWith(privilegedAppDir);
12914        } catch (IOException e) {
12915            Slog.e(TAG, "Unable to access code path " + path);
12916        }
12917        return false;
12918    }
12919
12920    /*
12921     * Tries to delete system package.
12922     */
12923    private boolean deleteSystemPackageLI(PackageSetting newPs,
12924            int[] allUserHandles, boolean[] perUserInstalled,
12925            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12926        final boolean applyUserRestrictions
12927                = (allUserHandles != null) && (perUserInstalled != null);
12928        PackageSetting disabledPs = null;
12929        // Confirm if the system package has been updated
12930        // An updated system app can be deleted. This will also have to restore
12931        // the system pkg from system partition
12932        // reader
12933        synchronized (mPackages) {
12934            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12935        }
12936        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12937                + " disabledPs=" + disabledPs);
12938        if (disabledPs == null) {
12939            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12940            return false;
12941        } else if (DEBUG_REMOVE) {
12942            Slog.d(TAG, "Deleting system pkg from data partition");
12943        }
12944        if (DEBUG_REMOVE) {
12945            if (applyUserRestrictions) {
12946                Slog.d(TAG, "Remembering install states:");
12947                for (int i = 0; i < allUserHandles.length; i++) {
12948                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12949                }
12950            }
12951        }
12952        // Delete the updated package
12953        outInfo.isRemovedPackageSystemUpdate = true;
12954        if (disabledPs.versionCode < newPs.versionCode) {
12955            // Delete data for downgrades
12956            flags &= ~PackageManager.DELETE_KEEP_DATA;
12957        } else {
12958            // Preserve data by setting flag
12959            flags |= PackageManager.DELETE_KEEP_DATA;
12960        }
12961        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12962                allUserHandles, perUserInstalled, outInfo, writeSettings);
12963        if (!ret) {
12964            return false;
12965        }
12966        // writer
12967        synchronized (mPackages) {
12968            // Reinstate the old system package
12969            mSettings.enableSystemPackageLPw(newPs.name);
12970            // Remove any native libraries from the upgraded package.
12971            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12972        }
12973        // Install the system package
12974        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12975        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12976        if (locationIsPrivileged(disabledPs.codePath)) {
12977            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12978        }
12979
12980        final PackageParser.Package newPkg;
12981        try {
12982            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12983        } catch (PackageManagerException e) {
12984            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12985            return false;
12986        }
12987
12988        // writer
12989        synchronized (mPackages) {
12990            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12991
12992            // Propagate the permissions state as we do not want to drop on the floor
12993            // runtime permissions. The update permissions method below will take
12994            // care of removing obsolete permissions and grant install permissions.
12995            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
12996            updatePermissionsLPw(newPkg.packageName, newPkg,
12997                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12998
12999            if (applyUserRestrictions) {
13000                if (DEBUG_REMOVE) {
13001                    Slog.d(TAG, "Propagating install state across reinstall");
13002                }
13003                for (int i = 0; i < allUserHandles.length; i++) {
13004                    if (DEBUG_REMOVE) {
13005                        Slog.d(TAG, "    user " + allUserHandles[i]
13006                                + " => " + perUserInstalled[i]);
13007                    }
13008                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13009
13010                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13011                }
13012                // Regardless of writeSettings we need to ensure that this restriction
13013                // state propagation is persisted
13014                mSettings.writeAllUsersPackageRestrictionsLPr();
13015            }
13016            // can downgrade to reader here
13017            if (writeSettings) {
13018                mSettings.writeLPr();
13019            }
13020        }
13021        return true;
13022    }
13023
13024    private boolean deleteInstalledPackageLI(PackageSetting ps,
13025            boolean deleteCodeAndResources, int flags,
13026            int[] allUserHandles, boolean[] perUserInstalled,
13027            PackageRemovedInfo outInfo, boolean writeSettings) {
13028        if (outInfo != null) {
13029            outInfo.uid = ps.appId;
13030        }
13031
13032        // Delete package data from internal structures and also remove data if flag is set
13033        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13034
13035        // Delete application code and resources
13036        if (deleteCodeAndResources && (outInfo != null)) {
13037            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13038                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13039            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13040        }
13041        return true;
13042    }
13043
13044    @Override
13045    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13046            int userId) {
13047        mContext.enforceCallingOrSelfPermission(
13048                android.Manifest.permission.DELETE_PACKAGES, null);
13049        synchronized (mPackages) {
13050            PackageSetting ps = mSettings.mPackages.get(packageName);
13051            if (ps == null) {
13052                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13053                return false;
13054            }
13055            if (!ps.getInstalled(userId)) {
13056                // Can't block uninstall for an app that is not installed or enabled.
13057                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13058                return false;
13059            }
13060            ps.setBlockUninstall(blockUninstall, userId);
13061            mSettings.writePackageRestrictionsLPr(userId);
13062        }
13063        return true;
13064    }
13065
13066    @Override
13067    public boolean getBlockUninstallForUser(String packageName, int userId) {
13068        synchronized (mPackages) {
13069            PackageSetting ps = mSettings.mPackages.get(packageName);
13070            if (ps == null) {
13071                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13072                return false;
13073            }
13074            return ps.getBlockUninstall(userId);
13075        }
13076    }
13077
13078    /*
13079     * This method handles package deletion in general
13080     */
13081    private boolean deletePackageLI(String packageName, UserHandle user,
13082            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13083            int flags, PackageRemovedInfo outInfo,
13084            boolean writeSettings) {
13085        if (packageName == null) {
13086            Slog.w(TAG, "Attempt to delete null packageName.");
13087            return false;
13088        }
13089        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13090        PackageSetting ps;
13091        boolean dataOnly = false;
13092        int removeUser = -1;
13093        int appId = -1;
13094        synchronized (mPackages) {
13095            ps = mSettings.mPackages.get(packageName);
13096            if (ps == null) {
13097                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13098                return false;
13099            }
13100            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13101                    && user.getIdentifier() != UserHandle.USER_ALL) {
13102                // The caller is asking that the package only be deleted for a single
13103                // user.  To do this, we just mark its uninstalled state and delete
13104                // its data.  If this is a system app, we only allow this to happen if
13105                // they have set the special DELETE_SYSTEM_APP which requests different
13106                // semantics than normal for uninstalling system apps.
13107                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13108                final int userId = user.getIdentifier();
13109                ps.setUserState(userId,
13110                        COMPONENT_ENABLED_STATE_DEFAULT,
13111                        false, //installed
13112                        true,  //stopped
13113                        true,  //notLaunched
13114                        false, //hidden
13115                        null, null, null,
13116                        false, // blockUninstall
13117                        ps.readUserState(userId).domainVerificationStatus, 0);
13118                if (!isSystemApp(ps)) {
13119                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13120                        // Other user still have this package installed, so all
13121                        // we need to do is clear this user's data and save that
13122                        // it is uninstalled.
13123                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13124                        removeUser = user.getIdentifier();
13125                        appId = ps.appId;
13126                        scheduleWritePackageRestrictionsLocked(removeUser);
13127                    } else {
13128                        // We need to set it back to 'installed' so the uninstall
13129                        // broadcasts will be sent correctly.
13130                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13131                        ps.setInstalled(true, user.getIdentifier());
13132                    }
13133                } else {
13134                    // This is a system app, so we assume that the
13135                    // other users still have this package installed, so all
13136                    // we need to do is clear this user's data and save that
13137                    // it is uninstalled.
13138                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13139                    removeUser = user.getIdentifier();
13140                    appId = ps.appId;
13141                    scheduleWritePackageRestrictionsLocked(removeUser);
13142                }
13143            }
13144        }
13145
13146        if (removeUser >= 0) {
13147            // From above, we determined that we are deleting this only
13148            // for a single user.  Continue the work here.
13149            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13150            if (outInfo != null) {
13151                outInfo.removedPackage = packageName;
13152                outInfo.removedAppId = appId;
13153                outInfo.removedUsers = new int[] {removeUser};
13154            }
13155            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13156            removeKeystoreDataIfNeeded(removeUser, appId);
13157            schedulePackageCleaning(packageName, removeUser, false);
13158            synchronized (mPackages) {
13159                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13160                    scheduleWritePackageRestrictionsLocked(removeUser);
13161                }
13162                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13163            }
13164            return true;
13165        }
13166
13167        if (dataOnly) {
13168            // Delete application data first
13169            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13170            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13171            return true;
13172        }
13173
13174        boolean ret = false;
13175        if (isSystemApp(ps)) {
13176            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13177            // When an updated system application is deleted we delete the existing resources as well and
13178            // fall back to existing code in system partition
13179            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13180                    flags, outInfo, writeSettings);
13181        } else {
13182            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13183            // Kill application pre-emptively especially for apps on sd.
13184            killApplication(packageName, ps.appId, "uninstall pkg");
13185            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13186                    allUserHandles, perUserInstalled,
13187                    outInfo, writeSettings);
13188        }
13189
13190        return ret;
13191    }
13192
13193    private final class ClearStorageConnection implements ServiceConnection {
13194        IMediaContainerService mContainerService;
13195
13196        @Override
13197        public void onServiceConnected(ComponentName name, IBinder service) {
13198            synchronized (this) {
13199                mContainerService = IMediaContainerService.Stub.asInterface(service);
13200                notifyAll();
13201            }
13202        }
13203
13204        @Override
13205        public void onServiceDisconnected(ComponentName name) {
13206        }
13207    }
13208
13209    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13210        final boolean mounted;
13211        if (Environment.isExternalStorageEmulated()) {
13212            mounted = true;
13213        } else {
13214            final String status = Environment.getExternalStorageState();
13215
13216            mounted = status.equals(Environment.MEDIA_MOUNTED)
13217                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13218        }
13219
13220        if (!mounted) {
13221            return;
13222        }
13223
13224        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13225        int[] users;
13226        if (userId == UserHandle.USER_ALL) {
13227            users = sUserManager.getUserIds();
13228        } else {
13229            users = new int[] { userId };
13230        }
13231        final ClearStorageConnection conn = new ClearStorageConnection();
13232        if (mContext.bindServiceAsUser(
13233                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13234            try {
13235                for (int curUser : users) {
13236                    long timeout = SystemClock.uptimeMillis() + 5000;
13237                    synchronized (conn) {
13238                        long now = SystemClock.uptimeMillis();
13239                        while (conn.mContainerService == null && now < timeout) {
13240                            try {
13241                                conn.wait(timeout - now);
13242                            } catch (InterruptedException e) {
13243                            }
13244                        }
13245                    }
13246                    if (conn.mContainerService == null) {
13247                        return;
13248                    }
13249
13250                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13251                    clearDirectory(conn.mContainerService,
13252                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13253                    if (allData) {
13254                        clearDirectory(conn.mContainerService,
13255                                userEnv.buildExternalStorageAppDataDirs(packageName));
13256                        clearDirectory(conn.mContainerService,
13257                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13258                    }
13259                }
13260            } finally {
13261                mContext.unbindService(conn);
13262            }
13263        }
13264    }
13265
13266    @Override
13267    public void clearApplicationUserData(final String packageName,
13268            final IPackageDataObserver observer, final int userId) {
13269        mContext.enforceCallingOrSelfPermission(
13270                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13271        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13272        // Queue up an async operation since the package deletion may take a little while.
13273        mHandler.post(new Runnable() {
13274            public void run() {
13275                mHandler.removeCallbacks(this);
13276                final boolean succeeded;
13277                synchronized (mInstallLock) {
13278                    succeeded = clearApplicationUserDataLI(packageName, userId);
13279                }
13280                clearExternalStorageDataSync(packageName, userId, true);
13281                if (succeeded) {
13282                    // invoke DeviceStorageMonitor's update method to clear any notifications
13283                    DeviceStorageMonitorInternal
13284                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13285                    if (dsm != null) {
13286                        dsm.checkMemory();
13287                    }
13288                }
13289                if(observer != null) {
13290                    try {
13291                        observer.onRemoveCompleted(packageName, succeeded);
13292                    } catch (RemoteException e) {
13293                        Log.i(TAG, "Observer no longer exists.");
13294                    }
13295                } //end if observer
13296            } //end run
13297        });
13298    }
13299
13300    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13301        if (packageName == null) {
13302            Slog.w(TAG, "Attempt to delete null packageName.");
13303            return false;
13304        }
13305
13306        // Try finding details about the requested package
13307        PackageParser.Package pkg;
13308        synchronized (mPackages) {
13309            pkg = mPackages.get(packageName);
13310            if (pkg == null) {
13311                final PackageSetting ps = mSettings.mPackages.get(packageName);
13312                if (ps != null) {
13313                    pkg = ps.pkg;
13314                }
13315            }
13316
13317            if (pkg == null) {
13318                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13319                return false;
13320            }
13321
13322            PackageSetting ps = (PackageSetting) pkg.mExtras;
13323            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13324        }
13325
13326        // Always delete data directories for package, even if we found no other
13327        // record of app. This helps users recover from UID mismatches without
13328        // resorting to a full data wipe.
13329        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13330        if (retCode < 0) {
13331            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13332            return false;
13333        }
13334
13335        final int appId = pkg.applicationInfo.uid;
13336        removeKeystoreDataIfNeeded(userId, appId);
13337
13338        // Create a native library symlink only if we have native libraries
13339        // and if the native libraries are 32 bit libraries. We do not provide
13340        // this symlink for 64 bit libraries.
13341        if (pkg.applicationInfo.primaryCpuAbi != null &&
13342                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13343            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13344            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13345                    nativeLibPath, userId) < 0) {
13346                Slog.w(TAG, "Failed linking native library dir");
13347                return false;
13348            }
13349        }
13350
13351        return true;
13352    }
13353
13354    /**
13355     * Reverts user permission state changes (permissions and flags) in
13356     * all packages for a given user.
13357     *
13358     * @param userId The device user for which to do a reset.
13359     */
13360    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13361        final int packageCount = mPackages.size();
13362        for (int i = 0; i < packageCount; i++) {
13363            PackageParser.Package pkg = mPackages.valueAt(i);
13364            PackageSetting ps = (PackageSetting) pkg.mExtras;
13365            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13366        }
13367    }
13368
13369    /**
13370     * Reverts user permission state changes (permissions and flags).
13371     *
13372     * @param ps The package for which to reset.
13373     * @param userId The device user for which to do a reset.
13374     */
13375    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13376            final PackageSetting ps, final int userId) {
13377        if (ps.pkg == null) {
13378            return;
13379        }
13380
13381        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13382                | FLAG_PERMISSION_USER_FIXED
13383                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13384
13385        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13386                | FLAG_PERMISSION_POLICY_FIXED;
13387
13388        boolean writeInstallPermissions = false;
13389        boolean writeRuntimePermissions = false;
13390
13391        final int permissionCount = ps.pkg.requestedPermissions.size();
13392        for (int i = 0; i < permissionCount; i++) {
13393            String permission = ps.pkg.requestedPermissions.get(i);
13394
13395            BasePermission bp = mSettings.mPermissions.get(permission);
13396            if (bp == null) {
13397                continue;
13398            }
13399
13400            // If shared user we just reset the state to which only this app contributed.
13401            if (ps.sharedUser != null) {
13402                boolean used = false;
13403                final int packageCount = ps.sharedUser.packages.size();
13404                for (int j = 0; j < packageCount; j++) {
13405                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13406                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13407                            && pkg.pkg.requestedPermissions.contains(permission)) {
13408                        used = true;
13409                        break;
13410                    }
13411                }
13412                if (used) {
13413                    continue;
13414                }
13415            }
13416
13417            PermissionsState permissionsState = ps.getPermissionsState();
13418
13419            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13420
13421            // Always clear the user settable flags.
13422            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13423                    bp.name) != null;
13424            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13425                if (hasInstallState) {
13426                    writeInstallPermissions = true;
13427                } else {
13428                    writeRuntimePermissions = true;
13429                }
13430            }
13431
13432            // Below is only runtime permission handling.
13433            if (!bp.isRuntime()) {
13434                continue;
13435            }
13436
13437            // Never clobber system or policy.
13438            if ((oldFlags & policyOrSystemFlags) != 0) {
13439                continue;
13440            }
13441
13442            // If this permission was granted by default, make sure it is.
13443            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13444                if (permissionsState.grantRuntimePermission(bp, userId)
13445                        != PERMISSION_OPERATION_FAILURE) {
13446                    writeRuntimePermissions = true;
13447                }
13448            } else {
13449                // Otherwise, reset the permission.
13450                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13451                switch (revokeResult) {
13452                    case PERMISSION_OPERATION_SUCCESS: {
13453                        writeRuntimePermissions = true;
13454                    } break;
13455
13456                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13457                        writeRuntimePermissions = true;
13458                        final int appId = ps.appId;
13459                        mHandler.post(new Runnable() {
13460                            @Override
13461                            public void run() {
13462                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13463                            }
13464                        });
13465                    } break;
13466                }
13467            }
13468        }
13469
13470        // Synchronously write as we are taking permissions away.
13471        if (writeRuntimePermissions) {
13472            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13473        }
13474
13475        // Synchronously write as we are taking permissions away.
13476        if (writeInstallPermissions) {
13477            mSettings.writeLPr();
13478        }
13479    }
13480
13481    /**
13482     * Remove entries from the keystore daemon. Will only remove it if the
13483     * {@code appId} is valid.
13484     */
13485    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13486        if (appId < 0) {
13487            return;
13488        }
13489
13490        final KeyStore keyStore = KeyStore.getInstance();
13491        if (keyStore != null) {
13492            if (userId == UserHandle.USER_ALL) {
13493                for (final int individual : sUserManager.getUserIds()) {
13494                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13495                }
13496            } else {
13497                keyStore.clearUid(UserHandle.getUid(userId, appId));
13498            }
13499        } else {
13500            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13501        }
13502    }
13503
13504    @Override
13505    public void deleteApplicationCacheFiles(final String packageName,
13506            final IPackageDataObserver observer) {
13507        mContext.enforceCallingOrSelfPermission(
13508                android.Manifest.permission.DELETE_CACHE_FILES, null);
13509        // Queue up an async operation since the package deletion may take a little while.
13510        final int userId = UserHandle.getCallingUserId();
13511        mHandler.post(new Runnable() {
13512            public void run() {
13513                mHandler.removeCallbacks(this);
13514                final boolean succeded;
13515                synchronized (mInstallLock) {
13516                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13517                }
13518                clearExternalStorageDataSync(packageName, userId, false);
13519                if (observer != null) {
13520                    try {
13521                        observer.onRemoveCompleted(packageName, succeded);
13522                    } catch (RemoteException e) {
13523                        Log.i(TAG, "Observer no longer exists.");
13524                    }
13525                } //end if observer
13526            } //end run
13527        });
13528    }
13529
13530    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13531        if (packageName == null) {
13532            Slog.w(TAG, "Attempt to delete null packageName.");
13533            return false;
13534        }
13535        PackageParser.Package p;
13536        synchronized (mPackages) {
13537            p = mPackages.get(packageName);
13538        }
13539        if (p == null) {
13540            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13541            return false;
13542        }
13543        final ApplicationInfo applicationInfo = p.applicationInfo;
13544        if (applicationInfo == null) {
13545            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13546            return false;
13547        }
13548        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13549        if (retCode < 0) {
13550            Slog.w(TAG, "Couldn't remove cache files for package: "
13551                       + packageName + " u" + userId);
13552            return false;
13553        }
13554        return true;
13555    }
13556
13557    @Override
13558    public void getPackageSizeInfo(final String packageName, int userHandle,
13559            final IPackageStatsObserver observer) {
13560        mContext.enforceCallingOrSelfPermission(
13561                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13562        if (packageName == null) {
13563            throw new IllegalArgumentException("Attempt to get size of null packageName");
13564        }
13565
13566        PackageStats stats = new PackageStats(packageName, userHandle);
13567
13568        /*
13569         * Queue up an async operation since the package measurement may take a
13570         * little while.
13571         */
13572        Message msg = mHandler.obtainMessage(INIT_COPY);
13573        msg.obj = new MeasureParams(stats, observer);
13574        mHandler.sendMessage(msg);
13575    }
13576
13577    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13578            PackageStats pStats) {
13579        if (packageName == null) {
13580            Slog.w(TAG, "Attempt to get size of null packageName.");
13581            return false;
13582        }
13583        PackageParser.Package p;
13584        boolean dataOnly = false;
13585        String libDirRoot = null;
13586        String asecPath = null;
13587        PackageSetting ps = null;
13588        synchronized (mPackages) {
13589            p = mPackages.get(packageName);
13590            ps = mSettings.mPackages.get(packageName);
13591            if(p == null) {
13592                dataOnly = true;
13593                if((ps == null) || (ps.pkg == null)) {
13594                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13595                    return false;
13596                }
13597                p = ps.pkg;
13598            }
13599            if (ps != null) {
13600                libDirRoot = ps.legacyNativeLibraryPathString;
13601            }
13602            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13603                final long token = Binder.clearCallingIdentity();
13604                try {
13605                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13606                    if (secureContainerId != null) {
13607                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13608                    }
13609                } finally {
13610                    Binder.restoreCallingIdentity(token);
13611                }
13612            }
13613        }
13614        String publicSrcDir = null;
13615        if(!dataOnly) {
13616            final ApplicationInfo applicationInfo = p.applicationInfo;
13617            if (applicationInfo == null) {
13618                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13619                return false;
13620            }
13621            if (p.isForwardLocked()) {
13622                publicSrcDir = applicationInfo.getBaseResourcePath();
13623            }
13624        }
13625        // TODO: extend to measure size of split APKs
13626        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13627        // not just the first level.
13628        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13629        // just the primary.
13630        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13631        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13632                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13633        if (res < 0) {
13634            return false;
13635        }
13636
13637        // Fix-up for forward-locked applications in ASEC containers.
13638        if (!isExternal(p)) {
13639            pStats.codeSize += pStats.externalCodeSize;
13640            pStats.externalCodeSize = 0L;
13641        }
13642
13643        return true;
13644    }
13645
13646
13647    @Override
13648    public void addPackageToPreferred(String packageName) {
13649        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13650    }
13651
13652    @Override
13653    public void removePackageFromPreferred(String packageName) {
13654        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13655    }
13656
13657    @Override
13658    public List<PackageInfo> getPreferredPackages(int flags) {
13659        return new ArrayList<PackageInfo>();
13660    }
13661
13662    private int getUidTargetSdkVersionLockedLPr(int uid) {
13663        Object obj = mSettings.getUserIdLPr(uid);
13664        if (obj instanceof SharedUserSetting) {
13665            final SharedUserSetting sus = (SharedUserSetting) obj;
13666            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13667            final Iterator<PackageSetting> it = sus.packages.iterator();
13668            while (it.hasNext()) {
13669                final PackageSetting ps = it.next();
13670                if (ps.pkg != null) {
13671                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13672                    if (v < vers) vers = v;
13673                }
13674            }
13675            return vers;
13676        } else if (obj instanceof PackageSetting) {
13677            final PackageSetting ps = (PackageSetting) obj;
13678            if (ps.pkg != null) {
13679                return ps.pkg.applicationInfo.targetSdkVersion;
13680            }
13681        }
13682        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13683    }
13684
13685    @Override
13686    public void addPreferredActivity(IntentFilter filter, int match,
13687            ComponentName[] set, ComponentName activity, int userId) {
13688        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13689                "Adding preferred");
13690    }
13691
13692    private void addPreferredActivityInternal(IntentFilter filter, int match,
13693            ComponentName[] set, ComponentName activity, boolean always, int userId,
13694            String opname) {
13695        // writer
13696        int callingUid = Binder.getCallingUid();
13697        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13698        if (filter.countActions() == 0) {
13699            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13700            return;
13701        }
13702        synchronized (mPackages) {
13703            if (mContext.checkCallingOrSelfPermission(
13704                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13705                    != PackageManager.PERMISSION_GRANTED) {
13706                if (getUidTargetSdkVersionLockedLPr(callingUid)
13707                        < Build.VERSION_CODES.FROYO) {
13708                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13709                            + callingUid);
13710                    return;
13711                }
13712                mContext.enforceCallingOrSelfPermission(
13713                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13714            }
13715
13716            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13717            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13718                    + userId + ":");
13719            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13720            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13721            scheduleWritePackageRestrictionsLocked(userId);
13722        }
13723    }
13724
13725    @Override
13726    public void replacePreferredActivity(IntentFilter filter, int match,
13727            ComponentName[] set, ComponentName activity, int userId) {
13728        if (filter.countActions() != 1) {
13729            throw new IllegalArgumentException(
13730                    "replacePreferredActivity expects filter to have only 1 action.");
13731        }
13732        if (filter.countDataAuthorities() != 0
13733                || filter.countDataPaths() != 0
13734                || filter.countDataSchemes() > 1
13735                || filter.countDataTypes() != 0) {
13736            throw new IllegalArgumentException(
13737                    "replacePreferredActivity expects filter to have no data authorities, " +
13738                    "paths, or types; and at most one scheme.");
13739        }
13740
13741        final int callingUid = Binder.getCallingUid();
13742        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13743        synchronized (mPackages) {
13744            if (mContext.checkCallingOrSelfPermission(
13745                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13746                    != PackageManager.PERMISSION_GRANTED) {
13747                if (getUidTargetSdkVersionLockedLPr(callingUid)
13748                        < Build.VERSION_CODES.FROYO) {
13749                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13750                            + Binder.getCallingUid());
13751                    return;
13752                }
13753                mContext.enforceCallingOrSelfPermission(
13754                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13755            }
13756
13757            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13758            if (pir != null) {
13759                // Get all of the existing entries that exactly match this filter.
13760                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13761                if (existing != null && existing.size() == 1) {
13762                    PreferredActivity cur = existing.get(0);
13763                    if (DEBUG_PREFERRED) {
13764                        Slog.i(TAG, "Checking replace of preferred:");
13765                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13766                        if (!cur.mPref.mAlways) {
13767                            Slog.i(TAG, "  -- CUR; not mAlways!");
13768                        } else {
13769                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13770                            Slog.i(TAG, "  -- CUR: mSet="
13771                                    + Arrays.toString(cur.mPref.mSetComponents));
13772                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13773                            Slog.i(TAG, "  -- NEW: mMatch="
13774                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13775                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13776                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13777                        }
13778                    }
13779                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13780                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13781                            && cur.mPref.sameSet(set)) {
13782                        // Setting the preferred activity to what it happens to be already
13783                        if (DEBUG_PREFERRED) {
13784                            Slog.i(TAG, "Replacing with same preferred activity "
13785                                    + cur.mPref.mShortComponent + " for user "
13786                                    + userId + ":");
13787                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13788                        }
13789                        return;
13790                    }
13791                }
13792
13793                if (existing != null) {
13794                    if (DEBUG_PREFERRED) {
13795                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13796                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13797                    }
13798                    for (int i = 0; i < existing.size(); i++) {
13799                        PreferredActivity pa = existing.get(i);
13800                        if (DEBUG_PREFERRED) {
13801                            Slog.i(TAG, "Removing existing preferred activity "
13802                                    + pa.mPref.mComponent + ":");
13803                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13804                        }
13805                        pir.removeFilter(pa);
13806                    }
13807                }
13808            }
13809            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13810                    "Replacing preferred");
13811        }
13812    }
13813
13814    @Override
13815    public void clearPackagePreferredActivities(String packageName) {
13816        final int uid = Binder.getCallingUid();
13817        // writer
13818        synchronized (mPackages) {
13819            PackageParser.Package pkg = mPackages.get(packageName);
13820            if (pkg == null || pkg.applicationInfo.uid != uid) {
13821                if (mContext.checkCallingOrSelfPermission(
13822                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13823                        != PackageManager.PERMISSION_GRANTED) {
13824                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13825                            < Build.VERSION_CODES.FROYO) {
13826                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13827                                + Binder.getCallingUid());
13828                        return;
13829                    }
13830                    mContext.enforceCallingOrSelfPermission(
13831                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13832                }
13833            }
13834
13835            int user = UserHandle.getCallingUserId();
13836            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13837                scheduleWritePackageRestrictionsLocked(user);
13838            }
13839        }
13840    }
13841
13842    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13843    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13844        ArrayList<PreferredActivity> removed = null;
13845        boolean changed = false;
13846        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13847            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13848            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13849            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13850                continue;
13851            }
13852            Iterator<PreferredActivity> it = pir.filterIterator();
13853            while (it.hasNext()) {
13854                PreferredActivity pa = it.next();
13855                // Mark entry for removal only if it matches the package name
13856                // and the entry is of type "always".
13857                if (packageName == null ||
13858                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13859                                && pa.mPref.mAlways)) {
13860                    if (removed == null) {
13861                        removed = new ArrayList<PreferredActivity>();
13862                    }
13863                    removed.add(pa);
13864                }
13865            }
13866            if (removed != null) {
13867                for (int j=0; j<removed.size(); j++) {
13868                    PreferredActivity pa = removed.get(j);
13869                    pir.removeFilter(pa);
13870                }
13871                changed = true;
13872            }
13873        }
13874        return changed;
13875    }
13876
13877    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13878    private void clearIntentFilterVerificationsLPw(int userId) {
13879        final int packageCount = mPackages.size();
13880        for (int i = 0; i < packageCount; i++) {
13881            PackageParser.Package pkg = mPackages.valueAt(i);
13882            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13883        }
13884    }
13885
13886    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13887    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13888        if (userId == UserHandle.USER_ALL) {
13889            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13890                    sUserManager.getUserIds())) {
13891                for (int oneUserId : sUserManager.getUserIds()) {
13892                    scheduleWritePackageRestrictionsLocked(oneUserId);
13893                }
13894            }
13895        } else {
13896            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13897                scheduleWritePackageRestrictionsLocked(userId);
13898            }
13899        }
13900    }
13901
13902    void clearDefaultBrowserIfNeeded(String packageName) {
13903        for (int oneUserId : sUserManager.getUserIds()) {
13904            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13905            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13906            if (packageName.equals(defaultBrowserPackageName)) {
13907                setDefaultBrowserPackageName(null, oneUserId);
13908            }
13909        }
13910    }
13911
13912    @Override
13913    public void resetApplicationPreferences(int userId) {
13914        mContext.enforceCallingOrSelfPermission(
13915                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13916        // writer
13917        synchronized (mPackages) {
13918            final long identity = Binder.clearCallingIdentity();
13919            try {
13920                clearPackagePreferredActivitiesLPw(null, userId);
13921                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13922                // TODO: We have to reset the default SMS and Phone. This requires
13923                // significant refactoring to keep all default apps in the package
13924                // manager (cleaner but more work) or have the services provide
13925                // callbacks to the package manager to request a default app reset.
13926                applyFactoryDefaultBrowserLPw(userId);
13927                clearIntentFilterVerificationsLPw(userId);
13928                primeDomainVerificationsLPw(userId);
13929                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13930                scheduleWritePackageRestrictionsLocked(userId);
13931            } finally {
13932                Binder.restoreCallingIdentity(identity);
13933            }
13934        }
13935    }
13936
13937    @Override
13938    public int getPreferredActivities(List<IntentFilter> outFilters,
13939            List<ComponentName> outActivities, String packageName) {
13940
13941        int num = 0;
13942        final int userId = UserHandle.getCallingUserId();
13943        // reader
13944        synchronized (mPackages) {
13945            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13946            if (pir != null) {
13947                final Iterator<PreferredActivity> it = pir.filterIterator();
13948                while (it.hasNext()) {
13949                    final PreferredActivity pa = it.next();
13950                    if (packageName == null
13951                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13952                                    && pa.mPref.mAlways)) {
13953                        if (outFilters != null) {
13954                            outFilters.add(new IntentFilter(pa));
13955                        }
13956                        if (outActivities != null) {
13957                            outActivities.add(pa.mPref.mComponent);
13958                        }
13959                    }
13960                }
13961            }
13962        }
13963
13964        return num;
13965    }
13966
13967    @Override
13968    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13969            int userId) {
13970        int callingUid = Binder.getCallingUid();
13971        if (callingUid != Process.SYSTEM_UID) {
13972            throw new SecurityException(
13973                    "addPersistentPreferredActivity can only be run by the system");
13974        }
13975        if (filter.countActions() == 0) {
13976            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13977            return;
13978        }
13979        synchronized (mPackages) {
13980            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13981                    " :");
13982            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13983            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13984                    new PersistentPreferredActivity(filter, activity));
13985            scheduleWritePackageRestrictionsLocked(userId);
13986        }
13987    }
13988
13989    @Override
13990    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13991        int callingUid = Binder.getCallingUid();
13992        if (callingUid != Process.SYSTEM_UID) {
13993            throw new SecurityException(
13994                    "clearPackagePersistentPreferredActivities can only be run by the system");
13995        }
13996        ArrayList<PersistentPreferredActivity> removed = null;
13997        boolean changed = false;
13998        synchronized (mPackages) {
13999            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14000                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14001                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14002                        .valueAt(i);
14003                if (userId != thisUserId) {
14004                    continue;
14005                }
14006                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14007                while (it.hasNext()) {
14008                    PersistentPreferredActivity ppa = it.next();
14009                    // Mark entry for removal only if it matches the package name.
14010                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14011                        if (removed == null) {
14012                            removed = new ArrayList<PersistentPreferredActivity>();
14013                        }
14014                        removed.add(ppa);
14015                    }
14016                }
14017                if (removed != null) {
14018                    for (int j=0; j<removed.size(); j++) {
14019                        PersistentPreferredActivity ppa = removed.get(j);
14020                        ppir.removeFilter(ppa);
14021                    }
14022                    changed = true;
14023                }
14024            }
14025
14026            if (changed) {
14027                scheduleWritePackageRestrictionsLocked(userId);
14028            }
14029        }
14030    }
14031
14032    /**
14033     * Common machinery for picking apart a restored XML blob and passing
14034     * it to a caller-supplied functor to be applied to the running system.
14035     */
14036    private void restoreFromXml(XmlPullParser parser, int userId,
14037            String expectedStartTag, BlobXmlRestorer functor)
14038            throws IOException, XmlPullParserException {
14039        int type;
14040        while ((type = parser.next()) != XmlPullParser.START_TAG
14041                && type != XmlPullParser.END_DOCUMENT) {
14042        }
14043        if (type != XmlPullParser.START_TAG) {
14044            // oops didn't find a start tag?!
14045            if (DEBUG_BACKUP) {
14046                Slog.e(TAG, "Didn't find start tag during restore");
14047            }
14048            return;
14049        }
14050
14051        // this is supposed to be TAG_PREFERRED_BACKUP
14052        if (!expectedStartTag.equals(parser.getName())) {
14053            if (DEBUG_BACKUP) {
14054                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14055            }
14056            return;
14057        }
14058
14059        // skip interfering stuff, then we're aligned with the backing implementation
14060        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14061        functor.apply(parser, userId);
14062    }
14063
14064    private interface BlobXmlRestorer {
14065        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14066    }
14067
14068    /**
14069     * Non-Binder method, support for the backup/restore mechanism: write the
14070     * full set of preferred activities in its canonical XML format.  Returns the
14071     * XML output as a byte array, or null if there is none.
14072     */
14073    @Override
14074    public byte[] getPreferredActivityBackup(int userId) {
14075        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14076            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14077        }
14078
14079        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14080        try {
14081            final XmlSerializer serializer = new FastXmlSerializer();
14082            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14083            serializer.startDocument(null, true);
14084            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14085
14086            synchronized (mPackages) {
14087                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14088            }
14089
14090            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14091            serializer.endDocument();
14092            serializer.flush();
14093        } catch (Exception e) {
14094            if (DEBUG_BACKUP) {
14095                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14096            }
14097            return null;
14098        }
14099
14100        return dataStream.toByteArray();
14101    }
14102
14103    @Override
14104    public void restorePreferredActivities(byte[] backup, int userId) {
14105        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14106            throw new SecurityException("Only the system may call restorePreferredActivities()");
14107        }
14108
14109        try {
14110            final XmlPullParser parser = Xml.newPullParser();
14111            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14112            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14113                    new BlobXmlRestorer() {
14114                        @Override
14115                        public void apply(XmlPullParser parser, int userId)
14116                                throws XmlPullParserException, IOException {
14117                            synchronized (mPackages) {
14118                                mSettings.readPreferredActivitiesLPw(parser, userId);
14119                            }
14120                        }
14121                    } );
14122        } catch (Exception e) {
14123            if (DEBUG_BACKUP) {
14124                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14125            }
14126        }
14127    }
14128
14129    /**
14130     * Non-Binder method, support for the backup/restore mechanism: write the
14131     * default browser (etc) settings in its canonical XML format.  Returns the default
14132     * browser XML representation as a byte array, or null if there is none.
14133     */
14134    @Override
14135    public byte[] getDefaultAppsBackup(int userId) {
14136        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14137            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14138        }
14139
14140        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14141        try {
14142            final XmlSerializer serializer = new FastXmlSerializer();
14143            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14144            serializer.startDocument(null, true);
14145            serializer.startTag(null, TAG_DEFAULT_APPS);
14146
14147            synchronized (mPackages) {
14148                mSettings.writeDefaultAppsLPr(serializer, userId);
14149            }
14150
14151            serializer.endTag(null, TAG_DEFAULT_APPS);
14152            serializer.endDocument();
14153            serializer.flush();
14154        } catch (Exception e) {
14155            if (DEBUG_BACKUP) {
14156                Slog.e(TAG, "Unable to write default apps for backup", e);
14157            }
14158            return null;
14159        }
14160
14161        return dataStream.toByteArray();
14162    }
14163
14164    @Override
14165    public void restoreDefaultApps(byte[] backup, int userId) {
14166        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14167            throw new SecurityException("Only the system may call restoreDefaultApps()");
14168        }
14169
14170        try {
14171            final XmlPullParser parser = Xml.newPullParser();
14172            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14173            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14174                    new BlobXmlRestorer() {
14175                        @Override
14176                        public void apply(XmlPullParser parser, int userId)
14177                                throws XmlPullParserException, IOException {
14178                            synchronized (mPackages) {
14179                                mSettings.readDefaultAppsLPw(parser, userId);
14180                            }
14181                        }
14182                    } );
14183        } catch (Exception e) {
14184            if (DEBUG_BACKUP) {
14185                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14186            }
14187        }
14188    }
14189
14190    @Override
14191    public byte[] getIntentFilterVerificationBackup(int userId) {
14192        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14193            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14194        }
14195
14196        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14197        try {
14198            final XmlSerializer serializer = new FastXmlSerializer();
14199            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14200            serializer.startDocument(null, true);
14201            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14202
14203            synchronized (mPackages) {
14204                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14205            }
14206
14207            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14208            serializer.endDocument();
14209            serializer.flush();
14210        } catch (Exception e) {
14211            if (DEBUG_BACKUP) {
14212                Slog.e(TAG, "Unable to write default apps for backup", e);
14213            }
14214            return null;
14215        }
14216
14217        return dataStream.toByteArray();
14218    }
14219
14220    @Override
14221    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14222        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14223            throw new SecurityException("Only the system may call restorePreferredActivities()");
14224        }
14225
14226        try {
14227            final XmlPullParser parser = Xml.newPullParser();
14228            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14229            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14230                    new BlobXmlRestorer() {
14231                        @Override
14232                        public void apply(XmlPullParser parser, int userId)
14233                                throws XmlPullParserException, IOException {
14234                            synchronized (mPackages) {
14235                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14236                                mSettings.writeLPr();
14237                            }
14238                        }
14239                    } );
14240        } catch (Exception e) {
14241            if (DEBUG_BACKUP) {
14242                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14243            }
14244        }
14245    }
14246
14247    @Override
14248    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14249            int sourceUserId, int targetUserId, int flags) {
14250        mContext.enforceCallingOrSelfPermission(
14251                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14252        int callingUid = Binder.getCallingUid();
14253        enforceOwnerRights(ownerPackage, callingUid);
14254        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14255        if (intentFilter.countActions() == 0) {
14256            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14257            return;
14258        }
14259        synchronized (mPackages) {
14260            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14261                    ownerPackage, targetUserId, flags);
14262            CrossProfileIntentResolver resolver =
14263                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14264            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14265            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14266            if (existing != null) {
14267                int size = existing.size();
14268                for (int i = 0; i < size; i++) {
14269                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14270                        return;
14271                    }
14272                }
14273            }
14274            resolver.addFilter(newFilter);
14275            scheduleWritePackageRestrictionsLocked(sourceUserId);
14276        }
14277    }
14278
14279    @Override
14280    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14281        mContext.enforceCallingOrSelfPermission(
14282                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14283        int callingUid = Binder.getCallingUid();
14284        enforceOwnerRights(ownerPackage, callingUid);
14285        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14286        synchronized (mPackages) {
14287            CrossProfileIntentResolver resolver =
14288                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14289            ArraySet<CrossProfileIntentFilter> set =
14290                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14291            for (CrossProfileIntentFilter filter : set) {
14292                if (filter.getOwnerPackage().equals(ownerPackage)) {
14293                    resolver.removeFilter(filter);
14294                }
14295            }
14296            scheduleWritePackageRestrictionsLocked(sourceUserId);
14297        }
14298    }
14299
14300    // Enforcing that callingUid is owning pkg on userId
14301    private void enforceOwnerRights(String pkg, int callingUid) {
14302        // The system owns everything.
14303        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14304            return;
14305        }
14306        int callingUserId = UserHandle.getUserId(callingUid);
14307        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14308        if (pi == null) {
14309            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14310                    + callingUserId);
14311        }
14312        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14313            throw new SecurityException("Calling uid " + callingUid
14314                    + " does not own package " + pkg);
14315        }
14316    }
14317
14318    @Override
14319    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14320        Intent intent = new Intent(Intent.ACTION_MAIN);
14321        intent.addCategory(Intent.CATEGORY_HOME);
14322
14323        final int callingUserId = UserHandle.getCallingUserId();
14324        List<ResolveInfo> list = queryIntentActivities(intent, null,
14325                PackageManager.GET_META_DATA, callingUserId);
14326        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14327                true, false, false, callingUserId);
14328
14329        allHomeCandidates.clear();
14330        if (list != null) {
14331            for (ResolveInfo ri : list) {
14332                allHomeCandidates.add(ri);
14333            }
14334        }
14335        return (preferred == null || preferred.activityInfo == null)
14336                ? null
14337                : new ComponentName(preferred.activityInfo.packageName,
14338                        preferred.activityInfo.name);
14339    }
14340
14341    @Override
14342    public void setApplicationEnabledSetting(String appPackageName,
14343            int newState, int flags, int userId, String callingPackage) {
14344        if (!sUserManager.exists(userId)) return;
14345        if (callingPackage == null) {
14346            callingPackage = Integer.toString(Binder.getCallingUid());
14347        }
14348        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14349    }
14350
14351    @Override
14352    public void setComponentEnabledSetting(ComponentName componentName,
14353            int newState, int flags, int userId) {
14354        if (!sUserManager.exists(userId)) return;
14355        setEnabledSetting(componentName.getPackageName(),
14356                componentName.getClassName(), newState, flags, userId, null);
14357    }
14358
14359    private void setEnabledSetting(final String packageName, String className, int newState,
14360            final int flags, int userId, String callingPackage) {
14361        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14362              || newState == COMPONENT_ENABLED_STATE_ENABLED
14363              || newState == COMPONENT_ENABLED_STATE_DISABLED
14364              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14365              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14366            throw new IllegalArgumentException("Invalid new component state: "
14367                    + newState);
14368        }
14369        PackageSetting pkgSetting;
14370        final int uid = Binder.getCallingUid();
14371        final int permission = mContext.checkCallingOrSelfPermission(
14372                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14373        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14374        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14375        boolean sendNow = false;
14376        boolean isApp = (className == null);
14377        String componentName = isApp ? packageName : className;
14378        int packageUid = -1;
14379        ArrayList<String> components;
14380
14381        // writer
14382        synchronized (mPackages) {
14383            pkgSetting = mSettings.mPackages.get(packageName);
14384            if (pkgSetting == null) {
14385                if (className == null) {
14386                    throw new IllegalArgumentException(
14387                            "Unknown package: " + packageName);
14388                }
14389                throw new IllegalArgumentException(
14390                        "Unknown component: " + packageName
14391                        + "/" + className);
14392            }
14393            // Allow root and verify that userId is not being specified by a different user
14394            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14395                throw new SecurityException(
14396                        "Permission Denial: attempt to change component state from pid="
14397                        + Binder.getCallingPid()
14398                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14399            }
14400            if (className == null) {
14401                // We're dealing with an application/package level state change
14402                if (pkgSetting.getEnabled(userId) == newState) {
14403                    // Nothing to do
14404                    return;
14405                }
14406                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14407                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14408                    // Don't care about who enables an app.
14409                    callingPackage = null;
14410                }
14411                pkgSetting.setEnabled(newState, userId, callingPackage);
14412                // pkgSetting.pkg.mSetEnabled = newState;
14413            } else {
14414                // We're dealing with a component level state change
14415                // First, verify that this is a valid class name.
14416                PackageParser.Package pkg = pkgSetting.pkg;
14417                if (pkg == null || !pkg.hasComponentClassName(className)) {
14418                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14419                        throw new IllegalArgumentException("Component class " + className
14420                                + " does not exist in " + packageName);
14421                    } else {
14422                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14423                                + className + " does not exist in " + packageName);
14424                    }
14425                }
14426                switch (newState) {
14427                case COMPONENT_ENABLED_STATE_ENABLED:
14428                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14429                        return;
14430                    }
14431                    break;
14432                case COMPONENT_ENABLED_STATE_DISABLED:
14433                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14434                        return;
14435                    }
14436                    break;
14437                case COMPONENT_ENABLED_STATE_DEFAULT:
14438                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14439                        return;
14440                    }
14441                    break;
14442                default:
14443                    Slog.e(TAG, "Invalid new component state: " + newState);
14444                    return;
14445                }
14446            }
14447            scheduleWritePackageRestrictionsLocked(userId);
14448            components = mPendingBroadcasts.get(userId, packageName);
14449            final boolean newPackage = components == null;
14450            if (newPackage) {
14451                components = new ArrayList<String>();
14452            }
14453            if (!components.contains(componentName)) {
14454                components.add(componentName);
14455            }
14456            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14457                sendNow = true;
14458                // Purge entry from pending broadcast list if another one exists already
14459                // since we are sending one right away.
14460                mPendingBroadcasts.remove(userId, packageName);
14461            } else {
14462                if (newPackage) {
14463                    mPendingBroadcasts.put(userId, packageName, components);
14464                }
14465                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14466                    // Schedule a message
14467                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14468                }
14469            }
14470        }
14471
14472        long callingId = Binder.clearCallingIdentity();
14473        try {
14474            if (sendNow) {
14475                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14476                sendPackageChangedBroadcast(packageName,
14477                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14478            }
14479        } finally {
14480            Binder.restoreCallingIdentity(callingId);
14481        }
14482    }
14483
14484    private void sendPackageChangedBroadcast(String packageName,
14485            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14486        if (DEBUG_INSTALL)
14487            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14488                    + componentNames);
14489        Bundle extras = new Bundle(4);
14490        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14491        String nameList[] = new String[componentNames.size()];
14492        componentNames.toArray(nameList);
14493        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14494        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14495        extras.putInt(Intent.EXTRA_UID, packageUid);
14496        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14497                new int[] {UserHandle.getUserId(packageUid)});
14498    }
14499
14500    @Override
14501    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14502        if (!sUserManager.exists(userId)) return;
14503        final int uid = Binder.getCallingUid();
14504        final int permission = mContext.checkCallingOrSelfPermission(
14505                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14506        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14507        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14508        // writer
14509        synchronized (mPackages) {
14510            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14511                    allowedByPermission, uid, userId)) {
14512                scheduleWritePackageRestrictionsLocked(userId);
14513            }
14514        }
14515    }
14516
14517    @Override
14518    public String getInstallerPackageName(String packageName) {
14519        // reader
14520        synchronized (mPackages) {
14521            return mSettings.getInstallerPackageNameLPr(packageName);
14522        }
14523    }
14524
14525    @Override
14526    public int getApplicationEnabledSetting(String packageName, int userId) {
14527        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14528        int uid = Binder.getCallingUid();
14529        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14530        // reader
14531        synchronized (mPackages) {
14532            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14533        }
14534    }
14535
14536    @Override
14537    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14538        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14539        int uid = Binder.getCallingUid();
14540        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14541        // reader
14542        synchronized (mPackages) {
14543            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14544        }
14545    }
14546
14547    @Override
14548    public void enterSafeMode() {
14549        enforceSystemOrRoot("Only the system can request entering safe mode");
14550
14551        if (!mSystemReady) {
14552            mSafeMode = true;
14553        }
14554    }
14555
14556    @Override
14557    public void systemReady() {
14558        mSystemReady = true;
14559
14560        // Read the compatibilty setting when the system is ready.
14561        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14562                mContext.getContentResolver(),
14563                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14564        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14565        if (DEBUG_SETTINGS) {
14566            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14567        }
14568
14569        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14570
14571        synchronized (mPackages) {
14572            // Verify that all of the preferred activity components actually
14573            // exist.  It is possible for applications to be updated and at
14574            // that point remove a previously declared activity component that
14575            // had been set as a preferred activity.  We try to clean this up
14576            // the next time we encounter that preferred activity, but it is
14577            // possible for the user flow to never be able to return to that
14578            // situation so here we do a sanity check to make sure we haven't
14579            // left any junk around.
14580            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14581            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14582                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14583                removed.clear();
14584                for (PreferredActivity pa : pir.filterSet()) {
14585                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14586                        removed.add(pa);
14587                    }
14588                }
14589                if (removed.size() > 0) {
14590                    for (int r=0; r<removed.size(); r++) {
14591                        PreferredActivity pa = removed.get(r);
14592                        Slog.w(TAG, "Removing dangling preferred activity: "
14593                                + pa.mPref.mComponent);
14594                        pir.removeFilter(pa);
14595                    }
14596                    mSettings.writePackageRestrictionsLPr(
14597                            mSettings.mPreferredActivities.keyAt(i));
14598                }
14599            }
14600
14601            for (int userId : UserManagerService.getInstance().getUserIds()) {
14602                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14603                    grantPermissionsUserIds = ArrayUtils.appendInt(
14604                            grantPermissionsUserIds, userId);
14605                }
14606            }
14607        }
14608        sUserManager.systemReady();
14609
14610        // If we upgraded grant all default permissions before kicking off.
14611        for (int userId : grantPermissionsUserIds) {
14612            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14613        }
14614
14615        // Kick off any messages waiting for system ready
14616        if (mPostSystemReadyMessages != null) {
14617            for (Message msg : mPostSystemReadyMessages) {
14618                msg.sendToTarget();
14619            }
14620            mPostSystemReadyMessages = null;
14621        }
14622
14623        // Watch for external volumes that come and go over time
14624        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14625        storage.registerListener(mStorageListener);
14626
14627        mInstallerService.systemReady();
14628        mPackageDexOptimizer.systemReady();
14629
14630        MountServiceInternal mountServiceInternal = LocalServices.getService(
14631                MountServiceInternal.class);
14632        mountServiceInternal.addExternalStoragePolicy(
14633                new MountServiceInternal.ExternalStorageMountPolicy() {
14634            @Override
14635            public int getMountMode(int uid, String packageName) {
14636                if (Process.isIsolated(uid)) {
14637                    return Zygote.MOUNT_EXTERNAL_NONE;
14638                }
14639                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14640                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14641                }
14642                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14643                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14644                }
14645                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14646                    return Zygote.MOUNT_EXTERNAL_READ;
14647                }
14648                return Zygote.MOUNT_EXTERNAL_WRITE;
14649            }
14650
14651            @Override
14652            public boolean hasExternalStorage(int uid, String packageName) {
14653                return true;
14654            }
14655        });
14656    }
14657
14658    @Override
14659    public boolean isSafeMode() {
14660        return mSafeMode;
14661    }
14662
14663    @Override
14664    public boolean hasSystemUidErrors() {
14665        return mHasSystemUidErrors;
14666    }
14667
14668    static String arrayToString(int[] array) {
14669        StringBuffer buf = new StringBuffer(128);
14670        buf.append('[');
14671        if (array != null) {
14672            for (int i=0; i<array.length; i++) {
14673                if (i > 0) buf.append(", ");
14674                buf.append(array[i]);
14675            }
14676        }
14677        buf.append(']');
14678        return buf.toString();
14679    }
14680
14681    static class DumpState {
14682        public static final int DUMP_LIBS = 1 << 0;
14683        public static final int DUMP_FEATURES = 1 << 1;
14684        public static final int DUMP_RESOLVERS = 1 << 2;
14685        public static final int DUMP_PERMISSIONS = 1 << 3;
14686        public static final int DUMP_PACKAGES = 1 << 4;
14687        public static final int DUMP_SHARED_USERS = 1 << 5;
14688        public static final int DUMP_MESSAGES = 1 << 6;
14689        public static final int DUMP_PROVIDERS = 1 << 7;
14690        public static final int DUMP_VERIFIERS = 1 << 8;
14691        public static final int DUMP_PREFERRED = 1 << 9;
14692        public static final int DUMP_PREFERRED_XML = 1 << 10;
14693        public static final int DUMP_KEYSETS = 1 << 11;
14694        public static final int DUMP_VERSION = 1 << 12;
14695        public static final int DUMP_INSTALLS = 1 << 13;
14696        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14697        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14698
14699        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14700
14701        private int mTypes;
14702
14703        private int mOptions;
14704
14705        private boolean mTitlePrinted;
14706
14707        private SharedUserSetting mSharedUser;
14708
14709        public boolean isDumping(int type) {
14710            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14711                return true;
14712            }
14713
14714            return (mTypes & type) != 0;
14715        }
14716
14717        public void setDump(int type) {
14718            mTypes |= type;
14719        }
14720
14721        public boolean isOptionEnabled(int option) {
14722            return (mOptions & option) != 0;
14723        }
14724
14725        public void setOptionEnabled(int option) {
14726            mOptions |= option;
14727        }
14728
14729        public boolean onTitlePrinted() {
14730            final boolean printed = mTitlePrinted;
14731            mTitlePrinted = true;
14732            return printed;
14733        }
14734
14735        public boolean getTitlePrinted() {
14736            return mTitlePrinted;
14737        }
14738
14739        public void setTitlePrinted(boolean enabled) {
14740            mTitlePrinted = enabled;
14741        }
14742
14743        public SharedUserSetting getSharedUser() {
14744            return mSharedUser;
14745        }
14746
14747        public void setSharedUser(SharedUserSetting user) {
14748            mSharedUser = user;
14749        }
14750    }
14751
14752    @Override
14753    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14754        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14755                != PackageManager.PERMISSION_GRANTED) {
14756            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14757                    + Binder.getCallingPid()
14758                    + ", uid=" + Binder.getCallingUid()
14759                    + " without permission "
14760                    + android.Manifest.permission.DUMP);
14761            return;
14762        }
14763
14764        DumpState dumpState = new DumpState();
14765        boolean fullPreferred = false;
14766        boolean checkin = false;
14767
14768        String packageName = null;
14769        ArraySet<String> permissionNames = null;
14770
14771        int opti = 0;
14772        while (opti < args.length) {
14773            String opt = args[opti];
14774            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14775                break;
14776            }
14777            opti++;
14778
14779            if ("-a".equals(opt)) {
14780                // Right now we only know how to print all.
14781            } else if ("-h".equals(opt)) {
14782                pw.println("Package manager dump options:");
14783                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14784                pw.println("    --checkin: dump for a checkin");
14785                pw.println("    -f: print details of intent filters");
14786                pw.println("    -h: print this help");
14787                pw.println("  cmd may be one of:");
14788                pw.println("    l[ibraries]: list known shared libraries");
14789                pw.println("    f[ibraries]: list device features");
14790                pw.println("    k[eysets]: print known keysets");
14791                pw.println("    r[esolvers]: dump intent resolvers");
14792                pw.println("    perm[issions]: dump permissions");
14793                pw.println("    permission [name ...]: dump declaration and use of given permission");
14794                pw.println("    pref[erred]: print preferred package settings");
14795                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14796                pw.println("    prov[iders]: dump content providers");
14797                pw.println("    p[ackages]: dump installed packages");
14798                pw.println("    s[hared-users]: dump shared user IDs");
14799                pw.println("    m[essages]: print collected runtime messages");
14800                pw.println("    v[erifiers]: print package verifier info");
14801                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14802                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14803                pw.println("    version: print database version info");
14804                pw.println("    write: write current settings now");
14805                pw.println("    installs: details about install sessions");
14806                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14807                pw.println("    <package.name>: info about given package");
14808                return;
14809            } else if ("--checkin".equals(opt)) {
14810                checkin = true;
14811            } else if ("-f".equals(opt)) {
14812                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14813            } else {
14814                pw.println("Unknown argument: " + opt + "; use -h for help");
14815            }
14816        }
14817
14818        // Is the caller requesting to dump a particular piece of data?
14819        if (opti < args.length) {
14820            String cmd = args[opti];
14821            opti++;
14822            // Is this a package name?
14823            if ("android".equals(cmd) || cmd.contains(".")) {
14824                packageName = cmd;
14825                // When dumping a single package, we always dump all of its
14826                // filter information since the amount of data will be reasonable.
14827                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14828            } else if ("check-permission".equals(cmd)) {
14829                if (opti >= args.length) {
14830                    pw.println("Error: check-permission missing permission argument");
14831                    return;
14832                }
14833                String perm = args[opti];
14834                opti++;
14835                if (opti >= args.length) {
14836                    pw.println("Error: check-permission missing package argument");
14837                    return;
14838                }
14839                String pkg = args[opti];
14840                opti++;
14841                int user = UserHandle.getUserId(Binder.getCallingUid());
14842                if (opti < args.length) {
14843                    try {
14844                        user = Integer.parseInt(args[opti]);
14845                    } catch (NumberFormatException e) {
14846                        pw.println("Error: check-permission user argument is not a number: "
14847                                + args[opti]);
14848                        return;
14849                    }
14850                }
14851                pw.println(checkPermission(perm, pkg, user));
14852                return;
14853            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14854                dumpState.setDump(DumpState.DUMP_LIBS);
14855            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14856                dumpState.setDump(DumpState.DUMP_FEATURES);
14857            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14858                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14859            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14860                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14861            } else if ("permission".equals(cmd)) {
14862                if (opti >= args.length) {
14863                    pw.println("Error: permission requires permission name");
14864                    return;
14865                }
14866                permissionNames = new ArraySet<>();
14867                while (opti < args.length) {
14868                    permissionNames.add(args[opti]);
14869                    opti++;
14870                }
14871                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14872                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14873            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14874                dumpState.setDump(DumpState.DUMP_PREFERRED);
14875            } else if ("preferred-xml".equals(cmd)) {
14876                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14877                if (opti < args.length && "--full".equals(args[opti])) {
14878                    fullPreferred = true;
14879                    opti++;
14880                }
14881            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14882                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14883            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14884                dumpState.setDump(DumpState.DUMP_PACKAGES);
14885            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14886                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14887            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14888                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14889            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14890                dumpState.setDump(DumpState.DUMP_MESSAGES);
14891            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14892                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14893            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14894                    || "intent-filter-verifiers".equals(cmd)) {
14895                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14896            } else if ("version".equals(cmd)) {
14897                dumpState.setDump(DumpState.DUMP_VERSION);
14898            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14899                dumpState.setDump(DumpState.DUMP_KEYSETS);
14900            } else if ("installs".equals(cmd)) {
14901                dumpState.setDump(DumpState.DUMP_INSTALLS);
14902            } else if ("write".equals(cmd)) {
14903                synchronized (mPackages) {
14904                    mSettings.writeLPr();
14905                    pw.println("Settings written.");
14906                    return;
14907                }
14908            }
14909        }
14910
14911        if (checkin) {
14912            pw.println("vers,1");
14913        }
14914
14915        // reader
14916        synchronized (mPackages) {
14917            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14918                if (!checkin) {
14919                    if (dumpState.onTitlePrinted())
14920                        pw.println();
14921                    pw.println("Database versions:");
14922                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14923                }
14924            }
14925
14926            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14927                if (!checkin) {
14928                    if (dumpState.onTitlePrinted())
14929                        pw.println();
14930                    pw.println("Verifiers:");
14931                    pw.print("  Required: ");
14932                    pw.print(mRequiredVerifierPackage);
14933                    pw.print(" (uid=");
14934                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14935                    pw.println(")");
14936                } else if (mRequiredVerifierPackage != null) {
14937                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14938                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14939                }
14940            }
14941
14942            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14943                    packageName == null) {
14944                if (mIntentFilterVerifierComponent != null) {
14945                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14946                    if (!checkin) {
14947                        if (dumpState.onTitlePrinted())
14948                            pw.println();
14949                        pw.println("Intent Filter Verifier:");
14950                        pw.print("  Using: ");
14951                        pw.print(verifierPackageName);
14952                        pw.print(" (uid=");
14953                        pw.print(getPackageUid(verifierPackageName, 0));
14954                        pw.println(")");
14955                    } else if (verifierPackageName != null) {
14956                        pw.print("ifv,"); pw.print(verifierPackageName);
14957                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14958                    }
14959                } else {
14960                    pw.println();
14961                    pw.println("No Intent Filter Verifier available!");
14962                }
14963            }
14964
14965            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14966                boolean printedHeader = false;
14967                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14968                while (it.hasNext()) {
14969                    String name = it.next();
14970                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14971                    if (!checkin) {
14972                        if (!printedHeader) {
14973                            if (dumpState.onTitlePrinted())
14974                                pw.println();
14975                            pw.println("Libraries:");
14976                            printedHeader = true;
14977                        }
14978                        pw.print("  ");
14979                    } else {
14980                        pw.print("lib,");
14981                    }
14982                    pw.print(name);
14983                    if (!checkin) {
14984                        pw.print(" -> ");
14985                    }
14986                    if (ent.path != null) {
14987                        if (!checkin) {
14988                            pw.print("(jar) ");
14989                            pw.print(ent.path);
14990                        } else {
14991                            pw.print(",jar,");
14992                            pw.print(ent.path);
14993                        }
14994                    } else {
14995                        if (!checkin) {
14996                            pw.print("(apk) ");
14997                            pw.print(ent.apk);
14998                        } else {
14999                            pw.print(",apk,");
15000                            pw.print(ent.apk);
15001                        }
15002                    }
15003                    pw.println();
15004                }
15005            }
15006
15007            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15008                if (dumpState.onTitlePrinted())
15009                    pw.println();
15010                if (!checkin) {
15011                    pw.println("Features:");
15012                }
15013                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15014                while (it.hasNext()) {
15015                    String name = it.next();
15016                    if (!checkin) {
15017                        pw.print("  ");
15018                    } else {
15019                        pw.print("feat,");
15020                    }
15021                    pw.println(name);
15022                }
15023            }
15024
15025            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15026                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15027                        : "Activity Resolver Table:", "  ", packageName,
15028                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15029                    dumpState.setTitlePrinted(true);
15030                }
15031                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15032                        : "Receiver Resolver Table:", "  ", packageName,
15033                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15034                    dumpState.setTitlePrinted(true);
15035                }
15036                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15037                        : "Service Resolver Table:", "  ", packageName,
15038                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15039                    dumpState.setTitlePrinted(true);
15040                }
15041                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15042                        : "Provider Resolver Table:", "  ", packageName,
15043                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15044                    dumpState.setTitlePrinted(true);
15045                }
15046            }
15047
15048            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15049                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15050                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15051                    int user = mSettings.mPreferredActivities.keyAt(i);
15052                    if (pir.dump(pw,
15053                            dumpState.getTitlePrinted()
15054                                ? "\nPreferred Activities User " + user + ":"
15055                                : "Preferred Activities User " + user + ":", "  ",
15056                            packageName, true, false)) {
15057                        dumpState.setTitlePrinted(true);
15058                    }
15059                }
15060            }
15061
15062            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15063                pw.flush();
15064                FileOutputStream fout = new FileOutputStream(fd);
15065                BufferedOutputStream str = new BufferedOutputStream(fout);
15066                XmlSerializer serializer = new FastXmlSerializer();
15067                try {
15068                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15069                    serializer.startDocument(null, true);
15070                    serializer.setFeature(
15071                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15072                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15073                    serializer.endDocument();
15074                    serializer.flush();
15075                } catch (IllegalArgumentException e) {
15076                    pw.println("Failed writing: " + e);
15077                } catch (IllegalStateException e) {
15078                    pw.println("Failed writing: " + e);
15079                } catch (IOException e) {
15080                    pw.println("Failed writing: " + e);
15081                }
15082            }
15083
15084            if (!checkin
15085                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15086                    && packageName == null) {
15087                pw.println();
15088                int count = mSettings.mPackages.size();
15089                if (count == 0) {
15090                    pw.println("No applications!");
15091                    pw.println();
15092                } else {
15093                    final String prefix = "  ";
15094                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15095                    if (allPackageSettings.size() == 0) {
15096                        pw.println("No domain preferred apps!");
15097                        pw.println();
15098                    } else {
15099                        pw.println("App verification status:");
15100                        pw.println();
15101                        count = 0;
15102                        for (PackageSetting ps : allPackageSettings) {
15103                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15104                            if (ivi == null || ivi.getPackageName() == null) continue;
15105                            pw.println(prefix + "Package: " + ivi.getPackageName());
15106                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15107                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15108                            pw.println();
15109                            count++;
15110                        }
15111                        if (count == 0) {
15112                            pw.println(prefix + "No app verification established.");
15113                            pw.println();
15114                        }
15115                        for (int userId : sUserManager.getUserIds()) {
15116                            pw.println("App linkages for user " + userId + ":");
15117                            pw.println();
15118                            count = 0;
15119                            for (PackageSetting ps : allPackageSettings) {
15120                                final long status = ps.getDomainVerificationStatusForUser(userId);
15121                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15122                                    continue;
15123                                }
15124                                pw.println(prefix + "Package: " + ps.name);
15125                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15126                                String statusStr = IntentFilterVerificationInfo.
15127                                        getStatusStringFromValue(status);
15128                                pw.println(prefix + "Status:  " + statusStr);
15129                                pw.println();
15130                                count++;
15131                            }
15132                            if (count == 0) {
15133                                pw.println(prefix + "No configured app linkages.");
15134                                pw.println();
15135                            }
15136                        }
15137                    }
15138                }
15139            }
15140
15141            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15142                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15143                if (packageName == null && permissionNames == null) {
15144                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15145                        if (iperm == 0) {
15146                            if (dumpState.onTitlePrinted())
15147                                pw.println();
15148                            pw.println("AppOp Permissions:");
15149                        }
15150                        pw.print("  AppOp Permission ");
15151                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15152                        pw.println(":");
15153                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15154                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15155                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15156                        }
15157                    }
15158                }
15159            }
15160
15161            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15162                boolean printedSomething = false;
15163                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15164                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15165                        continue;
15166                    }
15167                    if (!printedSomething) {
15168                        if (dumpState.onTitlePrinted())
15169                            pw.println();
15170                        pw.println("Registered ContentProviders:");
15171                        printedSomething = true;
15172                    }
15173                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15174                    pw.print("    "); pw.println(p.toString());
15175                }
15176                printedSomething = false;
15177                for (Map.Entry<String, PackageParser.Provider> entry :
15178                        mProvidersByAuthority.entrySet()) {
15179                    PackageParser.Provider p = entry.getValue();
15180                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15181                        continue;
15182                    }
15183                    if (!printedSomething) {
15184                        if (dumpState.onTitlePrinted())
15185                            pw.println();
15186                        pw.println("ContentProvider Authorities:");
15187                        printedSomething = true;
15188                    }
15189                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15190                    pw.print("    "); pw.println(p.toString());
15191                    if (p.info != null && p.info.applicationInfo != null) {
15192                        final String appInfo = p.info.applicationInfo.toString();
15193                        pw.print("      applicationInfo="); pw.println(appInfo);
15194                    }
15195                }
15196            }
15197
15198            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15199                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15200            }
15201
15202            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15203                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15204            }
15205
15206            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15207                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15208            }
15209
15210            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15211                // XXX should handle packageName != null by dumping only install data that
15212                // the given package is involved with.
15213                if (dumpState.onTitlePrinted()) pw.println();
15214                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15215            }
15216
15217            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15218                if (dumpState.onTitlePrinted()) pw.println();
15219                mSettings.dumpReadMessagesLPr(pw, dumpState);
15220
15221                pw.println();
15222                pw.println("Package warning messages:");
15223                BufferedReader in = null;
15224                String line = null;
15225                try {
15226                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15227                    while ((line = in.readLine()) != null) {
15228                        if (line.contains("ignored: updated version")) continue;
15229                        pw.println(line);
15230                    }
15231                } catch (IOException ignored) {
15232                } finally {
15233                    IoUtils.closeQuietly(in);
15234                }
15235            }
15236
15237            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15238                BufferedReader in = null;
15239                String line = null;
15240                try {
15241                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15242                    while ((line = in.readLine()) != null) {
15243                        if (line.contains("ignored: updated version")) continue;
15244                        pw.print("msg,");
15245                        pw.println(line);
15246                    }
15247                } catch (IOException ignored) {
15248                } finally {
15249                    IoUtils.closeQuietly(in);
15250                }
15251            }
15252        }
15253    }
15254
15255    private String dumpDomainString(String packageName) {
15256        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15257        List<IntentFilter> filters = getAllIntentFilters(packageName);
15258
15259        ArraySet<String> result = new ArraySet<>();
15260        if (iviList.size() > 0) {
15261            for (IntentFilterVerificationInfo ivi : iviList) {
15262                for (String host : ivi.getDomains()) {
15263                    result.add(host);
15264                }
15265            }
15266        }
15267        if (filters != null && filters.size() > 0) {
15268            for (IntentFilter filter : filters) {
15269                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15270                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15271                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15272                    result.addAll(filter.getHostsList());
15273                }
15274            }
15275        }
15276
15277        StringBuilder sb = new StringBuilder(result.size() * 16);
15278        for (String domain : result) {
15279            if (sb.length() > 0) sb.append(" ");
15280            sb.append(domain);
15281        }
15282        return sb.toString();
15283    }
15284
15285    // ------- apps on sdcard specific code -------
15286    static final boolean DEBUG_SD_INSTALL = false;
15287
15288    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15289
15290    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15291
15292    private boolean mMediaMounted = false;
15293
15294    static String getEncryptKey() {
15295        try {
15296            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15297                    SD_ENCRYPTION_KEYSTORE_NAME);
15298            if (sdEncKey == null) {
15299                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15300                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15301                if (sdEncKey == null) {
15302                    Slog.e(TAG, "Failed to create encryption keys");
15303                    return null;
15304                }
15305            }
15306            return sdEncKey;
15307        } catch (NoSuchAlgorithmException nsae) {
15308            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15309            return null;
15310        } catch (IOException ioe) {
15311            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15312            return null;
15313        }
15314    }
15315
15316    /*
15317     * Update media status on PackageManager.
15318     */
15319    @Override
15320    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15321        int callingUid = Binder.getCallingUid();
15322        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15323            throw new SecurityException("Media status can only be updated by the system");
15324        }
15325        // reader; this apparently protects mMediaMounted, but should probably
15326        // be a different lock in that case.
15327        synchronized (mPackages) {
15328            Log.i(TAG, "Updating external media status from "
15329                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15330                    + (mediaStatus ? "mounted" : "unmounted"));
15331            if (DEBUG_SD_INSTALL)
15332                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15333                        + ", mMediaMounted=" + mMediaMounted);
15334            if (mediaStatus == mMediaMounted) {
15335                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15336                        : 0, -1);
15337                mHandler.sendMessage(msg);
15338                return;
15339            }
15340            mMediaMounted = mediaStatus;
15341        }
15342        // Queue up an async operation since the package installation may take a
15343        // little while.
15344        mHandler.post(new Runnable() {
15345            public void run() {
15346                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15347            }
15348        });
15349    }
15350
15351    /**
15352     * Called by MountService when the initial ASECs to scan are available.
15353     * Should block until all the ASEC containers are finished being scanned.
15354     */
15355    public void scanAvailableAsecs() {
15356        updateExternalMediaStatusInner(true, false, false);
15357        if (mShouldRestoreconData) {
15358            SELinuxMMAC.setRestoreconDone();
15359            mShouldRestoreconData = false;
15360        }
15361    }
15362
15363    /*
15364     * Collect information of applications on external media, map them against
15365     * existing containers and update information based on current mount status.
15366     * Please note that we always have to report status if reportStatus has been
15367     * set to true especially when unloading packages.
15368     */
15369    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15370            boolean externalStorage) {
15371        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15372        int[] uidArr = EmptyArray.INT;
15373
15374        final String[] list = PackageHelper.getSecureContainerList();
15375        if (ArrayUtils.isEmpty(list)) {
15376            Log.i(TAG, "No secure containers found");
15377        } else {
15378            // Process list of secure containers and categorize them
15379            // as active or stale based on their package internal state.
15380
15381            // reader
15382            synchronized (mPackages) {
15383                for (String cid : list) {
15384                    // Leave stages untouched for now; installer service owns them
15385                    if (PackageInstallerService.isStageName(cid)) continue;
15386
15387                    if (DEBUG_SD_INSTALL)
15388                        Log.i(TAG, "Processing container " + cid);
15389                    String pkgName = getAsecPackageName(cid);
15390                    if (pkgName == null) {
15391                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15392                        continue;
15393                    }
15394                    if (DEBUG_SD_INSTALL)
15395                        Log.i(TAG, "Looking for pkg : " + pkgName);
15396
15397                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15398                    if (ps == null) {
15399                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15400                        continue;
15401                    }
15402
15403                    /*
15404                     * Skip packages that are not external if we're unmounting
15405                     * external storage.
15406                     */
15407                    if (externalStorage && !isMounted && !isExternal(ps)) {
15408                        continue;
15409                    }
15410
15411                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15412                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15413                    // The package status is changed only if the code path
15414                    // matches between settings and the container id.
15415                    if (ps.codePathString != null
15416                            && ps.codePathString.startsWith(args.getCodePath())) {
15417                        if (DEBUG_SD_INSTALL) {
15418                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15419                                    + " at code path: " + ps.codePathString);
15420                        }
15421
15422                        // We do have a valid package installed on sdcard
15423                        processCids.put(args, ps.codePathString);
15424                        final int uid = ps.appId;
15425                        if (uid != -1) {
15426                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15427                        }
15428                    } else {
15429                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15430                                + ps.codePathString);
15431                    }
15432                }
15433            }
15434
15435            Arrays.sort(uidArr);
15436        }
15437
15438        // Process packages with valid entries.
15439        if (isMounted) {
15440            if (DEBUG_SD_INSTALL)
15441                Log.i(TAG, "Loading packages");
15442            loadMediaPackages(processCids, uidArr);
15443            startCleaningPackages();
15444            mInstallerService.onSecureContainersAvailable();
15445        } else {
15446            if (DEBUG_SD_INSTALL)
15447                Log.i(TAG, "Unloading packages");
15448            unloadMediaPackages(processCids, uidArr, reportStatus);
15449        }
15450    }
15451
15452    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15453            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15454        final int size = infos.size();
15455        final String[] packageNames = new String[size];
15456        final int[] packageUids = new int[size];
15457        for (int i = 0; i < size; i++) {
15458            final ApplicationInfo info = infos.get(i);
15459            packageNames[i] = info.packageName;
15460            packageUids[i] = info.uid;
15461        }
15462        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15463                finishedReceiver);
15464    }
15465
15466    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15467            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15468        sendResourcesChangedBroadcast(mediaStatus, replacing,
15469                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15470    }
15471
15472    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15473            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15474        int size = pkgList.length;
15475        if (size > 0) {
15476            // Send broadcasts here
15477            Bundle extras = new Bundle();
15478            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15479            if (uidArr != null) {
15480                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15481            }
15482            if (replacing) {
15483                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15484            }
15485            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15486                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15487            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15488        }
15489    }
15490
15491   /*
15492     * Look at potentially valid container ids from processCids If package
15493     * information doesn't match the one on record or package scanning fails,
15494     * the cid is added to list of removeCids. We currently don't delete stale
15495     * containers.
15496     */
15497    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15498        ArrayList<String> pkgList = new ArrayList<String>();
15499        Set<AsecInstallArgs> keys = processCids.keySet();
15500
15501        for (AsecInstallArgs args : keys) {
15502            String codePath = processCids.get(args);
15503            if (DEBUG_SD_INSTALL)
15504                Log.i(TAG, "Loading container : " + args.cid);
15505            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15506            try {
15507                // Make sure there are no container errors first.
15508                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15509                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15510                            + " when installing from sdcard");
15511                    continue;
15512                }
15513                // Check code path here.
15514                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15515                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15516                            + " does not match one in settings " + codePath);
15517                    continue;
15518                }
15519                // Parse package
15520                int parseFlags = mDefParseFlags;
15521                if (args.isExternalAsec()) {
15522                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15523                }
15524                if (args.isFwdLocked()) {
15525                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15526                }
15527
15528                synchronized (mInstallLock) {
15529                    PackageParser.Package pkg = null;
15530                    try {
15531                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15532                    } catch (PackageManagerException e) {
15533                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15534                    }
15535                    // Scan the package
15536                    if (pkg != null) {
15537                        /*
15538                         * TODO why is the lock being held? doPostInstall is
15539                         * called in other places without the lock. This needs
15540                         * to be straightened out.
15541                         */
15542                        // writer
15543                        synchronized (mPackages) {
15544                            retCode = PackageManager.INSTALL_SUCCEEDED;
15545                            pkgList.add(pkg.packageName);
15546                            // Post process args
15547                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15548                                    pkg.applicationInfo.uid);
15549                        }
15550                    } else {
15551                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15552                    }
15553                }
15554
15555            } finally {
15556                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15557                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15558                }
15559            }
15560        }
15561        // writer
15562        synchronized (mPackages) {
15563            // If the platform SDK has changed since the last time we booted,
15564            // we need to re-grant app permission to catch any new ones that
15565            // appear. This is really a hack, and means that apps can in some
15566            // cases get permissions that the user didn't initially explicitly
15567            // allow... it would be nice to have some better way to handle
15568            // this situation.
15569            final VersionInfo ver = mSettings.getExternalVersion();
15570
15571            int updateFlags = UPDATE_PERMISSIONS_ALL;
15572            if (ver.sdkVersion != mSdkVersion) {
15573                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15574                        + mSdkVersion + "; regranting permissions for external");
15575                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15576            }
15577            updatePermissionsLPw(null, null, updateFlags);
15578
15579            // Yay, everything is now upgraded
15580            ver.forceCurrent();
15581
15582            // can downgrade to reader
15583            // Persist settings
15584            mSettings.writeLPr();
15585        }
15586        // Send a broadcast to let everyone know we are done processing
15587        if (pkgList.size() > 0) {
15588            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15589        }
15590    }
15591
15592   /*
15593     * Utility method to unload a list of specified containers
15594     */
15595    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15596        // Just unmount all valid containers.
15597        for (AsecInstallArgs arg : cidArgs) {
15598            synchronized (mInstallLock) {
15599                arg.doPostDeleteLI(false);
15600           }
15601       }
15602   }
15603
15604    /*
15605     * Unload packages mounted on external media. This involves deleting package
15606     * data from internal structures, sending broadcasts about diabled packages,
15607     * gc'ing to free up references, unmounting all secure containers
15608     * corresponding to packages on external media, and posting a
15609     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15610     * that we always have to post this message if status has been requested no
15611     * matter what.
15612     */
15613    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15614            final boolean reportStatus) {
15615        if (DEBUG_SD_INSTALL)
15616            Log.i(TAG, "unloading media packages");
15617        ArrayList<String> pkgList = new ArrayList<String>();
15618        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15619        final Set<AsecInstallArgs> keys = processCids.keySet();
15620        for (AsecInstallArgs args : keys) {
15621            String pkgName = args.getPackageName();
15622            if (DEBUG_SD_INSTALL)
15623                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15624            // Delete package internally
15625            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15626            synchronized (mInstallLock) {
15627                boolean res = deletePackageLI(pkgName, null, false, null, null,
15628                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15629                if (res) {
15630                    pkgList.add(pkgName);
15631                } else {
15632                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15633                    failedList.add(args);
15634                }
15635            }
15636        }
15637
15638        // reader
15639        synchronized (mPackages) {
15640            // We didn't update the settings after removing each package;
15641            // write them now for all packages.
15642            mSettings.writeLPr();
15643        }
15644
15645        // We have to absolutely send UPDATED_MEDIA_STATUS only
15646        // after confirming that all the receivers processed the ordered
15647        // broadcast when packages get disabled, force a gc to clean things up.
15648        // and unload all the containers.
15649        if (pkgList.size() > 0) {
15650            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15651                    new IIntentReceiver.Stub() {
15652                public void performReceive(Intent intent, int resultCode, String data,
15653                        Bundle extras, boolean ordered, boolean sticky,
15654                        int sendingUser) throws RemoteException {
15655                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15656                            reportStatus ? 1 : 0, 1, keys);
15657                    mHandler.sendMessage(msg);
15658                }
15659            });
15660        } else {
15661            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15662                    keys);
15663            mHandler.sendMessage(msg);
15664        }
15665    }
15666
15667    private void loadPrivatePackages(VolumeInfo vol) {
15668        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15669        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15670        synchronized (mInstallLock) {
15671        synchronized (mPackages) {
15672            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15673            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15674            for (PackageSetting ps : packages) {
15675                final PackageParser.Package pkg;
15676                try {
15677                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15678                    loaded.add(pkg.applicationInfo);
15679                } catch (PackageManagerException e) {
15680                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15681                }
15682
15683                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15684                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15685                }
15686            }
15687
15688            int updateFlags = UPDATE_PERMISSIONS_ALL;
15689            if (ver.sdkVersion != mSdkVersion) {
15690                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15691                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15692                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15693            }
15694            updatePermissionsLPw(null, null, updateFlags);
15695
15696            // Yay, everything is now upgraded
15697            ver.forceCurrent();
15698
15699            mSettings.writeLPr();
15700        }
15701        }
15702
15703        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15704        sendResourcesChangedBroadcast(true, false, loaded, null);
15705    }
15706
15707    private void unloadPrivatePackages(VolumeInfo vol) {
15708        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15709        synchronized (mInstallLock) {
15710        synchronized (mPackages) {
15711            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15712            for (PackageSetting ps : packages) {
15713                if (ps.pkg == null) continue;
15714
15715                final ApplicationInfo info = ps.pkg.applicationInfo;
15716                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15717                if (deletePackageLI(ps.name, null, false, null, null,
15718                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15719                    unloaded.add(info);
15720                } else {
15721                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15722                }
15723            }
15724
15725            mSettings.writeLPr();
15726        }
15727        }
15728
15729        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15730        sendResourcesChangedBroadcast(false, false, unloaded, null);
15731    }
15732
15733    /**
15734     * Examine all users present on given mounted volume, and destroy data
15735     * belonging to users that are no longer valid, or whose user ID has been
15736     * recycled.
15737     */
15738    private void reconcileUsers(String volumeUuid) {
15739        final File[] files = FileUtils
15740                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15741        for (File file : files) {
15742            if (!file.isDirectory()) continue;
15743
15744            final int userId;
15745            final UserInfo info;
15746            try {
15747                userId = Integer.parseInt(file.getName());
15748                info = sUserManager.getUserInfo(userId);
15749            } catch (NumberFormatException e) {
15750                Slog.w(TAG, "Invalid user directory " + file);
15751                continue;
15752            }
15753
15754            boolean destroyUser = false;
15755            if (info == null) {
15756                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15757                        + " because no matching user was found");
15758                destroyUser = true;
15759            } else {
15760                try {
15761                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15762                } catch (IOException e) {
15763                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15764                            + " because we failed to enforce serial number: " + e);
15765                    destroyUser = true;
15766                }
15767            }
15768
15769            if (destroyUser) {
15770                synchronized (mInstallLock) {
15771                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15772                }
15773            }
15774        }
15775
15776        final UserManager um = mContext.getSystemService(UserManager.class);
15777        for (UserInfo user : um.getUsers()) {
15778            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15779            if (userDir.exists()) continue;
15780
15781            try {
15782                UserManagerService.prepareUserDirectory(userDir);
15783                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15784            } catch (IOException e) {
15785                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15786            }
15787        }
15788    }
15789
15790    /**
15791     * Examine all apps present on given mounted volume, and destroy apps that
15792     * aren't expected, either due to uninstallation or reinstallation on
15793     * another volume.
15794     */
15795    private void reconcileApps(String volumeUuid) {
15796        final File[] files = FileUtils
15797                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15798        for (File file : files) {
15799            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15800                    && !PackageInstallerService.isStageName(file.getName());
15801            if (!isPackage) {
15802                // Ignore entries which are not packages
15803                continue;
15804            }
15805
15806            boolean destroyApp = false;
15807            String packageName = null;
15808            try {
15809                final PackageLite pkg = PackageParser.parsePackageLite(file,
15810                        PackageParser.PARSE_MUST_BE_APK);
15811                packageName = pkg.packageName;
15812
15813                synchronized (mPackages) {
15814                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15815                    if (ps == null) {
15816                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15817                                + volumeUuid + " because we found no install record");
15818                        destroyApp = true;
15819                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15820                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15821                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15822                        destroyApp = true;
15823                    }
15824                }
15825
15826            } catch (PackageParserException e) {
15827                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15828                destroyApp = true;
15829            }
15830
15831            if (destroyApp) {
15832                synchronized (mInstallLock) {
15833                    if (packageName != null) {
15834                        removeDataDirsLI(volumeUuid, packageName);
15835                    }
15836                    if (file.isDirectory()) {
15837                        mInstaller.rmPackageDir(file.getAbsolutePath());
15838                    } else {
15839                        file.delete();
15840                    }
15841                }
15842            }
15843        }
15844    }
15845
15846    private void unfreezePackage(String packageName) {
15847        synchronized (mPackages) {
15848            final PackageSetting ps = mSettings.mPackages.get(packageName);
15849            if (ps != null) {
15850                ps.frozen = false;
15851            }
15852        }
15853    }
15854
15855    @Override
15856    public int movePackage(final String packageName, final String volumeUuid) {
15857        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15858
15859        final int moveId = mNextMoveId.getAndIncrement();
15860        try {
15861            movePackageInternal(packageName, volumeUuid, moveId);
15862        } catch (PackageManagerException e) {
15863            Slog.w(TAG, "Failed to move " + packageName, e);
15864            mMoveCallbacks.notifyStatusChanged(moveId,
15865                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15866        }
15867        return moveId;
15868    }
15869
15870    private void movePackageInternal(final String packageName, final String volumeUuid,
15871            final int moveId) throws PackageManagerException {
15872        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15873        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15874        final PackageManager pm = mContext.getPackageManager();
15875
15876        final boolean currentAsec;
15877        final String currentVolumeUuid;
15878        final File codeFile;
15879        final String installerPackageName;
15880        final String packageAbiOverride;
15881        final int appId;
15882        final String seinfo;
15883        final String label;
15884
15885        // reader
15886        synchronized (mPackages) {
15887            final PackageParser.Package pkg = mPackages.get(packageName);
15888            final PackageSetting ps = mSettings.mPackages.get(packageName);
15889            if (pkg == null || ps == null) {
15890                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15891            }
15892
15893            if (pkg.applicationInfo.isSystemApp()) {
15894                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15895                        "Cannot move system application");
15896            }
15897
15898            if (pkg.applicationInfo.isExternalAsec()) {
15899                currentAsec = true;
15900                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
15901            } else if (pkg.applicationInfo.isForwardLocked()) {
15902                currentAsec = true;
15903                currentVolumeUuid = "forward_locked";
15904            } else {
15905                currentAsec = false;
15906                currentVolumeUuid = ps.volumeUuid;
15907
15908                final File probe = new File(pkg.codePath);
15909                final File probeOat = new File(probe, "oat");
15910                if (!probe.isDirectory() || !probeOat.isDirectory()) {
15911                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15912                            "Move only supported for modern cluster style installs");
15913                }
15914            }
15915
15916            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
15917                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15918                        "Package already moved to " + volumeUuid);
15919            }
15920
15921            if (ps.frozen) {
15922                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15923                        "Failed to move already frozen package");
15924            }
15925            ps.frozen = true;
15926
15927            codeFile = new File(pkg.codePath);
15928            installerPackageName = ps.installerPackageName;
15929            packageAbiOverride = ps.cpuAbiOverrideString;
15930            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15931            seinfo = pkg.applicationInfo.seinfo;
15932            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15933        }
15934
15935        // Now that we're guarded by frozen state, kill app during move
15936        final long token = Binder.clearCallingIdentity();
15937        try {
15938            killApplication(packageName, appId, "move pkg");
15939        } finally {
15940            Binder.restoreCallingIdentity(token);
15941        }
15942
15943        final Bundle extras = new Bundle();
15944        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15945        extras.putString(Intent.EXTRA_TITLE, label);
15946        mMoveCallbacks.notifyCreated(moveId, extras);
15947
15948        int installFlags;
15949        final boolean moveCompleteApp;
15950        final File measurePath;
15951
15952        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15953            installFlags = INSTALL_INTERNAL;
15954            moveCompleteApp = !currentAsec;
15955            measurePath = Environment.getDataAppDirectory(volumeUuid);
15956        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15957            installFlags = INSTALL_EXTERNAL;
15958            moveCompleteApp = false;
15959            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15960        } else {
15961            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15962            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15963                    || !volume.isMountedWritable()) {
15964                unfreezePackage(packageName);
15965                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15966                        "Move location not mounted private volume");
15967            }
15968
15969            Preconditions.checkState(!currentAsec);
15970
15971            installFlags = INSTALL_INTERNAL;
15972            moveCompleteApp = true;
15973            measurePath = Environment.getDataAppDirectory(volumeUuid);
15974        }
15975
15976        final PackageStats stats = new PackageStats(null, -1);
15977        synchronized (mInstaller) {
15978            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15979                unfreezePackage(packageName);
15980                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15981                        "Failed to measure package size");
15982            }
15983        }
15984
15985        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15986                + stats.dataSize);
15987
15988        final long startFreeBytes = measurePath.getFreeSpace();
15989        final long sizeBytes;
15990        if (moveCompleteApp) {
15991            sizeBytes = stats.codeSize + stats.dataSize;
15992        } else {
15993            sizeBytes = stats.codeSize;
15994        }
15995
15996        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15997            unfreezePackage(packageName);
15998            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15999                    "Not enough free space to move");
16000        }
16001
16002        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16003
16004        final CountDownLatch installedLatch = new CountDownLatch(1);
16005        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16006            @Override
16007            public void onUserActionRequired(Intent intent) throws RemoteException {
16008                throw new IllegalStateException();
16009            }
16010
16011            @Override
16012            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16013                    Bundle extras) throws RemoteException {
16014                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16015                        + PackageManager.installStatusToString(returnCode, msg));
16016
16017                installedLatch.countDown();
16018
16019                // Regardless of success or failure of the move operation,
16020                // always unfreeze the package
16021                unfreezePackage(packageName);
16022
16023                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16024                switch (status) {
16025                    case PackageInstaller.STATUS_SUCCESS:
16026                        mMoveCallbacks.notifyStatusChanged(moveId,
16027                                PackageManager.MOVE_SUCCEEDED);
16028                        break;
16029                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16030                        mMoveCallbacks.notifyStatusChanged(moveId,
16031                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16032                        break;
16033                    default:
16034                        mMoveCallbacks.notifyStatusChanged(moveId,
16035                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16036                        break;
16037                }
16038            }
16039        };
16040
16041        final MoveInfo move;
16042        if (moveCompleteApp) {
16043            // Kick off a thread to report progress estimates
16044            new Thread() {
16045                @Override
16046                public void run() {
16047                    while (true) {
16048                        try {
16049                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16050                                break;
16051                            }
16052                        } catch (InterruptedException ignored) {
16053                        }
16054
16055                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16056                        final int progress = 10 + (int) MathUtils.constrain(
16057                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16058                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16059                    }
16060                }
16061            }.start();
16062
16063            final String dataAppName = codeFile.getName();
16064            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16065                    dataAppName, appId, seinfo);
16066        } else {
16067            move = null;
16068        }
16069
16070        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16071
16072        final Message msg = mHandler.obtainMessage(INIT_COPY);
16073        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16074        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16075                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16076        mHandler.sendMessage(msg);
16077    }
16078
16079    @Override
16080    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16081        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16082
16083        final int realMoveId = mNextMoveId.getAndIncrement();
16084        final Bundle extras = new Bundle();
16085        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16086        mMoveCallbacks.notifyCreated(realMoveId, extras);
16087
16088        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16089            @Override
16090            public void onCreated(int moveId, Bundle extras) {
16091                // Ignored
16092            }
16093
16094            @Override
16095            public void onStatusChanged(int moveId, int status, long estMillis) {
16096                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16097            }
16098        };
16099
16100        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16101        storage.setPrimaryStorageUuid(volumeUuid, callback);
16102        return realMoveId;
16103    }
16104
16105    @Override
16106    public int getMoveStatus(int moveId) {
16107        mContext.enforceCallingOrSelfPermission(
16108                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16109        return mMoveCallbacks.mLastStatus.get(moveId);
16110    }
16111
16112    @Override
16113    public void registerMoveCallback(IPackageMoveObserver callback) {
16114        mContext.enforceCallingOrSelfPermission(
16115                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16116        mMoveCallbacks.register(callback);
16117    }
16118
16119    @Override
16120    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16121        mContext.enforceCallingOrSelfPermission(
16122                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16123        mMoveCallbacks.unregister(callback);
16124    }
16125
16126    @Override
16127    public boolean setInstallLocation(int loc) {
16128        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16129                null);
16130        if (getInstallLocation() == loc) {
16131            return true;
16132        }
16133        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16134                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16135            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16136                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16137            return true;
16138        }
16139        return false;
16140   }
16141
16142    @Override
16143    public int getInstallLocation() {
16144        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16145                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16146                PackageHelper.APP_INSTALL_AUTO);
16147    }
16148
16149    /** Called by UserManagerService */
16150    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16151        mDirtyUsers.remove(userHandle);
16152        mSettings.removeUserLPw(userHandle);
16153        mPendingBroadcasts.remove(userHandle);
16154        if (mInstaller != null) {
16155            // Technically, we shouldn't be doing this with the package lock
16156            // held.  However, this is very rare, and there is already so much
16157            // other disk I/O going on, that we'll let it slide for now.
16158            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16159            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16160                final String volumeUuid = vol.getFsUuid();
16161                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16162                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16163            }
16164        }
16165        mUserNeedsBadging.delete(userHandle);
16166        removeUnusedPackagesLILPw(userManager, userHandle);
16167    }
16168
16169    /**
16170     * We're removing userHandle and would like to remove any downloaded packages
16171     * that are no longer in use by any other user.
16172     * @param userHandle the user being removed
16173     */
16174    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16175        final boolean DEBUG_CLEAN_APKS = false;
16176        int [] users = userManager.getUserIdsLPr();
16177        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16178        while (psit.hasNext()) {
16179            PackageSetting ps = psit.next();
16180            if (ps.pkg == null) {
16181                continue;
16182            }
16183            final String packageName = ps.pkg.packageName;
16184            // Skip over if system app
16185            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16186                continue;
16187            }
16188            if (DEBUG_CLEAN_APKS) {
16189                Slog.i(TAG, "Checking package " + packageName);
16190            }
16191            boolean keep = false;
16192            for (int i = 0; i < users.length; i++) {
16193                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16194                    keep = true;
16195                    if (DEBUG_CLEAN_APKS) {
16196                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16197                                + users[i]);
16198                    }
16199                    break;
16200                }
16201            }
16202            if (!keep) {
16203                if (DEBUG_CLEAN_APKS) {
16204                    Slog.i(TAG, "  Removing package " + packageName);
16205                }
16206                mHandler.post(new Runnable() {
16207                    public void run() {
16208                        deletePackageX(packageName, userHandle, 0);
16209                    } //end run
16210                });
16211            }
16212        }
16213    }
16214
16215    /** Called by UserManagerService */
16216    void createNewUserLILPw(int userHandle) {
16217        if (mInstaller != null) {
16218            mInstaller.createUserConfig(userHandle);
16219            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16220            applyFactoryDefaultBrowserLPw(userHandle);
16221            primeDomainVerificationsLPw(userHandle);
16222        }
16223    }
16224
16225    void newUserCreated(final int userHandle) {
16226        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16227    }
16228
16229    @Override
16230    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16231        mContext.enforceCallingOrSelfPermission(
16232                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16233                "Only package verification agents can read the verifier device identity");
16234
16235        synchronized (mPackages) {
16236            return mSettings.getVerifierDeviceIdentityLPw();
16237        }
16238    }
16239
16240    @Override
16241    public void setPermissionEnforced(String permission, boolean enforced) {
16242        // TODO: Now that we no longer change GID for storage, this should to away.
16243        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16244                "setPermissionEnforced");
16245        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16246            synchronized (mPackages) {
16247                if (mSettings.mReadExternalStorageEnforced == null
16248                        || mSettings.mReadExternalStorageEnforced != enforced) {
16249                    mSettings.mReadExternalStorageEnforced = enforced;
16250                    mSettings.writeLPr();
16251                }
16252            }
16253            // kill any non-foreground processes so we restart them and
16254            // grant/revoke the GID.
16255            final IActivityManager am = ActivityManagerNative.getDefault();
16256            if (am != null) {
16257                final long token = Binder.clearCallingIdentity();
16258                try {
16259                    am.killProcessesBelowForeground("setPermissionEnforcement");
16260                } catch (RemoteException e) {
16261                } finally {
16262                    Binder.restoreCallingIdentity(token);
16263                }
16264            }
16265        } else {
16266            throw new IllegalArgumentException("No selective enforcement for " + permission);
16267        }
16268    }
16269
16270    @Override
16271    @Deprecated
16272    public boolean isPermissionEnforced(String permission) {
16273        return true;
16274    }
16275
16276    @Override
16277    public boolean isStorageLow() {
16278        final long token = Binder.clearCallingIdentity();
16279        try {
16280            final DeviceStorageMonitorInternal
16281                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16282            if (dsm != null) {
16283                return dsm.isMemoryLow();
16284            } else {
16285                return false;
16286            }
16287        } finally {
16288            Binder.restoreCallingIdentity(token);
16289        }
16290    }
16291
16292    @Override
16293    public IPackageInstaller getPackageInstaller() {
16294        return mInstallerService;
16295    }
16296
16297    private boolean userNeedsBadging(int userId) {
16298        int index = mUserNeedsBadging.indexOfKey(userId);
16299        if (index < 0) {
16300            final UserInfo userInfo;
16301            final long token = Binder.clearCallingIdentity();
16302            try {
16303                userInfo = sUserManager.getUserInfo(userId);
16304            } finally {
16305                Binder.restoreCallingIdentity(token);
16306            }
16307            final boolean b;
16308            if (userInfo != null && userInfo.isManagedProfile()) {
16309                b = true;
16310            } else {
16311                b = false;
16312            }
16313            mUserNeedsBadging.put(userId, b);
16314            return b;
16315        }
16316        return mUserNeedsBadging.valueAt(index);
16317    }
16318
16319    @Override
16320    public KeySet getKeySetByAlias(String packageName, String alias) {
16321        if (packageName == null || alias == null) {
16322            return null;
16323        }
16324        synchronized(mPackages) {
16325            final PackageParser.Package pkg = mPackages.get(packageName);
16326            if (pkg == null) {
16327                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16328                throw new IllegalArgumentException("Unknown package: " + packageName);
16329            }
16330            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16331            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16332        }
16333    }
16334
16335    @Override
16336    public KeySet getSigningKeySet(String packageName) {
16337        if (packageName == null) {
16338            return null;
16339        }
16340        synchronized(mPackages) {
16341            final PackageParser.Package pkg = mPackages.get(packageName);
16342            if (pkg == null) {
16343                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16344                throw new IllegalArgumentException("Unknown package: " + packageName);
16345            }
16346            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16347                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16348                throw new SecurityException("May not access signing KeySet of other apps.");
16349            }
16350            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16351            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16352        }
16353    }
16354
16355    @Override
16356    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16357        if (packageName == null || ks == null) {
16358            return false;
16359        }
16360        synchronized(mPackages) {
16361            final PackageParser.Package pkg = mPackages.get(packageName);
16362            if (pkg == null) {
16363                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16364                throw new IllegalArgumentException("Unknown package: " + packageName);
16365            }
16366            IBinder ksh = ks.getToken();
16367            if (ksh instanceof KeySetHandle) {
16368                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16369                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16370            }
16371            return false;
16372        }
16373    }
16374
16375    @Override
16376    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16377        if (packageName == null || ks == null) {
16378            return false;
16379        }
16380        synchronized(mPackages) {
16381            final PackageParser.Package pkg = mPackages.get(packageName);
16382            if (pkg == null) {
16383                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16384                throw new IllegalArgumentException("Unknown package: " + packageName);
16385            }
16386            IBinder ksh = ks.getToken();
16387            if (ksh instanceof KeySetHandle) {
16388                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16389                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16390            }
16391            return false;
16392        }
16393    }
16394
16395    public void getUsageStatsIfNoPackageUsageInfo() {
16396        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16397            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16398            if (usm == null) {
16399                throw new IllegalStateException("UsageStatsManager must be initialized");
16400            }
16401            long now = System.currentTimeMillis();
16402            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16403            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16404                String packageName = entry.getKey();
16405                PackageParser.Package pkg = mPackages.get(packageName);
16406                if (pkg == null) {
16407                    continue;
16408                }
16409                UsageStats usage = entry.getValue();
16410                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16411                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16412            }
16413        }
16414    }
16415
16416    /**
16417     * Check and throw if the given before/after packages would be considered a
16418     * downgrade.
16419     */
16420    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16421            throws PackageManagerException {
16422        if (after.versionCode < before.mVersionCode) {
16423            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16424                    "Update version code " + after.versionCode + " is older than current "
16425                    + before.mVersionCode);
16426        } else if (after.versionCode == before.mVersionCode) {
16427            if (after.baseRevisionCode < before.baseRevisionCode) {
16428                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16429                        "Update base revision code " + after.baseRevisionCode
16430                        + " is older than current " + before.baseRevisionCode);
16431            }
16432
16433            if (!ArrayUtils.isEmpty(after.splitNames)) {
16434                for (int i = 0; i < after.splitNames.length; i++) {
16435                    final String splitName = after.splitNames[i];
16436                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16437                    if (j != -1) {
16438                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16439                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16440                                    "Update split " + splitName + " revision code "
16441                                    + after.splitRevisionCodes[i] + " is older than current "
16442                                    + before.splitRevisionCodes[j]);
16443                        }
16444                    }
16445                }
16446            }
16447        }
16448    }
16449
16450    private static class MoveCallbacks extends Handler {
16451        private static final int MSG_CREATED = 1;
16452        private static final int MSG_STATUS_CHANGED = 2;
16453
16454        private final RemoteCallbackList<IPackageMoveObserver>
16455                mCallbacks = new RemoteCallbackList<>();
16456
16457        private final SparseIntArray mLastStatus = new SparseIntArray();
16458
16459        public MoveCallbacks(Looper looper) {
16460            super(looper);
16461        }
16462
16463        public void register(IPackageMoveObserver callback) {
16464            mCallbacks.register(callback);
16465        }
16466
16467        public void unregister(IPackageMoveObserver callback) {
16468            mCallbacks.unregister(callback);
16469        }
16470
16471        @Override
16472        public void handleMessage(Message msg) {
16473            final SomeArgs args = (SomeArgs) msg.obj;
16474            final int n = mCallbacks.beginBroadcast();
16475            for (int i = 0; i < n; i++) {
16476                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16477                try {
16478                    invokeCallback(callback, msg.what, args);
16479                } catch (RemoteException ignored) {
16480                }
16481            }
16482            mCallbacks.finishBroadcast();
16483            args.recycle();
16484        }
16485
16486        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16487                throws RemoteException {
16488            switch (what) {
16489                case MSG_CREATED: {
16490                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16491                    break;
16492                }
16493                case MSG_STATUS_CHANGED: {
16494                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16495                    break;
16496                }
16497            }
16498        }
16499
16500        private void notifyCreated(int moveId, Bundle extras) {
16501            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16502
16503            final SomeArgs args = SomeArgs.obtain();
16504            args.argi1 = moveId;
16505            args.arg2 = extras;
16506            obtainMessage(MSG_CREATED, args).sendToTarget();
16507        }
16508
16509        private void notifyStatusChanged(int moveId, int status) {
16510            notifyStatusChanged(moveId, status, -1);
16511        }
16512
16513        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16514            Slog.v(TAG, "Move " + moveId + " status " + status);
16515
16516            final SomeArgs args = SomeArgs.obtain();
16517            args.argi1 = moveId;
16518            args.argi2 = status;
16519            args.arg3 = estMillis;
16520            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16521
16522            synchronized (mLastStatus) {
16523                mLastStatus.put(moveId, status);
16524            }
16525        }
16526    }
16527
16528    private final class OnPermissionChangeListeners extends Handler {
16529        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16530
16531        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16532                new RemoteCallbackList<>();
16533
16534        public OnPermissionChangeListeners(Looper looper) {
16535            super(looper);
16536        }
16537
16538        @Override
16539        public void handleMessage(Message msg) {
16540            switch (msg.what) {
16541                case MSG_ON_PERMISSIONS_CHANGED: {
16542                    final int uid = msg.arg1;
16543                    handleOnPermissionsChanged(uid);
16544                } break;
16545            }
16546        }
16547
16548        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16549            mPermissionListeners.register(listener);
16550
16551        }
16552
16553        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16554            mPermissionListeners.unregister(listener);
16555        }
16556
16557        public void onPermissionsChanged(int uid) {
16558            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16559                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16560            }
16561        }
16562
16563        private void handleOnPermissionsChanged(int uid) {
16564            final int count = mPermissionListeners.beginBroadcast();
16565            try {
16566                for (int i = 0; i < count; i++) {
16567                    IOnPermissionsChangeListener callback = mPermissionListeners
16568                            .getBroadcastItem(i);
16569                    try {
16570                        callback.onPermissionsChanged(uid);
16571                    } catch (RemoteException e) {
16572                        Log.e(TAG, "Permission listener is dead", e);
16573                    }
16574                }
16575            } finally {
16576                mPermissionListeners.finishBroadcast();
16577            }
16578        }
16579    }
16580
16581    private class PackageManagerInternalImpl extends PackageManagerInternal {
16582        @Override
16583        public void setLocationPackagesProvider(PackagesProvider provider) {
16584            synchronized (mPackages) {
16585                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16586            }
16587        }
16588
16589        @Override
16590        public void setImePackagesProvider(PackagesProvider provider) {
16591            synchronized (mPackages) {
16592                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16593            }
16594        }
16595
16596        @Override
16597        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16598            synchronized (mPackages) {
16599                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16600            }
16601        }
16602
16603        @Override
16604        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16605            synchronized (mPackages) {
16606                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16607            }
16608        }
16609
16610        @Override
16611        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16612            synchronized (mPackages) {
16613                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16614            }
16615        }
16616
16617        @Override
16618        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16619            synchronized (mPackages) {
16620                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16621            }
16622        }
16623
16624        @Override
16625        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16626            synchronized (mPackages) {
16627                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16628            }
16629        }
16630
16631        @Override
16632        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16633            synchronized (mPackages) {
16634                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16635                        packageName, userId);
16636            }
16637        }
16638
16639        @Override
16640        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16641            synchronized (mPackages) {
16642                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16643                        packageName, userId);
16644            }
16645        }
16646        @Override
16647        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16648            synchronized (mPackages) {
16649                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16650                        packageName, userId);
16651            }
16652        }
16653    }
16654
16655    @Override
16656    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16657        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16658        synchronized (mPackages) {
16659            final long identity = Binder.clearCallingIdentity();
16660            try {
16661                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16662                        packageNames, userId);
16663            } finally {
16664                Binder.restoreCallingIdentity(identity);
16665            }
16666        }
16667    }
16668
16669    private static void enforceSystemOrPhoneCaller(String tag) {
16670        int callingUid = Binder.getCallingUid();
16671        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16672            throw new SecurityException(
16673                    "Cannot call " + tag + " from UID " + callingUid);
16674        }
16675    }
16676}
16677