PackageManagerService.java revision 6499a85a30e59a33ee643e9fda7d36d794716769
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            // clear only after permissions have been updated
2287            mExistingSystemPackages.clear();
2288            mPromoteSystemApps = false;
2289
2290            // If this is the first boot, and it is a normal boot, then
2291            // we need to initialize the default preferred apps.
2292            if (!mRestoredSettings && !onlyCore) {
2293                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2294                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2295                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
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            // All the changes are done during package scanning.
2314            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2315
2316            // can downgrade to reader
2317            mSettings.writeLPr();
2318
2319            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2320                    SystemClock.uptimeMillis());
2321
2322            mRequiredVerifierPackage = getRequiredVerifierLPr();
2323            mRequiredInstallerPackage = getRequiredInstallerLPr();
2324
2325            mInstallerService = new PackageInstallerService(context, this);
2326
2327            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2328            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2329                    mIntentFilterVerifierComponent);
2330
2331        } // synchronized (mPackages)
2332        } // synchronized (mInstallLock)
2333
2334        // Now after opening every single application zip, make sure they
2335        // are all flushed.  Not really needed, but keeps things nice and
2336        // tidy.
2337        Runtime.getRuntime().gc();
2338
2339        // Expose private service for system components to use.
2340        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2341    }
2342
2343    @Override
2344    public boolean isFirstBoot() {
2345        return !mRestoredSettings;
2346    }
2347
2348    @Override
2349    public boolean isOnlyCoreApps() {
2350        return mOnlyCore;
2351    }
2352
2353    @Override
2354    public boolean isUpgrade() {
2355        return mIsUpgrade;
2356    }
2357
2358    private String getRequiredVerifierLPr() {
2359        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2360        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2361                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2362
2363        String requiredVerifier = null;
2364
2365        final int N = receivers.size();
2366        for (int i = 0; i < N; i++) {
2367            final ResolveInfo info = receivers.get(i);
2368
2369            if (info.activityInfo == null) {
2370                continue;
2371            }
2372
2373            final String packageName = info.activityInfo.packageName;
2374
2375            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2376                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2377                continue;
2378            }
2379
2380            if (requiredVerifier != null) {
2381                throw new RuntimeException("There can be only one required verifier");
2382            }
2383
2384            requiredVerifier = packageName;
2385        }
2386
2387        return requiredVerifier;
2388    }
2389
2390    private String getRequiredInstallerLPr() {
2391        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2392        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2393        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2394
2395        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2396                PACKAGE_MIME_TYPE, 0, 0);
2397
2398        String requiredInstaller = null;
2399
2400        final int N = installers.size();
2401        for (int i = 0; i < N; i++) {
2402            final ResolveInfo info = installers.get(i);
2403            final String packageName = info.activityInfo.packageName;
2404
2405            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2406                continue;
2407            }
2408
2409            if (requiredInstaller != null) {
2410                throw new RuntimeException("There must be one required installer");
2411            }
2412
2413            requiredInstaller = packageName;
2414        }
2415
2416        if (requiredInstaller == null) {
2417            throw new RuntimeException("There must be one required installer");
2418        }
2419
2420        return requiredInstaller;
2421    }
2422
2423    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2424        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2425        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2426                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2427
2428        ComponentName verifierComponentName = null;
2429
2430        int priority = -1000;
2431        final int N = receivers.size();
2432        for (int i = 0; i < N; i++) {
2433            final ResolveInfo info = receivers.get(i);
2434
2435            if (info.activityInfo == null) {
2436                continue;
2437            }
2438
2439            final String packageName = info.activityInfo.packageName;
2440
2441            final PackageSetting ps = mSettings.mPackages.get(packageName);
2442            if (ps == null) {
2443                continue;
2444            }
2445
2446            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2447                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2448                continue;
2449            }
2450
2451            // Select the IntentFilterVerifier with the highest priority
2452            if (priority < info.priority) {
2453                priority = info.priority;
2454                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2455                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2456                        + verifierComponentName + " with priority: " + info.priority);
2457            }
2458        }
2459
2460        return verifierComponentName;
2461    }
2462
2463    private void primeDomainVerificationsLPw(int userId) {
2464        if (DEBUG_DOMAIN_VERIFICATION) {
2465            Slog.d(TAG, "Priming domain verifications in user " + userId);
2466        }
2467
2468        SystemConfig systemConfig = SystemConfig.getInstance();
2469        ArraySet<String> packages = systemConfig.getLinkedApps();
2470        ArraySet<String> domains = new ArraySet<String>();
2471
2472        for (String packageName : packages) {
2473            PackageParser.Package pkg = mPackages.get(packageName);
2474            if (pkg != null) {
2475                if (!pkg.isSystemApp()) {
2476                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2477                    continue;
2478                }
2479
2480                domains.clear();
2481                for (PackageParser.Activity a : pkg.activities) {
2482                    for (ActivityIntentInfo filter : a.intents) {
2483                        if (hasValidDomains(filter)) {
2484                            domains.addAll(filter.getHostsList());
2485                        }
2486                    }
2487                }
2488
2489                if (domains.size() > 0) {
2490                    if (DEBUG_DOMAIN_VERIFICATION) {
2491                        Slog.v(TAG, "      + " + packageName);
2492                    }
2493                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2494                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2495                    // and then 'always' in the per-user state actually used for intent resolution.
2496                    final IntentFilterVerificationInfo ivi;
2497                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2498                            new ArrayList<String>(domains));
2499                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2500                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2501                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2502                } else {
2503                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2504                            + "' does not handle web links");
2505                }
2506            } else {
2507                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2508            }
2509        }
2510
2511        scheduleWritePackageRestrictionsLocked(userId);
2512        scheduleWriteSettingsLocked();
2513    }
2514
2515    private void applyFactoryDefaultBrowserLPw(int userId) {
2516        // The default browser app's package name is stored in a string resource,
2517        // with a product-specific overlay used for vendor customization.
2518        String browserPkg = mContext.getResources().getString(
2519                com.android.internal.R.string.default_browser);
2520        if (!TextUtils.isEmpty(browserPkg)) {
2521            // non-empty string => required to be a known package
2522            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2523            if (ps == null) {
2524                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2525                browserPkg = null;
2526            } else {
2527                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2528            }
2529        }
2530
2531        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2532        // default.  If there's more than one, just leave everything alone.
2533        if (browserPkg == null) {
2534            calculateDefaultBrowserLPw(userId);
2535        }
2536    }
2537
2538    private void calculateDefaultBrowserLPw(int userId) {
2539        List<String> allBrowsers = resolveAllBrowserApps(userId);
2540        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2541        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2542    }
2543
2544    private List<String> resolveAllBrowserApps(int userId) {
2545        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2546        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2547                PackageManager.MATCH_ALL, userId);
2548
2549        final int count = list.size();
2550        List<String> result = new ArrayList<String>(count);
2551        for (int i=0; i<count; i++) {
2552            ResolveInfo info = list.get(i);
2553            if (info.activityInfo == null
2554                    || !info.handleAllWebDataURI
2555                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2556                    || result.contains(info.activityInfo.packageName)) {
2557                continue;
2558            }
2559            result.add(info.activityInfo.packageName);
2560        }
2561
2562        return result;
2563    }
2564
2565    private boolean packageIsBrowser(String packageName, int userId) {
2566        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2567                PackageManager.MATCH_ALL, userId);
2568        final int N = list.size();
2569        for (int i = 0; i < N; i++) {
2570            ResolveInfo info = list.get(i);
2571            if (packageName.equals(info.activityInfo.packageName)) {
2572                return true;
2573            }
2574        }
2575        return false;
2576    }
2577
2578    private void checkDefaultBrowser() {
2579        final int myUserId = UserHandle.myUserId();
2580        final String packageName = getDefaultBrowserPackageName(myUserId);
2581        if (packageName != null) {
2582            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2583            if (info == null) {
2584                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2585                synchronized (mPackages) {
2586                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2587                }
2588            }
2589        }
2590    }
2591
2592    @Override
2593    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2594            throws RemoteException {
2595        try {
2596            return super.onTransact(code, data, reply, flags);
2597        } catch (RuntimeException e) {
2598            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2599                Slog.wtf(TAG, "Package Manager Crash", e);
2600            }
2601            throw e;
2602        }
2603    }
2604
2605    void cleanupInstallFailedPackage(PackageSetting ps) {
2606        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2607
2608        removeDataDirsLI(ps.volumeUuid, ps.name);
2609        if (ps.codePath != null) {
2610            if (ps.codePath.isDirectory()) {
2611                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2612            } else {
2613                ps.codePath.delete();
2614            }
2615        }
2616        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2617            if (ps.resourcePath.isDirectory()) {
2618                FileUtils.deleteContents(ps.resourcePath);
2619            }
2620            ps.resourcePath.delete();
2621        }
2622        mSettings.removePackageLPw(ps.name);
2623    }
2624
2625    static int[] appendInts(int[] cur, int[] add) {
2626        if (add == null) return cur;
2627        if (cur == null) return add;
2628        final int N = add.length;
2629        for (int i=0; i<N; i++) {
2630            cur = appendInt(cur, add[i]);
2631        }
2632        return cur;
2633    }
2634
2635    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2636        if (!sUserManager.exists(userId)) return null;
2637        final PackageSetting ps = (PackageSetting) p.mExtras;
2638        if (ps == null) {
2639            return null;
2640        }
2641
2642        final PermissionsState permissionsState = ps.getPermissionsState();
2643
2644        final int[] gids = permissionsState.computeGids(userId);
2645        final Set<String> permissions = permissionsState.getPermissions(userId);
2646        final PackageUserState state = ps.readUserState(userId);
2647
2648        return PackageParser.generatePackageInfo(p, gids, flags,
2649                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2650    }
2651
2652    @Override
2653    public boolean isPackageFrozen(String packageName) {
2654        synchronized (mPackages) {
2655            final PackageSetting ps = mSettings.mPackages.get(packageName);
2656            if (ps != null) {
2657                return ps.frozen;
2658            }
2659        }
2660        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2661        return true;
2662    }
2663
2664    @Override
2665    public boolean isPackageAvailable(String packageName, int userId) {
2666        if (!sUserManager.exists(userId)) return false;
2667        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2668        synchronized (mPackages) {
2669            PackageParser.Package p = mPackages.get(packageName);
2670            if (p != null) {
2671                final PackageSetting ps = (PackageSetting) p.mExtras;
2672                if (ps != null) {
2673                    final PackageUserState state = ps.readUserState(userId);
2674                    if (state != null) {
2675                        return PackageParser.isAvailable(state);
2676                    }
2677                }
2678            }
2679        }
2680        return false;
2681    }
2682
2683    @Override
2684    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2685        if (!sUserManager.exists(userId)) return null;
2686        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2687        // reader
2688        synchronized (mPackages) {
2689            PackageParser.Package p = mPackages.get(packageName);
2690            if (DEBUG_PACKAGE_INFO)
2691                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2692            if (p != null) {
2693                return generatePackageInfo(p, flags, userId);
2694            }
2695            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2696                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2697            }
2698        }
2699        return null;
2700    }
2701
2702    @Override
2703    public String[] currentToCanonicalPackageNames(String[] names) {
2704        String[] out = new String[names.length];
2705        // reader
2706        synchronized (mPackages) {
2707            for (int i=names.length-1; i>=0; i--) {
2708                PackageSetting ps = mSettings.mPackages.get(names[i]);
2709                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2710            }
2711        }
2712        return out;
2713    }
2714
2715    @Override
2716    public String[] canonicalToCurrentPackageNames(String[] names) {
2717        String[] out = new String[names.length];
2718        // reader
2719        synchronized (mPackages) {
2720            for (int i=names.length-1; i>=0; i--) {
2721                String cur = mSettings.mRenamedPackages.get(names[i]);
2722                out[i] = cur != null ? cur : names[i];
2723            }
2724        }
2725        return out;
2726    }
2727
2728    @Override
2729    public int getPackageUid(String packageName, int userId) {
2730        if (!sUserManager.exists(userId)) return -1;
2731        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2732
2733        // reader
2734        synchronized (mPackages) {
2735            PackageParser.Package p = mPackages.get(packageName);
2736            if(p != null) {
2737                return UserHandle.getUid(userId, p.applicationInfo.uid);
2738            }
2739            PackageSetting ps = mSettings.mPackages.get(packageName);
2740            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2741                return -1;
2742            }
2743            p = ps.pkg;
2744            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2745        }
2746    }
2747
2748    @Override
2749    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2750        if (!sUserManager.exists(userId)) {
2751            return null;
2752        }
2753
2754        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2755                "getPackageGids");
2756
2757        // reader
2758        synchronized (mPackages) {
2759            PackageParser.Package p = mPackages.get(packageName);
2760            if (DEBUG_PACKAGE_INFO) {
2761                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2762            }
2763            if (p != null) {
2764                PackageSetting ps = (PackageSetting) p.mExtras;
2765                return ps.getPermissionsState().computeGids(userId);
2766            }
2767        }
2768
2769        return null;
2770    }
2771
2772    static PermissionInfo generatePermissionInfo(
2773            BasePermission bp, int flags) {
2774        if (bp.perm != null) {
2775            return PackageParser.generatePermissionInfo(bp.perm, flags);
2776        }
2777        PermissionInfo pi = new PermissionInfo();
2778        pi.name = bp.name;
2779        pi.packageName = bp.sourcePackage;
2780        pi.nonLocalizedLabel = bp.name;
2781        pi.protectionLevel = bp.protectionLevel;
2782        return pi;
2783    }
2784
2785    @Override
2786    public PermissionInfo getPermissionInfo(String name, int flags) {
2787        // reader
2788        synchronized (mPackages) {
2789            final BasePermission p = mSettings.mPermissions.get(name);
2790            if (p != null) {
2791                return generatePermissionInfo(p, flags);
2792            }
2793            return null;
2794        }
2795    }
2796
2797    @Override
2798    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2799        // reader
2800        synchronized (mPackages) {
2801            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2802            for (BasePermission p : mSettings.mPermissions.values()) {
2803                if (group == null) {
2804                    if (p.perm == null || p.perm.info.group == null) {
2805                        out.add(generatePermissionInfo(p, flags));
2806                    }
2807                } else {
2808                    if (p.perm != null && group.equals(p.perm.info.group)) {
2809                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2810                    }
2811                }
2812            }
2813
2814            if (out.size() > 0) {
2815                return out;
2816            }
2817            return mPermissionGroups.containsKey(group) ? out : null;
2818        }
2819    }
2820
2821    @Override
2822    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2823        // reader
2824        synchronized (mPackages) {
2825            return PackageParser.generatePermissionGroupInfo(
2826                    mPermissionGroups.get(name), flags);
2827        }
2828    }
2829
2830    @Override
2831    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2832        // reader
2833        synchronized (mPackages) {
2834            final int N = mPermissionGroups.size();
2835            ArrayList<PermissionGroupInfo> out
2836                    = new ArrayList<PermissionGroupInfo>(N);
2837            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2838                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2839            }
2840            return out;
2841        }
2842    }
2843
2844    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2845            int userId) {
2846        if (!sUserManager.exists(userId)) return null;
2847        PackageSetting ps = mSettings.mPackages.get(packageName);
2848        if (ps != null) {
2849            if (ps.pkg == null) {
2850                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2851                        flags, userId);
2852                if (pInfo != null) {
2853                    return pInfo.applicationInfo;
2854                }
2855                return null;
2856            }
2857            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2858                    ps.readUserState(userId), userId);
2859        }
2860        return null;
2861    }
2862
2863    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2864            int userId) {
2865        if (!sUserManager.exists(userId)) return null;
2866        PackageSetting ps = mSettings.mPackages.get(packageName);
2867        if (ps != null) {
2868            PackageParser.Package pkg = ps.pkg;
2869            if (pkg == null) {
2870                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2871                    return null;
2872                }
2873                // Only data remains, so we aren't worried about code paths
2874                pkg = new PackageParser.Package(packageName);
2875                pkg.applicationInfo.packageName = packageName;
2876                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2877                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2878                pkg.applicationInfo.dataDir = Environment
2879                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2880                        .getAbsolutePath();
2881                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2882                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2883            }
2884            return generatePackageInfo(pkg, flags, userId);
2885        }
2886        return null;
2887    }
2888
2889    @Override
2890    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2891        if (!sUserManager.exists(userId)) return null;
2892        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2893        // writer
2894        synchronized (mPackages) {
2895            PackageParser.Package p = mPackages.get(packageName);
2896            if (DEBUG_PACKAGE_INFO) Log.v(
2897                    TAG, "getApplicationInfo " + packageName
2898                    + ": " + p);
2899            if (p != null) {
2900                PackageSetting ps = mSettings.mPackages.get(packageName);
2901                if (ps == null) return null;
2902                // Note: isEnabledLP() does not apply here - always return info
2903                return PackageParser.generateApplicationInfo(
2904                        p, flags, ps.readUserState(userId), userId);
2905            }
2906            if ("android".equals(packageName)||"system".equals(packageName)) {
2907                return mAndroidApplication;
2908            }
2909            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2910                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2911            }
2912        }
2913        return null;
2914    }
2915
2916    @Override
2917    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2918            final IPackageDataObserver observer) {
2919        mContext.enforceCallingOrSelfPermission(
2920                android.Manifest.permission.CLEAR_APP_CACHE, null);
2921        // Queue up an async operation since clearing cache may take a little while.
2922        mHandler.post(new Runnable() {
2923            public void run() {
2924                mHandler.removeCallbacks(this);
2925                int retCode = -1;
2926                synchronized (mInstallLock) {
2927                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2928                    if (retCode < 0) {
2929                        Slog.w(TAG, "Couldn't clear application caches");
2930                    }
2931                }
2932                if (observer != null) {
2933                    try {
2934                        observer.onRemoveCompleted(null, (retCode >= 0));
2935                    } catch (RemoteException e) {
2936                        Slog.w(TAG, "RemoveException when invoking call back");
2937                    }
2938                }
2939            }
2940        });
2941    }
2942
2943    @Override
2944    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2945            final IntentSender pi) {
2946        mContext.enforceCallingOrSelfPermission(
2947                android.Manifest.permission.CLEAR_APP_CACHE, null);
2948        // Queue up an async operation since clearing cache may take a little while.
2949        mHandler.post(new Runnable() {
2950            public void run() {
2951                mHandler.removeCallbacks(this);
2952                int retCode = -1;
2953                synchronized (mInstallLock) {
2954                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2955                    if (retCode < 0) {
2956                        Slog.w(TAG, "Couldn't clear application caches");
2957                    }
2958                }
2959                if(pi != null) {
2960                    try {
2961                        // Callback via pending intent
2962                        int code = (retCode >= 0) ? 1 : 0;
2963                        pi.sendIntent(null, code, null,
2964                                null, null);
2965                    } catch (SendIntentException e1) {
2966                        Slog.i(TAG, "Failed to send pending intent");
2967                    }
2968                }
2969            }
2970        });
2971    }
2972
2973    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2974        synchronized (mInstallLock) {
2975            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2976                throw new IOException("Failed to free enough space");
2977            }
2978        }
2979    }
2980
2981    @Override
2982    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2983        if (!sUserManager.exists(userId)) return null;
2984        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2985        synchronized (mPackages) {
2986            PackageParser.Activity a = mActivities.mActivities.get(component);
2987
2988            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2989            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2990                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2991                if (ps == null) return null;
2992                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2993                        userId);
2994            }
2995            if (mResolveComponentName.equals(component)) {
2996                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2997                        new PackageUserState(), userId);
2998            }
2999        }
3000        return null;
3001    }
3002
3003    @Override
3004    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3005            String resolvedType) {
3006        synchronized (mPackages) {
3007            if (component.equals(mResolveComponentName)) {
3008                // The resolver supports EVERYTHING!
3009                return true;
3010            }
3011            PackageParser.Activity a = mActivities.mActivities.get(component);
3012            if (a == null) {
3013                return false;
3014            }
3015            for (int i=0; i<a.intents.size(); i++) {
3016                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3017                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3018                    return true;
3019                }
3020            }
3021            return false;
3022        }
3023    }
3024
3025    @Override
3026    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3027        if (!sUserManager.exists(userId)) return null;
3028        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3029        synchronized (mPackages) {
3030            PackageParser.Activity a = mReceivers.mActivities.get(component);
3031            if (DEBUG_PACKAGE_INFO) Log.v(
3032                TAG, "getReceiverInfo " + component + ": " + a);
3033            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3034                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3035                if (ps == null) return null;
3036                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3037                        userId);
3038            }
3039        }
3040        return null;
3041    }
3042
3043    @Override
3044    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3045        if (!sUserManager.exists(userId)) return null;
3046        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3047        synchronized (mPackages) {
3048            PackageParser.Service s = mServices.mServices.get(component);
3049            if (DEBUG_PACKAGE_INFO) Log.v(
3050                TAG, "getServiceInfo " + component + ": " + s);
3051            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3052                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3053                if (ps == null) return null;
3054                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3055                        userId);
3056            }
3057        }
3058        return null;
3059    }
3060
3061    @Override
3062    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3063        if (!sUserManager.exists(userId)) return null;
3064        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3065        synchronized (mPackages) {
3066            PackageParser.Provider p = mProviders.mProviders.get(component);
3067            if (DEBUG_PACKAGE_INFO) Log.v(
3068                TAG, "getProviderInfo " + component + ": " + p);
3069            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3070                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3071                if (ps == null) return null;
3072                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3073                        userId);
3074            }
3075        }
3076        return null;
3077    }
3078
3079    @Override
3080    public String[] getSystemSharedLibraryNames() {
3081        Set<String> libSet;
3082        synchronized (mPackages) {
3083            libSet = mSharedLibraries.keySet();
3084            int size = libSet.size();
3085            if (size > 0) {
3086                String[] libs = new String[size];
3087                libSet.toArray(libs);
3088                return libs;
3089            }
3090        }
3091        return null;
3092    }
3093
3094    /**
3095     * @hide
3096     */
3097    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3098        synchronized (mPackages) {
3099            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3100            if (lib != null && lib.apk != null) {
3101                return mPackages.get(lib.apk);
3102            }
3103        }
3104        return null;
3105    }
3106
3107    @Override
3108    public FeatureInfo[] getSystemAvailableFeatures() {
3109        Collection<FeatureInfo> featSet;
3110        synchronized (mPackages) {
3111            featSet = mAvailableFeatures.values();
3112            int size = featSet.size();
3113            if (size > 0) {
3114                FeatureInfo[] features = new FeatureInfo[size+1];
3115                featSet.toArray(features);
3116                FeatureInfo fi = new FeatureInfo();
3117                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3118                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3119                features[size] = fi;
3120                return features;
3121            }
3122        }
3123        return null;
3124    }
3125
3126    @Override
3127    public boolean hasSystemFeature(String name) {
3128        synchronized (mPackages) {
3129            return mAvailableFeatures.containsKey(name);
3130        }
3131    }
3132
3133    private void checkValidCaller(int uid, int userId) {
3134        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3135            return;
3136
3137        throw new SecurityException("Caller uid=" + uid
3138                + " is not privileged to communicate with user=" + userId);
3139    }
3140
3141    @Override
3142    public int checkPermission(String permName, String pkgName, int userId) {
3143        if (!sUserManager.exists(userId)) {
3144            return PackageManager.PERMISSION_DENIED;
3145        }
3146
3147        synchronized (mPackages) {
3148            final PackageParser.Package p = mPackages.get(pkgName);
3149            if (p != null && p.mExtras != null) {
3150                final PackageSetting ps = (PackageSetting) p.mExtras;
3151                final PermissionsState permissionsState = ps.getPermissionsState();
3152                if (permissionsState.hasPermission(permName, userId)) {
3153                    return PackageManager.PERMISSION_GRANTED;
3154                }
3155                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3156                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3157                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3158                    return PackageManager.PERMISSION_GRANTED;
3159                }
3160            }
3161        }
3162
3163        return PackageManager.PERMISSION_DENIED;
3164    }
3165
3166    @Override
3167    public int checkUidPermission(String permName, int uid) {
3168        final int userId = UserHandle.getUserId(uid);
3169
3170        if (!sUserManager.exists(userId)) {
3171            return PackageManager.PERMISSION_DENIED;
3172        }
3173
3174        synchronized (mPackages) {
3175            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3176            if (obj != null) {
3177                final SettingBase ps = (SettingBase) obj;
3178                final PermissionsState permissionsState = ps.getPermissionsState();
3179                if (permissionsState.hasPermission(permName, userId)) {
3180                    return PackageManager.PERMISSION_GRANTED;
3181                }
3182                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3183                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3184                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3185                    return PackageManager.PERMISSION_GRANTED;
3186                }
3187            } else {
3188                ArraySet<String> perms = mSystemPermissions.get(uid);
3189                if (perms != null) {
3190                    if (perms.contains(permName)) {
3191                        return PackageManager.PERMISSION_GRANTED;
3192                    }
3193                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3194                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3195                        return PackageManager.PERMISSION_GRANTED;
3196                    }
3197                }
3198            }
3199        }
3200
3201        return PackageManager.PERMISSION_DENIED;
3202    }
3203
3204    @Override
3205    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3206        if (UserHandle.getCallingUserId() != userId) {
3207            mContext.enforceCallingPermission(
3208                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3209                    "isPermissionRevokedByPolicy for user " + userId);
3210        }
3211
3212        if (checkPermission(permission, packageName, userId)
3213                == PackageManager.PERMISSION_GRANTED) {
3214            return false;
3215        }
3216
3217        final long identity = Binder.clearCallingIdentity();
3218        try {
3219            final int flags = getPermissionFlags(permission, packageName, userId);
3220            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3221        } finally {
3222            Binder.restoreCallingIdentity(identity);
3223        }
3224    }
3225
3226    @Override
3227    public String getPermissionControllerPackageName() {
3228        synchronized (mPackages) {
3229            return mRequiredInstallerPackage;
3230        }
3231    }
3232
3233    /**
3234     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3235     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3236     * @param checkShell TODO(yamasani):
3237     * @param message the message to log on security exception
3238     */
3239    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3240            boolean checkShell, String message) {
3241        if (userId < 0) {
3242            throw new IllegalArgumentException("Invalid userId " + userId);
3243        }
3244        if (checkShell) {
3245            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3246        }
3247        if (userId == UserHandle.getUserId(callingUid)) return;
3248        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3249            if (requireFullPermission) {
3250                mContext.enforceCallingOrSelfPermission(
3251                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3252            } else {
3253                try {
3254                    mContext.enforceCallingOrSelfPermission(
3255                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3256                } catch (SecurityException se) {
3257                    mContext.enforceCallingOrSelfPermission(
3258                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3259                }
3260            }
3261        }
3262    }
3263
3264    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3265        if (callingUid == Process.SHELL_UID) {
3266            if (userHandle >= 0
3267                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3268                throw new SecurityException("Shell does not have permission to access user "
3269                        + userHandle);
3270            } else if (userHandle < 0) {
3271                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3272                        + Debug.getCallers(3));
3273            }
3274        }
3275    }
3276
3277    private BasePermission findPermissionTreeLP(String permName) {
3278        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3279            if (permName.startsWith(bp.name) &&
3280                    permName.length() > bp.name.length() &&
3281                    permName.charAt(bp.name.length()) == '.') {
3282                return bp;
3283            }
3284        }
3285        return null;
3286    }
3287
3288    private BasePermission checkPermissionTreeLP(String permName) {
3289        if (permName != null) {
3290            BasePermission bp = findPermissionTreeLP(permName);
3291            if (bp != null) {
3292                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3293                    return bp;
3294                }
3295                throw new SecurityException("Calling uid "
3296                        + Binder.getCallingUid()
3297                        + " is not allowed to add to permission tree "
3298                        + bp.name + " owned by uid " + bp.uid);
3299            }
3300        }
3301        throw new SecurityException("No permission tree found for " + permName);
3302    }
3303
3304    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3305        if (s1 == null) {
3306            return s2 == null;
3307        }
3308        if (s2 == null) {
3309            return false;
3310        }
3311        if (s1.getClass() != s2.getClass()) {
3312            return false;
3313        }
3314        return s1.equals(s2);
3315    }
3316
3317    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3318        if (pi1.icon != pi2.icon) return false;
3319        if (pi1.logo != pi2.logo) return false;
3320        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3321        if (!compareStrings(pi1.name, pi2.name)) return false;
3322        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3323        // We'll take care of setting this one.
3324        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3325        // These are not currently stored in settings.
3326        //if (!compareStrings(pi1.group, pi2.group)) return false;
3327        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3328        //if (pi1.labelRes != pi2.labelRes) return false;
3329        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3330        return true;
3331    }
3332
3333    int permissionInfoFootprint(PermissionInfo info) {
3334        int size = info.name.length();
3335        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3336        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3337        return size;
3338    }
3339
3340    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3341        int size = 0;
3342        for (BasePermission perm : mSettings.mPermissions.values()) {
3343            if (perm.uid == tree.uid) {
3344                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3345            }
3346        }
3347        return size;
3348    }
3349
3350    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3351        // We calculate the max size of permissions defined by this uid and throw
3352        // if that plus the size of 'info' would exceed our stated maximum.
3353        if (tree.uid != Process.SYSTEM_UID) {
3354            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3355            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3356                throw new SecurityException("Permission tree size cap exceeded");
3357            }
3358        }
3359    }
3360
3361    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3362        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3363            throw new SecurityException("Label must be specified in permission");
3364        }
3365        BasePermission tree = checkPermissionTreeLP(info.name);
3366        BasePermission bp = mSettings.mPermissions.get(info.name);
3367        boolean added = bp == null;
3368        boolean changed = true;
3369        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3370        if (added) {
3371            enforcePermissionCapLocked(info, tree);
3372            bp = new BasePermission(info.name, tree.sourcePackage,
3373                    BasePermission.TYPE_DYNAMIC);
3374        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3375            throw new SecurityException(
3376                    "Not allowed to modify non-dynamic permission "
3377                    + info.name);
3378        } else {
3379            if (bp.protectionLevel == fixedLevel
3380                    && bp.perm.owner.equals(tree.perm.owner)
3381                    && bp.uid == tree.uid
3382                    && comparePermissionInfos(bp.perm.info, info)) {
3383                changed = false;
3384            }
3385        }
3386        bp.protectionLevel = fixedLevel;
3387        info = new PermissionInfo(info);
3388        info.protectionLevel = fixedLevel;
3389        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3390        bp.perm.info.packageName = tree.perm.info.packageName;
3391        bp.uid = tree.uid;
3392        if (added) {
3393            mSettings.mPermissions.put(info.name, bp);
3394        }
3395        if (changed) {
3396            if (!async) {
3397                mSettings.writeLPr();
3398            } else {
3399                scheduleWriteSettingsLocked();
3400            }
3401        }
3402        return added;
3403    }
3404
3405    @Override
3406    public boolean addPermission(PermissionInfo info) {
3407        synchronized (mPackages) {
3408            return addPermissionLocked(info, false);
3409        }
3410    }
3411
3412    @Override
3413    public boolean addPermissionAsync(PermissionInfo info) {
3414        synchronized (mPackages) {
3415            return addPermissionLocked(info, true);
3416        }
3417    }
3418
3419    @Override
3420    public void removePermission(String name) {
3421        synchronized (mPackages) {
3422            checkPermissionTreeLP(name);
3423            BasePermission bp = mSettings.mPermissions.get(name);
3424            if (bp != null) {
3425                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3426                    throw new SecurityException(
3427                            "Not allowed to modify non-dynamic permission "
3428                            + name);
3429                }
3430                mSettings.mPermissions.remove(name);
3431                mSettings.writeLPr();
3432            }
3433        }
3434    }
3435
3436    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3437            BasePermission bp) {
3438        int index = pkg.requestedPermissions.indexOf(bp.name);
3439        if (index == -1) {
3440            throw new SecurityException("Package " + pkg.packageName
3441                    + " has not requested permission " + bp.name);
3442        }
3443        if (!bp.isRuntime() && !bp.isDevelopment()) {
3444            throw new SecurityException("Permission " + bp.name
3445                    + " is not a changeable permission type");
3446        }
3447    }
3448
3449    @Override
3450    public void grantRuntimePermission(String packageName, String name, final int userId) {
3451        if (!sUserManager.exists(userId)) {
3452            Log.e(TAG, "No such user:" + userId);
3453            return;
3454        }
3455
3456        mContext.enforceCallingOrSelfPermission(
3457                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3458                "grantRuntimePermission");
3459
3460        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3461                "grantRuntimePermission");
3462
3463        final int uid;
3464        final SettingBase sb;
3465
3466        synchronized (mPackages) {
3467            final PackageParser.Package pkg = mPackages.get(packageName);
3468            if (pkg == null) {
3469                throw new IllegalArgumentException("Unknown package: " + packageName);
3470            }
3471
3472            final BasePermission bp = mSettings.mPermissions.get(name);
3473            if (bp == null) {
3474                throw new IllegalArgumentException("Unknown permission: " + name);
3475            }
3476
3477            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3478
3479            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3480            sb = (SettingBase) pkg.mExtras;
3481            if (sb == null) {
3482                throw new IllegalArgumentException("Unknown package: " + packageName);
3483            }
3484
3485            final PermissionsState permissionsState = sb.getPermissionsState();
3486
3487            final int flags = permissionsState.getPermissionFlags(name, userId);
3488            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3489                throw new SecurityException("Cannot grant system fixed permission: "
3490                        + name + " for package: " + packageName);
3491            }
3492
3493            if (bp.isDevelopment()) {
3494                // Development permissions must be handled specially, since they are not
3495                // normal runtime permissions.  For now they apply to all users.
3496                if (permissionsState.grantInstallPermission(bp) !=
3497                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3498                    scheduleWriteSettingsLocked();
3499                }
3500                return;
3501            }
3502
3503            final int result = permissionsState.grantRuntimePermission(bp, userId);
3504            switch (result) {
3505                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3506                    return;
3507                }
3508
3509                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3510                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3511                    mHandler.post(new Runnable() {
3512                        @Override
3513                        public void run() {
3514                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3515                        }
3516                    });
3517                } break;
3518            }
3519
3520            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3521
3522            // Not critical if that is lost - app has to request again.
3523            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3524        }
3525
3526        // Only need to do this if user is initialized. Otherwise it's a new user
3527        // and there are no processes running as the user yet and there's no need
3528        // to make an expensive call to remount processes for the changed permissions.
3529        if (READ_EXTERNAL_STORAGE.equals(name)
3530                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3531            final long token = Binder.clearCallingIdentity();
3532            try {
3533                if (sUserManager.isInitialized(userId)) {
3534                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3535                            MountServiceInternal.class);
3536                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3537                }
3538            } finally {
3539                Binder.restoreCallingIdentity(token);
3540            }
3541        }
3542    }
3543
3544    @Override
3545    public void revokeRuntimePermission(String packageName, String name, int userId) {
3546        if (!sUserManager.exists(userId)) {
3547            Log.e(TAG, "No such user:" + userId);
3548            return;
3549        }
3550
3551        mContext.enforceCallingOrSelfPermission(
3552                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3553                "revokeRuntimePermission");
3554
3555        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3556                "revokeRuntimePermission");
3557
3558        final int appId;
3559
3560        synchronized (mPackages) {
3561            final PackageParser.Package pkg = mPackages.get(packageName);
3562            if (pkg == null) {
3563                throw new IllegalArgumentException("Unknown package: " + packageName);
3564            }
3565
3566            final BasePermission bp = mSettings.mPermissions.get(name);
3567            if (bp == null) {
3568                throw new IllegalArgumentException("Unknown permission: " + name);
3569            }
3570
3571            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3572
3573            SettingBase sb = (SettingBase) pkg.mExtras;
3574            if (sb == null) {
3575                throw new IllegalArgumentException("Unknown package: " + packageName);
3576            }
3577
3578            final PermissionsState permissionsState = sb.getPermissionsState();
3579
3580            final int flags = permissionsState.getPermissionFlags(name, userId);
3581            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3582                throw new SecurityException("Cannot revoke system fixed permission: "
3583                        + name + " for package: " + packageName);
3584            }
3585
3586            if (bp.isDevelopment()) {
3587                // Development permissions must be handled specially, since they are not
3588                // normal runtime permissions.  For now they apply to all users.
3589                if (permissionsState.revokeInstallPermission(bp) !=
3590                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3591                    scheduleWriteSettingsLocked();
3592                }
3593                return;
3594            }
3595
3596            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3597                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3598                return;
3599            }
3600
3601            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3602
3603            // Critical, after this call app should never have the permission.
3604            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3605
3606            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3607        }
3608
3609        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3610    }
3611
3612    @Override
3613    public void resetRuntimePermissions() {
3614        mContext.enforceCallingOrSelfPermission(
3615                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3616                "revokeRuntimePermission");
3617
3618        int callingUid = Binder.getCallingUid();
3619        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3620            mContext.enforceCallingOrSelfPermission(
3621                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3622                    "resetRuntimePermissions");
3623        }
3624
3625        synchronized (mPackages) {
3626            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3627            for (int userId : UserManagerService.getInstance().getUserIds()) {
3628                final int packageCount = mPackages.size();
3629                for (int i = 0; i < packageCount; i++) {
3630                    PackageParser.Package pkg = mPackages.valueAt(i);
3631                    if (!(pkg.mExtras instanceof PackageSetting)) {
3632                        continue;
3633                    }
3634                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3635                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3636                }
3637            }
3638        }
3639    }
3640
3641    @Override
3642    public int getPermissionFlags(String name, String packageName, int userId) {
3643        if (!sUserManager.exists(userId)) {
3644            return 0;
3645        }
3646
3647        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3648
3649        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3650                "getPermissionFlags");
3651
3652        synchronized (mPackages) {
3653            final PackageParser.Package pkg = mPackages.get(packageName);
3654            if (pkg == null) {
3655                throw new IllegalArgumentException("Unknown package: " + packageName);
3656            }
3657
3658            final BasePermission bp = mSettings.mPermissions.get(name);
3659            if (bp == null) {
3660                throw new IllegalArgumentException("Unknown permission: " + name);
3661            }
3662
3663            SettingBase sb = (SettingBase) pkg.mExtras;
3664            if (sb == null) {
3665                throw new IllegalArgumentException("Unknown package: " + packageName);
3666            }
3667
3668            PermissionsState permissionsState = sb.getPermissionsState();
3669            return permissionsState.getPermissionFlags(name, userId);
3670        }
3671    }
3672
3673    @Override
3674    public void updatePermissionFlags(String name, String packageName, int flagMask,
3675            int flagValues, int userId) {
3676        if (!sUserManager.exists(userId)) {
3677            return;
3678        }
3679
3680        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3681
3682        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3683                "updatePermissionFlags");
3684
3685        // Only the system can change these flags and nothing else.
3686        if (getCallingUid() != Process.SYSTEM_UID) {
3687            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3688            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3689            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3690            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3691        }
3692
3693        synchronized (mPackages) {
3694            final PackageParser.Package pkg = mPackages.get(packageName);
3695            if (pkg == null) {
3696                throw new IllegalArgumentException("Unknown package: " + packageName);
3697            }
3698
3699            final BasePermission bp = mSettings.mPermissions.get(name);
3700            if (bp == null) {
3701                throw new IllegalArgumentException("Unknown permission: " + name);
3702            }
3703
3704            SettingBase sb = (SettingBase) pkg.mExtras;
3705            if (sb == null) {
3706                throw new IllegalArgumentException("Unknown package: " + packageName);
3707            }
3708
3709            PermissionsState permissionsState = sb.getPermissionsState();
3710
3711            // Only the package manager can change flags for system component permissions.
3712            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3713            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3714                return;
3715            }
3716
3717            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3718
3719            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3720                // Install and runtime permissions are stored in different places,
3721                // so figure out what permission changed and persist the change.
3722                if (permissionsState.getInstallPermissionState(name) != null) {
3723                    scheduleWriteSettingsLocked();
3724                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3725                        || hadState) {
3726                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3727                }
3728            }
3729        }
3730    }
3731
3732    /**
3733     * Update the permission flags for all packages and runtime permissions of a user in order
3734     * to allow device or profile owner to remove POLICY_FIXED.
3735     */
3736    @Override
3737    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3738        if (!sUserManager.exists(userId)) {
3739            return;
3740        }
3741
3742        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3743
3744        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3745                "updatePermissionFlagsForAllApps");
3746
3747        // Only the system can change system fixed flags.
3748        if (getCallingUid() != Process.SYSTEM_UID) {
3749            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3750            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3751        }
3752
3753        synchronized (mPackages) {
3754            boolean changed = false;
3755            final int packageCount = mPackages.size();
3756            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3757                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3758                SettingBase sb = (SettingBase) pkg.mExtras;
3759                if (sb == null) {
3760                    continue;
3761                }
3762                PermissionsState permissionsState = sb.getPermissionsState();
3763                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3764                        userId, flagMask, flagValues);
3765            }
3766            if (changed) {
3767                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3768            }
3769        }
3770    }
3771
3772    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3773        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3774                != PackageManager.PERMISSION_GRANTED
3775            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3776                != PackageManager.PERMISSION_GRANTED) {
3777            throw new SecurityException(message + " requires "
3778                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3779                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3780        }
3781    }
3782
3783    @Override
3784    public boolean shouldShowRequestPermissionRationale(String permissionName,
3785            String packageName, int userId) {
3786        if (UserHandle.getCallingUserId() != userId) {
3787            mContext.enforceCallingPermission(
3788                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3789                    "canShowRequestPermissionRationale for user " + userId);
3790        }
3791
3792        final int uid = getPackageUid(packageName, userId);
3793        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3794            return false;
3795        }
3796
3797        if (checkPermission(permissionName, packageName, userId)
3798                == PackageManager.PERMISSION_GRANTED) {
3799            return false;
3800        }
3801
3802        final int flags;
3803
3804        final long identity = Binder.clearCallingIdentity();
3805        try {
3806            flags = getPermissionFlags(permissionName,
3807                    packageName, userId);
3808        } finally {
3809            Binder.restoreCallingIdentity(identity);
3810        }
3811
3812        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3813                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3814                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3815
3816        if ((flags & fixedFlags) != 0) {
3817            return false;
3818        }
3819
3820        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3821    }
3822
3823    @Override
3824    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3825        mContext.enforceCallingOrSelfPermission(
3826                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3827                "addOnPermissionsChangeListener");
3828
3829        synchronized (mPackages) {
3830            mOnPermissionChangeListeners.addListenerLocked(listener);
3831        }
3832    }
3833
3834    @Override
3835    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3836        synchronized (mPackages) {
3837            mOnPermissionChangeListeners.removeListenerLocked(listener);
3838        }
3839    }
3840
3841    @Override
3842    public boolean isProtectedBroadcast(String actionName) {
3843        synchronized (mPackages) {
3844            return mProtectedBroadcasts.contains(actionName);
3845        }
3846    }
3847
3848    @Override
3849    public int checkSignatures(String pkg1, String pkg2) {
3850        synchronized (mPackages) {
3851            final PackageParser.Package p1 = mPackages.get(pkg1);
3852            final PackageParser.Package p2 = mPackages.get(pkg2);
3853            if (p1 == null || p1.mExtras == null
3854                    || p2 == null || p2.mExtras == null) {
3855                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3856            }
3857            return compareSignatures(p1.mSignatures, p2.mSignatures);
3858        }
3859    }
3860
3861    @Override
3862    public int checkUidSignatures(int uid1, int uid2) {
3863        // Map to base uids.
3864        uid1 = UserHandle.getAppId(uid1);
3865        uid2 = UserHandle.getAppId(uid2);
3866        // reader
3867        synchronized (mPackages) {
3868            Signature[] s1;
3869            Signature[] s2;
3870            Object obj = mSettings.getUserIdLPr(uid1);
3871            if (obj != null) {
3872                if (obj instanceof SharedUserSetting) {
3873                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3874                } else if (obj instanceof PackageSetting) {
3875                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3876                } else {
3877                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3878                }
3879            } else {
3880                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3881            }
3882            obj = mSettings.getUserIdLPr(uid2);
3883            if (obj != null) {
3884                if (obj instanceof SharedUserSetting) {
3885                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3886                } else if (obj instanceof PackageSetting) {
3887                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3888                } else {
3889                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3890                }
3891            } else {
3892                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3893            }
3894            return compareSignatures(s1, s2);
3895        }
3896    }
3897
3898    private void killUid(int appId, int userId, String reason) {
3899        final long identity = Binder.clearCallingIdentity();
3900        try {
3901            IActivityManager am = ActivityManagerNative.getDefault();
3902            if (am != null) {
3903                try {
3904                    am.killUid(appId, userId, reason);
3905                } catch (RemoteException e) {
3906                    /* ignore - same process */
3907                }
3908            }
3909        } finally {
3910            Binder.restoreCallingIdentity(identity);
3911        }
3912    }
3913
3914    /**
3915     * Compares two sets of signatures. Returns:
3916     * <br />
3917     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3918     * <br />
3919     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3920     * <br />
3921     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3922     * <br />
3923     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3924     * <br />
3925     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3926     */
3927    static int compareSignatures(Signature[] s1, Signature[] s2) {
3928        if (s1 == null) {
3929            return s2 == null
3930                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3931                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3932        }
3933
3934        if (s2 == null) {
3935            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3936        }
3937
3938        if (s1.length != s2.length) {
3939            return PackageManager.SIGNATURE_NO_MATCH;
3940        }
3941
3942        // Since both signature sets are of size 1, we can compare without HashSets.
3943        if (s1.length == 1) {
3944            return s1[0].equals(s2[0]) ?
3945                    PackageManager.SIGNATURE_MATCH :
3946                    PackageManager.SIGNATURE_NO_MATCH;
3947        }
3948
3949        ArraySet<Signature> set1 = new ArraySet<Signature>();
3950        for (Signature sig : s1) {
3951            set1.add(sig);
3952        }
3953        ArraySet<Signature> set2 = new ArraySet<Signature>();
3954        for (Signature sig : s2) {
3955            set2.add(sig);
3956        }
3957        // Make sure s2 contains all signatures in s1.
3958        if (set1.equals(set2)) {
3959            return PackageManager.SIGNATURE_MATCH;
3960        }
3961        return PackageManager.SIGNATURE_NO_MATCH;
3962    }
3963
3964    /**
3965     * If the database version for this type of package (internal storage or
3966     * external storage) is less than the version where package signatures
3967     * were updated, return true.
3968     */
3969    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3970        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3971        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3972    }
3973
3974    /**
3975     * Used for backward compatibility to make sure any packages with
3976     * certificate chains get upgraded to the new style. {@code existingSigs}
3977     * will be in the old format (since they were stored on disk from before the
3978     * system upgrade) and {@code scannedSigs} will be in the newer format.
3979     */
3980    private int compareSignaturesCompat(PackageSignatures existingSigs,
3981            PackageParser.Package scannedPkg) {
3982        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3983            return PackageManager.SIGNATURE_NO_MATCH;
3984        }
3985
3986        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3987        for (Signature sig : existingSigs.mSignatures) {
3988            existingSet.add(sig);
3989        }
3990        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3991        for (Signature sig : scannedPkg.mSignatures) {
3992            try {
3993                Signature[] chainSignatures = sig.getChainSignatures();
3994                for (Signature chainSig : chainSignatures) {
3995                    scannedCompatSet.add(chainSig);
3996                }
3997            } catch (CertificateEncodingException e) {
3998                scannedCompatSet.add(sig);
3999            }
4000        }
4001        /*
4002         * Make sure the expanded scanned set contains all signatures in the
4003         * existing one.
4004         */
4005        if (scannedCompatSet.equals(existingSet)) {
4006            // Migrate the old signatures to the new scheme.
4007            existingSigs.assignSignatures(scannedPkg.mSignatures);
4008            // The new KeySets will be re-added later in the scanning process.
4009            synchronized (mPackages) {
4010                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4011            }
4012            return PackageManager.SIGNATURE_MATCH;
4013        }
4014        return PackageManager.SIGNATURE_NO_MATCH;
4015    }
4016
4017    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4018        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4019        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4020    }
4021
4022    private int compareSignaturesRecover(PackageSignatures existingSigs,
4023            PackageParser.Package scannedPkg) {
4024        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4025            return PackageManager.SIGNATURE_NO_MATCH;
4026        }
4027
4028        String msg = null;
4029        try {
4030            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4031                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4032                        + scannedPkg.packageName);
4033                return PackageManager.SIGNATURE_MATCH;
4034            }
4035        } catch (CertificateException e) {
4036            msg = e.getMessage();
4037        }
4038
4039        logCriticalInfo(Log.INFO,
4040                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4041        return PackageManager.SIGNATURE_NO_MATCH;
4042    }
4043
4044    @Override
4045    public String[] getPackagesForUid(int uid) {
4046        uid = UserHandle.getAppId(uid);
4047        // reader
4048        synchronized (mPackages) {
4049            Object obj = mSettings.getUserIdLPr(uid);
4050            if (obj instanceof SharedUserSetting) {
4051                final SharedUserSetting sus = (SharedUserSetting) obj;
4052                final int N = sus.packages.size();
4053                final String[] res = new String[N];
4054                final Iterator<PackageSetting> it = sus.packages.iterator();
4055                int i = 0;
4056                while (it.hasNext()) {
4057                    res[i++] = it.next().name;
4058                }
4059                return res;
4060            } else if (obj instanceof PackageSetting) {
4061                final PackageSetting ps = (PackageSetting) obj;
4062                return new String[] { ps.name };
4063            }
4064        }
4065        return null;
4066    }
4067
4068    @Override
4069    public String getNameForUid(int uid) {
4070        // reader
4071        synchronized (mPackages) {
4072            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4073            if (obj instanceof SharedUserSetting) {
4074                final SharedUserSetting sus = (SharedUserSetting) obj;
4075                return sus.name + ":" + sus.userId;
4076            } else if (obj instanceof PackageSetting) {
4077                final PackageSetting ps = (PackageSetting) obj;
4078                return ps.name;
4079            }
4080        }
4081        return null;
4082    }
4083
4084    @Override
4085    public int getUidForSharedUser(String sharedUserName) {
4086        if(sharedUserName == null) {
4087            return -1;
4088        }
4089        // reader
4090        synchronized (mPackages) {
4091            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4092            if (suid == null) {
4093                return -1;
4094            }
4095            return suid.userId;
4096        }
4097    }
4098
4099    @Override
4100    public int getFlagsForUid(int uid) {
4101        synchronized (mPackages) {
4102            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4103            if (obj instanceof SharedUserSetting) {
4104                final SharedUserSetting sus = (SharedUserSetting) obj;
4105                return sus.pkgFlags;
4106            } else if (obj instanceof PackageSetting) {
4107                final PackageSetting ps = (PackageSetting) obj;
4108                return ps.pkgFlags;
4109            }
4110        }
4111        return 0;
4112    }
4113
4114    @Override
4115    public int getPrivateFlagsForUid(int uid) {
4116        synchronized (mPackages) {
4117            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4118            if (obj instanceof SharedUserSetting) {
4119                final SharedUserSetting sus = (SharedUserSetting) obj;
4120                return sus.pkgPrivateFlags;
4121            } else if (obj instanceof PackageSetting) {
4122                final PackageSetting ps = (PackageSetting) obj;
4123                return ps.pkgPrivateFlags;
4124            }
4125        }
4126        return 0;
4127    }
4128
4129    @Override
4130    public boolean isUidPrivileged(int uid) {
4131        uid = UserHandle.getAppId(uid);
4132        // reader
4133        synchronized (mPackages) {
4134            Object obj = mSettings.getUserIdLPr(uid);
4135            if (obj instanceof SharedUserSetting) {
4136                final SharedUserSetting sus = (SharedUserSetting) obj;
4137                final Iterator<PackageSetting> it = sus.packages.iterator();
4138                while (it.hasNext()) {
4139                    if (it.next().isPrivileged()) {
4140                        return true;
4141                    }
4142                }
4143            } else if (obj instanceof PackageSetting) {
4144                final PackageSetting ps = (PackageSetting) obj;
4145                return ps.isPrivileged();
4146            }
4147        }
4148        return false;
4149    }
4150
4151    @Override
4152    public String[] getAppOpPermissionPackages(String permissionName) {
4153        synchronized (mPackages) {
4154            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4155            if (pkgs == null) {
4156                return null;
4157            }
4158            return pkgs.toArray(new String[pkgs.size()]);
4159        }
4160    }
4161
4162    @Override
4163    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4164            int flags, int userId) {
4165        if (!sUserManager.exists(userId)) return null;
4166        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4167        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4168        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4169    }
4170
4171    @Override
4172    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4173            IntentFilter filter, int match, ComponentName activity) {
4174        final int userId = UserHandle.getCallingUserId();
4175        if (DEBUG_PREFERRED) {
4176            Log.v(TAG, "setLastChosenActivity intent=" + intent
4177                + " resolvedType=" + resolvedType
4178                + " flags=" + flags
4179                + " filter=" + filter
4180                + " match=" + match
4181                + " activity=" + activity);
4182            filter.dump(new PrintStreamPrinter(System.out), "    ");
4183        }
4184        intent.setComponent(null);
4185        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4186        // Find any earlier preferred or last chosen entries and nuke them
4187        findPreferredActivity(intent, resolvedType,
4188                flags, query, 0, false, true, false, userId);
4189        // Add the new activity as the last chosen for this filter
4190        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4191                "Setting last chosen");
4192    }
4193
4194    @Override
4195    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4196        final int userId = UserHandle.getCallingUserId();
4197        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4198        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4199        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4200                false, false, false, userId);
4201    }
4202
4203    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4204            int flags, List<ResolveInfo> query, int userId) {
4205        if (query != null) {
4206            final int N = query.size();
4207            if (N == 1) {
4208                return query.get(0);
4209            } else if (N > 1) {
4210                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4211                // If there is more than one activity with the same priority,
4212                // then let the user decide between them.
4213                ResolveInfo r0 = query.get(0);
4214                ResolveInfo r1 = query.get(1);
4215                if (DEBUG_INTENT_MATCHING || debug) {
4216                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4217                            + r1.activityInfo.name + "=" + r1.priority);
4218                }
4219                // If the first activity has a higher priority, or a different
4220                // default, then it is always desireable to pick it.
4221                if (r0.priority != r1.priority
4222                        || r0.preferredOrder != r1.preferredOrder
4223                        || r0.isDefault != r1.isDefault) {
4224                    return query.get(0);
4225                }
4226                // If we have saved a preference for a preferred activity for
4227                // this Intent, use that.
4228                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4229                        flags, query, r0.priority, true, false, debug, userId);
4230                if (ri != null) {
4231                    return ri;
4232                }
4233                ri = new ResolveInfo(mResolveInfo);
4234                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4235                ri.activityInfo.applicationInfo = new ApplicationInfo(
4236                        ri.activityInfo.applicationInfo);
4237                if (userId != 0) {
4238                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4239                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4240                }
4241                // Make sure that the resolver is displayable in car mode
4242                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4243                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4244                return ri;
4245            }
4246        }
4247        return null;
4248    }
4249
4250    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4251            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4252        final int N = query.size();
4253        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4254                .get(userId);
4255        // Get the list of persistent preferred activities that handle the intent
4256        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4257        List<PersistentPreferredActivity> pprefs = ppir != null
4258                ? ppir.queryIntent(intent, resolvedType,
4259                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4260                : null;
4261        if (pprefs != null && pprefs.size() > 0) {
4262            final int M = pprefs.size();
4263            for (int i=0; i<M; i++) {
4264                final PersistentPreferredActivity ppa = pprefs.get(i);
4265                if (DEBUG_PREFERRED || debug) {
4266                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4267                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4268                            + "\n  component=" + ppa.mComponent);
4269                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4270                }
4271                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4272                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4273                if (DEBUG_PREFERRED || debug) {
4274                    Slog.v(TAG, "Found persistent preferred activity:");
4275                    if (ai != null) {
4276                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4277                    } else {
4278                        Slog.v(TAG, "  null");
4279                    }
4280                }
4281                if (ai == null) {
4282                    // This previously registered persistent preferred activity
4283                    // component is no longer known. Ignore it and do NOT remove it.
4284                    continue;
4285                }
4286                for (int j=0; j<N; j++) {
4287                    final ResolveInfo ri = query.get(j);
4288                    if (!ri.activityInfo.applicationInfo.packageName
4289                            .equals(ai.applicationInfo.packageName)) {
4290                        continue;
4291                    }
4292                    if (!ri.activityInfo.name.equals(ai.name)) {
4293                        continue;
4294                    }
4295                    //  Found a persistent preference that can handle the intent.
4296                    if (DEBUG_PREFERRED || debug) {
4297                        Slog.v(TAG, "Returning persistent preferred activity: " +
4298                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4299                    }
4300                    return ri;
4301                }
4302            }
4303        }
4304        return null;
4305    }
4306
4307    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4308            List<ResolveInfo> query, int priority, boolean always,
4309            boolean removeMatches, boolean debug, int userId) {
4310        if (!sUserManager.exists(userId)) return null;
4311        // writer
4312        synchronized (mPackages) {
4313            if (intent.getSelector() != null) {
4314                intent = intent.getSelector();
4315            }
4316            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4317
4318            // Try to find a matching persistent preferred activity.
4319            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4320                    debug, userId);
4321
4322            // If a persistent preferred activity matched, use it.
4323            if (pri != null) {
4324                return pri;
4325            }
4326
4327            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4328            // Get the list of preferred activities that handle the intent
4329            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4330            List<PreferredActivity> prefs = pir != null
4331                    ? pir.queryIntent(intent, resolvedType,
4332                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4333                    : null;
4334            if (prefs != null && prefs.size() > 0) {
4335                boolean changed = false;
4336                try {
4337                    // First figure out how good the original match set is.
4338                    // We will only allow preferred activities that came
4339                    // from the same match quality.
4340                    int match = 0;
4341
4342                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4343
4344                    final int N = query.size();
4345                    for (int j=0; j<N; j++) {
4346                        final ResolveInfo ri = query.get(j);
4347                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4348                                + ": 0x" + Integer.toHexString(match));
4349                        if (ri.match > match) {
4350                            match = ri.match;
4351                        }
4352                    }
4353
4354                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4355                            + Integer.toHexString(match));
4356
4357                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4358                    final int M = prefs.size();
4359                    for (int i=0; i<M; i++) {
4360                        final PreferredActivity pa = prefs.get(i);
4361                        if (DEBUG_PREFERRED || debug) {
4362                            Slog.v(TAG, "Checking PreferredActivity ds="
4363                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4364                                    + "\n  component=" + pa.mPref.mComponent);
4365                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4366                        }
4367                        if (pa.mPref.mMatch != match) {
4368                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4369                                    + Integer.toHexString(pa.mPref.mMatch));
4370                            continue;
4371                        }
4372                        // If it's not an "always" type preferred activity and that's what we're
4373                        // looking for, skip it.
4374                        if (always && !pa.mPref.mAlways) {
4375                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4376                            continue;
4377                        }
4378                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4379                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4380                        if (DEBUG_PREFERRED || debug) {
4381                            Slog.v(TAG, "Found preferred activity:");
4382                            if (ai != null) {
4383                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4384                            } else {
4385                                Slog.v(TAG, "  null");
4386                            }
4387                        }
4388                        if (ai == null) {
4389                            // This previously registered preferred activity
4390                            // component is no longer known.  Most likely an update
4391                            // to the app was installed and in the new version this
4392                            // component no longer exists.  Clean it up by removing
4393                            // it from the preferred activities list, and skip it.
4394                            Slog.w(TAG, "Removing dangling preferred activity: "
4395                                    + pa.mPref.mComponent);
4396                            pir.removeFilter(pa);
4397                            changed = true;
4398                            continue;
4399                        }
4400                        for (int j=0; j<N; j++) {
4401                            final ResolveInfo ri = query.get(j);
4402                            if (!ri.activityInfo.applicationInfo.packageName
4403                                    .equals(ai.applicationInfo.packageName)) {
4404                                continue;
4405                            }
4406                            if (!ri.activityInfo.name.equals(ai.name)) {
4407                                continue;
4408                            }
4409
4410                            if (removeMatches) {
4411                                pir.removeFilter(pa);
4412                                changed = true;
4413                                if (DEBUG_PREFERRED) {
4414                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4415                                }
4416                                break;
4417                            }
4418
4419                            // Okay we found a previously set preferred or last chosen app.
4420                            // If the result set is different from when this
4421                            // was created, we need to clear it and re-ask the
4422                            // user their preference, if we're looking for an "always" type entry.
4423                            if (always && !pa.mPref.sameSet(query)) {
4424                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4425                                        + intent + " type " + resolvedType);
4426                                if (DEBUG_PREFERRED) {
4427                                    Slog.v(TAG, "Removing preferred activity since set changed "
4428                                            + pa.mPref.mComponent);
4429                                }
4430                                pir.removeFilter(pa);
4431                                // Re-add the filter as a "last chosen" entry (!always)
4432                                PreferredActivity lastChosen = new PreferredActivity(
4433                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4434                                pir.addFilter(lastChosen);
4435                                changed = true;
4436                                return null;
4437                            }
4438
4439                            // Yay! Either the set matched or we're looking for the last chosen
4440                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4441                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4442                            return ri;
4443                        }
4444                    }
4445                } finally {
4446                    if (changed) {
4447                        if (DEBUG_PREFERRED) {
4448                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4449                        }
4450                        scheduleWritePackageRestrictionsLocked(userId);
4451                    }
4452                }
4453            }
4454        }
4455        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4456        return null;
4457    }
4458
4459    /*
4460     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4461     */
4462    @Override
4463    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4464            int targetUserId) {
4465        mContext.enforceCallingOrSelfPermission(
4466                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4467        List<CrossProfileIntentFilter> matches =
4468                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4469        if (matches != null) {
4470            int size = matches.size();
4471            for (int i = 0; i < size; i++) {
4472                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4473            }
4474        }
4475        if (hasWebURI(intent)) {
4476            // cross-profile app linking works only towards the parent.
4477            final UserInfo parent = getProfileParent(sourceUserId);
4478            synchronized(mPackages) {
4479                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4480                        intent, resolvedType, 0, sourceUserId, parent.id);
4481                return xpDomainInfo != null;
4482            }
4483        }
4484        return false;
4485    }
4486
4487    private UserInfo getProfileParent(int userId) {
4488        final long identity = Binder.clearCallingIdentity();
4489        try {
4490            return sUserManager.getProfileParent(userId);
4491        } finally {
4492            Binder.restoreCallingIdentity(identity);
4493        }
4494    }
4495
4496    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4497            String resolvedType, int userId) {
4498        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4499        if (resolver != null) {
4500            return resolver.queryIntent(intent, resolvedType, false, userId);
4501        }
4502        return null;
4503    }
4504
4505    @Override
4506    public List<ResolveInfo> queryIntentActivities(Intent intent,
4507            String resolvedType, int flags, int userId) {
4508        if (!sUserManager.exists(userId)) return Collections.emptyList();
4509        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4510        ComponentName comp = intent.getComponent();
4511        if (comp == null) {
4512            if (intent.getSelector() != null) {
4513                intent = intent.getSelector();
4514                comp = intent.getComponent();
4515            }
4516        }
4517
4518        if (comp != null) {
4519            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4520            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4521            if (ai != null) {
4522                final ResolveInfo ri = new ResolveInfo();
4523                ri.activityInfo = ai;
4524                list.add(ri);
4525            }
4526            return list;
4527        }
4528
4529        // reader
4530        synchronized (mPackages) {
4531            final String pkgName = intent.getPackage();
4532            if (pkgName == null) {
4533                List<CrossProfileIntentFilter> matchingFilters =
4534                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4535                // Check for results that need to skip the current profile.
4536                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4537                        resolvedType, flags, userId);
4538                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4539                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4540                    result.add(xpResolveInfo);
4541                    return filterIfNotPrimaryUser(result, userId);
4542                }
4543
4544                // Check for results in the current profile.
4545                List<ResolveInfo> result = mActivities.queryIntent(
4546                        intent, resolvedType, flags, userId);
4547
4548                // Check for cross profile results.
4549                xpResolveInfo = queryCrossProfileIntents(
4550                        matchingFilters, intent, resolvedType, flags, userId);
4551                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4552                    result.add(xpResolveInfo);
4553                    Collections.sort(result, mResolvePrioritySorter);
4554                }
4555                result = filterIfNotPrimaryUser(result, userId);
4556                if (hasWebURI(intent)) {
4557                    CrossProfileDomainInfo xpDomainInfo = null;
4558                    final UserInfo parent = getProfileParent(userId);
4559                    if (parent != null) {
4560                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4561                                flags, userId, parent.id);
4562                    }
4563                    if (xpDomainInfo != null) {
4564                        if (xpResolveInfo != null) {
4565                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4566                            // in the result.
4567                            result.remove(xpResolveInfo);
4568                        }
4569                        if (result.size() == 0) {
4570                            result.add(xpDomainInfo.resolveInfo);
4571                            return result;
4572                        }
4573                    } else if (result.size() <= 1) {
4574                        return result;
4575                    }
4576                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4577                            xpDomainInfo, userId);
4578                    Collections.sort(result, mResolvePrioritySorter);
4579                }
4580                return result;
4581            }
4582            final PackageParser.Package pkg = mPackages.get(pkgName);
4583            if (pkg != null) {
4584                return filterIfNotPrimaryUser(
4585                        mActivities.queryIntentForPackage(
4586                                intent, resolvedType, flags, pkg.activities, userId),
4587                        userId);
4588            }
4589            return new ArrayList<ResolveInfo>();
4590        }
4591    }
4592
4593    private static class CrossProfileDomainInfo {
4594        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4595        ResolveInfo resolveInfo;
4596        /* Best domain verification status of the activities found in the other profile */
4597        int bestDomainVerificationStatus;
4598    }
4599
4600    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4601            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4602        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4603                sourceUserId)) {
4604            return null;
4605        }
4606        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4607                resolvedType, flags, parentUserId);
4608
4609        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4610            return null;
4611        }
4612        CrossProfileDomainInfo result = null;
4613        int size = resultTargetUser.size();
4614        for (int i = 0; i < size; i++) {
4615            ResolveInfo riTargetUser = resultTargetUser.get(i);
4616            // Intent filter verification is only for filters that specify a host. So don't return
4617            // those that handle all web uris.
4618            if (riTargetUser.handleAllWebDataURI) {
4619                continue;
4620            }
4621            String packageName = riTargetUser.activityInfo.packageName;
4622            PackageSetting ps = mSettings.mPackages.get(packageName);
4623            if (ps == null) {
4624                continue;
4625            }
4626            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4627            int status = (int)(verificationState >> 32);
4628            if (result == null) {
4629                result = new CrossProfileDomainInfo();
4630                result.resolveInfo =
4631                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4632                result.bestDomainVerificationStatus = status;
4633            } else {
4634                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4635                        result.bestDomainVerificationStatus);
4636            }
4637        }
4638        // Don't consider matches with status NEVER across profiles.
4639        if (result != null && result.bestDomainVerificationStatus
4640                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4641            return null;
4642        }
4643        return result;
4644    }
4645
4646    /**
4647     * Verification statuses are ordered from the worse to the best, except for
4648     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4649     */
4650    private int bestDomainVerificationStatus(int status1, int status2) {
4651        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4652            return status2;
4653        }
4654        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4655            return status1;
4656        }
4657        return (int) MathUtils.max(status1, status2);
4658    }
4659
4660    private boolean isUserEnabled(int userId) {
4661        long callingId = Binder.clearCallingIdentity();
4662        try {
4663            UserInfo userInfo = sUserManager.getUserInfo(userId);
4664            return userInfo != null && userInfo.isEnabled();
4665        } finally {
4666            Binder.restoreCallingIdentity(callingId);
4667        }
4668    }
4669
4670    /**
4671     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4672     *
4673     * @return filtered list
4674     */
4675    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4676        if (userId == UserHandle.USER_OWNER) {
4677            return resolveInfos;
4678        }
4679        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4680            ResolveInfo info = resolveInfos.get(i);
4681            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4682                resolveInfos.remove(i);
4683            }
4684        }
4685        return resolveInfos;
4686    }
4687
4688    private static boolean hasWebURI(Intent intent) {
4689        if (intent.getData() == null) {
4690            return false;
4691        }
4692        final String scheme = intent.getScheme();
4693        if (TextUtils.isEmpty(scheme)) {
4694            return false;
4695        }
4696        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4697    }
4698
4699    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4700            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4701            int userId) {
4702        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4703
4704        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4705            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4706                    candidates.size());
4707        }
4708
4709        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4710        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4711        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4712        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4713        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4714        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4715
4716        synchronized (mPackages) {
4717            final int count = candidates.size();
4718            // First, try to use linked apps. Partition the candidates into four lists:
4719            // one for the final results, one for the "do not use ever", one for "undefined status"
4720            // and finally one for "browser app type".
4721            for (int n=0; n<count; n++) {
4722                ResolveInfo info = candidates.get(n);
4723                String packageName = info.activityInfo.packageName;
4724                PackageSetting ps = mSettings.mPackages.get(packageName);
4725                if (ps != null) {
4726                    // Add to the special match all list (Browser use case)
4727                    if (info.handleAllWebDataURI) {
4728                        matchAllList.add(info);
4729                        continue;
4730                    }
4731                    // Try to get the status from User settings first
4732                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4733                    int status = (int)(packedStatus >> 32);
4734                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4735                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4736                        if (DEBUG_DOMAIN_VERIFICATION) {
4737                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4738                                    + " : linkgen=" + linkGeneration);
4739                        }
4740                        // Use link-enabled generation as preferredOrder, i.e.
4741                        // prefer newly-enabled over earlier-enabled.
4742                        info.preferredOrder = linkGeneration;
4743                        alwaysList.add(info);
4744                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4745                        if (DEBUG_DOMAIN_VERIFICATION) {
4746                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4747                        }
4748                        neverList.add(info);
4749                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4750                        if (DEBUG_DOMAIN_VERIFICATION) {
4751                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4752                        }
4753                        alwaysAskList.add(info);
4754                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4755                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4756                        if (DEBUG_DOMAIN_VERIFICATION) {
4757                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4758                        }
4759                        undefinedList.add(info);
4760                    }
4761                }
4762            }
4763
4764            // We'll want to include browser possibilities in a few cases
4765            boolean includeBrowser = false;
4766
4767            // First try to add the "always" resolution(s) for the current user, if any
4768            if (alwaysList.size() > 0) {
4769                result.addAll(alwaysList);
4770            // if there is an "always" for the parent user, add it.
4771            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4772                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4773                result.add(xpDomainInfo.resolveInfo);
4774            } else {
4775                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4776                result.addAll(undefinedList);
4777                if (xpDomainInfo != null && (
4778                        xpDomainInfo.bestDomainVerificationStatus
4779                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4780                        || xpDomainInfo.bestDomainVerificationStatus
4781                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4782                    result.add(xpDomainInfo.resolveInfo);
4783                }
4784                includeBrowser = true;
4785            }
4786
4787            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4788            // If there were 'always' entries their preferred order has been set, so we also
4789            // back that off to make the alternatives equivalent
4790            if (alwaysAskList.size() > 0) {
4791                for (ResolveInfo i : result) {
4792                    i.preferredOrder = 0;
4793                }
4794                result.addAll(alwaysAskList);
4795                includeBrowser = true;
4796            }
4797
4798            if (includeBrowser) {
4799                // Also add browsers (all of them or only the default one)
4800                if (DEBUG_DOMAIN_VERIFICATION) {
4801                    Slog.v(TAG, "   ...including browsers in candidate set");
4802                }
4803                if ((matchFlags & MATCH_ALL) != 0) {
4804                    result.addAll(matchAllList);
4805                } else {
4806                    // Browser/generic handling case.  If there's a default browser, go straight
4807                    // to that (but only if there is no other higher-priority match).
4808                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4809                    int maxMatchPrio = 0;
4810                    ResolveInfo defaultBrowserMatch = null;
4811                    final int numCandidates = matchAllList.size();
4812                    for (int n = 0; n < numCandidates; n++) {
4813                        ResolveInfo info = matchAllList.get(n);
4814                        // track the highest overall match priority...
4815                        if (info.priority > maxMatchPrio) {
4816                            maxMatchPrio = info.priority;
4817                        }
4818                        // ...and the highest-priority default browser match
4819                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4820                            if (defaultBrowserMatch == null
4821                                    || (defaultBrowserMatch.priority < info.priority)) {
4822                                if (debug) {
4823                                    Slog.v(TAG, "Considering default browser match " + info);
4824                                }
4825                                defaultBrowserMatch = info;
4826                            }
4827                        }
4828                    }
4829                    if (defaultBrowserMatch != null
4830                            && defaultBrowserMatch.priority >= maxMatchPrio
4831                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4832                    {
4833                        if (debug) {
4834                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4835                        }
4836                        result.add(defaultBrowserMatch);
4837                    } else {
4838                        result.addAll(matchAllList);
4839                    }
4840                }
4841
4842                // If there is nothing selected, add all candidates and remove the ones that the user
4843                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4844                if (result.size() == 0) {
4845                    result.addAll(candidates);
4846                    result.removeAll(neverList);
4847                }
4848            }
4849        }
4850        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4851            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4852                    result.size());
4853            for (ResolveInfo info : result) {
4854                Slog.v(TAG, "  + " + info.activityInfo);
4855            }
4856        }
4857        return result;
4858    }
4859
4860    // Returns a packed value as a long:
4861    //
4862    // high 'int'-sized word: link status: undefined/ask/never/always.
4863    // low 'int'-sized word: relative priority among 'always' results.
4864    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4865        long result = ps.getDomainVerificationStatusForUser(userId);
4866        // if none available, get the master status
4867        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4868            if (ps.getIntentFilterVerificationInfo() != null) {
4869                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4870            }
4871        }
4872        return result;
4873    }
4874
4875    private ResolveInfo querySkipCurrentProfileIntents(
4876            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4877            int flags, int sourceUserId) {
4878        if (matchingFilters != null) {
4879            int size = matchingFilters.size();
4880            for (int i = 0; i < size; i ++) {
4881                CrossProfileIntentFilter filter = matchingFilters.get(i);
4882                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4883                    // Checking if there are activities in the target user that can handle the
4884                    // intent.
4885                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4886                            flags, sourceUserId);
4887                    if (resolveInfo != null) {
4888                        return resolveInfo;
4889                    }
4890                }
4891            }
4892        }
4893        return null;
4894    }
4895
4896    // Return matching ResolveInfo if any for skip current profile intent filters.
4897    private ResolveInfo queryCrossProfileIntents(
4898            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4899            int flags, int sourceUserId) {
4900        if (matchingFilters != null) {
4901            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4902            // match the same intent. For performance reasons, it is better not to
4903            // run queryIntent twice for the same userId
4904            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4905            int size = matchingFilters.size();
4906            for (int i = 0; i < size; i++) {
4907                CrossProfileIntentFilter filter = matchingFilters.get(i);
4908                int targetUserId = filter.getTargetUserId();
4909                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4910                        && !alreadyTriedUserIds.get(targetUserId)) {
4911                    // Checking if there are activities in the target user that can handle the
4912                    // intent.
4913                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4914                            flags, sourceUserId);
4915                    if (resolveInfo != null) return resolveInfo;
4916                    alreadyTriedUserIds.put(targetUserId, true);
4917                }
4918            }
4919        }
4920        return null;
4921    }
4922
4923    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4924            String resolvedType, int flags, int sourceUserId) {
4925        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4926                resolvedType, flags, filter.getTargetUserId());
4927        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4928            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4929        }
4930        return null;
4931    }
4932
4933    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4934            int sourceUserId, int targetUserId) {
4935        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4936        String className;
4937        if (targetUserId == UserHandle.USER_OWNER) {
4938            className = FORWARD_INTENT_TO_USER_OWNER;
4939        } else {
4940            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4941        }
4942        ComponentName forwardingActivityComponentName = new ComponentName(
4943                mAndroidApplication.packageName, className);
4944        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4945                sourceUserId);
4946        if (targetUserId == UserHandle.USER_OWNER) {
4947            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4948            forwardingResolveInfo.noResourceId = true;
4949        }
4950        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4951        forwardingResolveInfo.priority = 0;
4952        forwardingResolveInfo.preferredOrder = 0;
4953        forwardingResolveInfo.match = 0;
4954        forwardingResolveInfo.isDefault = true;
4955        forwardingResolveInfo.filter = filter;
4956        forwardingResolveInfo.targetUserId = targetUserId;
4957        return forwardingResolveInfo;
4958    }
4959
4960    @Override
4961    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4962            Intent[] specifics, String[] specificTypes, Intent intent,
4963            String resolvedType, int flags, int userId) {
4964        if (!sUserManager.exists(userId)) return Collections.emptyList();
4965        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4966                false, "query intent activity options");
4967        final String resultsAction = intent.getAction();
4968
4969        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4970                | PackageManager.GET_RESOLVED_FILTER, userId);
4971
4972        if (DEBUG_INTENT_MATCHING) {
4973            Log.v(TAG, "Query " + intent + ": " + results);
4974        }
4975
4976        int specificsPos = 0;
4977        int N;
4978
4979        // todo: note that the algorithm used here is O(N^2).  This
4980        // isn't a problem in our current environment, but if we start running
4981        // into situations where we have more than 5 or 10 matches then this
4982        // should probably be changed to something smarter...
4983
4984        // First we go through and resolve each of the specific items
4985        // that were supplied, taking care of removing any corresponding
4986        // duplicate items in the generic resolve list.
4987        if (specifics != null) {
4988            for (int i=0; i<specifics.length; i++) {
4989                final Intent sintent = specifics[i];
4990                if (sintent == null) {
4991                    continue;
4992                }
4993
4994                if (DEBUG_INTENT_MATCHING) {
4995                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4996                }
4997
4998                String action = sintent.getAction();
4999                if (resultsAction != null && resultsAction.equals(action)) {
5000                    // If this action was explicitly requested, then don't
5001                    // remove things that have it.
5002                    action = null;
5003                }
5004
5005                ResolveInfo ri = null;
5006                ActivityInfo ai = null;
5007
5008                ComponentName comp = sintent.getComponent();
5009                if (comp == null) {
5010                    ri = resolveIntent(
5011                        sintent,
5012                        specificTypes != null ? specificTypes[i] : null,
5013                            flags, userId);
5014                    if (ri == null) {
5015                        continue;
5016                    }
5017                    if (ri == mResolveInfo) {
5018                        // ACK!  Must do something better with this.
5019                    }
5020                    ai = ri.activityInfo;
5021                    comp = new ComponentName(ai.applicationInfo.packageName,
5022                            ai.name);
5023                } else {
5024                    ai = getActivityInfo(comp, flags, userId);
5025                    if (ai == null) {
5026                        continue;
5027                    }
5028                }
5029
5030                // Look for any generic query activities that are duplicates
5031                // of this specific one, and remove them from the results.
5032                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5033                N = results.size();
5034                int j;
5035                for (j=specificsPos; j<N; j++) {
5036                    ResolveInfo sri = results.get(j);
5037                    if ((sri.activityInfo.name.equals(comp.getClassName())
5038                            && sri.activityInfo.applicationInfo.packageName.equals(
5039                                    comp.getPackageName()))
5040                        || (action != null && sri.filter.matchAction(action))) {
5041                        results.remove(j);
5042                        if (DEBUG_INTENT_MATCHING) Log.v(
5043                            TAG, "Removing duplicate item from " + j
5044                            + " due to specific " + specificsPos);
5045                        if (ri == null) {
5046                            ri = sri;
5047                        }
5048                        j--;
5049                        N--;
5050                    }
5051                }
5052
5053                // Add this specific item to its proper place.
5054                if (ri == null) {
5055                    ri = new ResolveInfo();
5056                    ri.activityInfo = ai;
5057                }
5058                results.add(specificsPos, ri);
5059                ri.specificIndex = i;
5060                specificsPos++;
5061            }
5062        }
5063
5064        // Now we go through the remaining generic results and remove any
5065        // duplicate actions that are found here.
5066        N = results.size();
5067        for (int i=specificsPos; i<N-1; i++) {
5068            final ResolveInfo rii = results.get(i);
5069            if (rii.filter == null) {
5070                continue;
5071            }
5072
5073            // Iterate over all of the actions of this result's intent
5074            // filter...  typically this should be just one.
5075            final Iterator<String> it = rii.filter.actionsIterator();
5076            if (it == null) {
5077                continue;
5078            }
5079            while (it.hasNext()) {
5080                final String action = it.next();
5081                if (resultsAction != null && resultsAction.equals(action)) {
5082                    // If this action was explicitly requested, then don't
5083                    // remove things that have it.
5084                    continue;
5085                }
5086                for (int j=i+1; j<N; j++) {
5087                    final ResolveInfo rij = results.get(j);
5088                    if (rij.filter != null && rij.filter.hasAction(action)) {
5089                        results.remove(j);
5090                        if (DEBUG_INTENT_MATCHING) Log.v(
5091                            TAG, "Removing duplicate item from " + j
5092                            + " due to action " + action + " at " + i);
5093                        j--;
5094                        N--;
5095                    }
5096                }
5097            }
5098
5099            // If the caller didn't request filter information, drop it now
5100            // so we don't have to marshall/unmarshall it.
5101            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5102                rii.filter = null;
5103            }
5104        }
5105
5106        // Filter out the caller activity if so requested.
5107        if (caller != null) {
5108            N = results.size();
5109            for (int i=0; i<N; i++) {
5110                ActivityInfo ainfo = results.get(i).activityInfo;
5111                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5112                        && caller.getClassName().equals(ainfo.name)) {
5113                    results.remove(i);
5114                    break;
5115                }
5116            }
5117        }
5118
5119        // If the caller didn't request filter information,
5120        // drop them now so we don't have to
5121        // marshall/unmarshall it.
5122        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5123            N = results.size();
5124            for (int i=0; i<N; i++) {
5125                results.get(i).filter = null;
5126            }
5127        }
5128
5129        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5130        return results;
5131    }
5132
5133    @Override
5134    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5135            int userId) {
5136        if (!sUserManager.exists(userId)) return Collections.emptyList();
5137        ComponentName comp = intent.getComponent();
5138        if (comp == null) {
5139            if (intent.getSelector() != null) {
5140                intent = intent.getSelector();
5141                comp = intent.getComponent();
5142            }
5143        }
5144        if (comp != null) {
5145            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5146            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5147            if (ai != null) {
5148                ResolveInfo ri = new ResolveInfo();
5149                ri.activityInfo = ai;
5150                list.add(ri);
5151            }
5152            return list;
5153        }
5154
5155        // reader
5156        synchronized (mPackages) {
5157            String pkgName = intent.getPackage();
5158            if (pkgName == null) {
5159                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5160            }
5161            final PackageParser.Package pkg = mPackages.get(pkgName);
5162            if (pkg != null) {
5163                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5164                        userId);
5165            }
5166            return null;
5167        }
5168    }
5169
5170    @Override
5171    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5172        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5173        if (!sUserManager.exists(userId)) return null;
5174        if (query != null) {
5175            if (query.size() >= 1) {
5176                // If there is more than one service with the same priority,
5177                // just arbitrarily pick the first one.
5178                return query.get(0);
5179            }
5180        }
5181        return null;
5182    }
5183
5184    @Override
5185    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5186            int userId) {
5187        if (!sUserManager.exists(userId)) return Collections.emptyList();
5188        ComponentName comp = intent.getComponent();
5189        if (comp == null) {
5190            if (intent.getSelector() != null) {
5191                intent = intent.getSelector();
5192                comp = intent.getComponent();
5193            }
5194        }
5195        if (comp != null) {
5196            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5197            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5198            if (si != null) {
5199                final ResolveInfo ri = new ResolveInfo();
5200                ri.serviceInfo = si;
5201                list.add(ri);
5202            }
5203            return list;
5204        }
5205
5206        // reader
5207        synchronized (mPackages) {
5208            String pkgName = intent.getPackage();
5209            if (pkgName == null) {
5210                return mServices.queryIntent(intent, resolvedType, flags, userId);
5211            }
5212            final PackageParser.Package pkg = mPackages.get(pkgName);
5213            if (pkg != null) {
5214                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5215                        userId);
5216            }
5217            return null;
5218        }
5219    }
5220
5221    @Override
5222    public List<ResolveInfo> queryIntentContentProviders(
5223            Intent intent, String resolvedType, int flags, int userId) {
5224        if (!sUserManager.exists(userId)) return Collections.emptyList();
5225        ComponentName comp = intent.getComponent();
5226        if (comp == null) {
5227            if (intent.getSelector() != null) {
5228                intent = intent.getSelector();
5229                comp = intent.getComponent();
5230            }
5231        }
5232        if (comp != null) {
5233            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5234            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5235            if (pi != null) {
5236                final ResolveInfo ri = new ResolveInfo();
5237                ri.providerInfo = pi;
5238                list.add(ri);
5239            }
5240            return list;
5241        }
5242
5243        // reader
5244        synchronized (mPackages) {
5245            String pkgName = intent.getPackage();
5246            if (pkgName == null) {
5247                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5248            }
5249            final PackageParser.Package pkg = mPackages.get(pkgName);
5250            if (pkg != null) {
5251                return mProviders.queryIntentForPackage(
5252                        intent, resolvedType, flags, pkg.providers, userId);
5253            }
5254            return null;
5255        }
5256    }
5257
5258    @Override
5259    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5260        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5261
5262        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5263
5264        // writer
5265        synchronized (mPackages) {
5266            ArrayList<PackageInfo> list;
5267            if (listUninstalled) {
5268                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5269                for (PackageSetting ps : mSettings.mPackages.values()) {
5270                    PackageInfo pi;
5271                    if (ps.pkg != null) {
5272                        pi = generatePackageInfo(ps.pkg, flags, userId);
5273                    } else {
5274                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5275                    }
5276                    if (pi != null) {
5277                        list.add(pi);
5278                    }
5279                }
5280            } else {
5281                list = new ArrayList<PackageInfo>(mPackages.size());
5282                for (PackageParser.Package p : mPackages.values()) {
5283                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5284                    if (pi != null) {
5285                        list.add(pi);
5286                    }
5287                }
5288            }
5289
5290            return new ParceledListSlice<PackageInfo>(list);
5291        }
5292    }
5293
5294    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5295            String[] permissions, boolean[] tmp, int flags, int userId) {
5296        int numMatch = 0;
5297        final PermissionsState permissionsState = ps.getPermissionsState();
5298        for (int i=0; i<permissions.length; i++) {
5299            final String permission = permissions[i];
5300            if (permissionsState.hasPermission(permission, userId)) {
5301                tmp[i] = true;
5302                numMatch++;
5303            } else {
5304                tmp[i] = false;
5305            }
5306        }
5307        if (numMatch == 0) {
5308            return;
5309        }
5310        PackageInfo pi;
5311        if (ps.pkg != null) {
5312            pi = generatePackageInfo(ps.pkg, flags, userId);
5313        } else {
5314            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5315        }
5316        // The above might return null in cases of uninstalled apps or install-state
5317        // skew across users/profiles.
5318        if (pi != null) {
5319            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5320                if (numMatch == permissions.length) {
5321                    pi.requestedPermissions = permissions;
5322                } else {
5323                    pi.requestedPermissions = new String[numMatch];
5324                    numMatch = 0;
5325                    for (int i=0; i<permissions.length; i++) {
5326                        if (tmp[i]) {
5327                            pi.requestedPermissions[numMatch] = permissions[i];
5328                            numMatch++;
5329                        }
5330                    }
5331                }
5332            }
5333            list.add(pi);
5334        }
5335    }
5336
5337    @Override
5338    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5339            String[] permissions, int flags, int userId) {
5340        if (!sUserManager.exists(userId)) return null;
5341        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5342
5343        // writer
5344        synchronized (mPackages) {
5345            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5346            boolean[] tmpBools = new boolean[permissions.length];
5347            if (listUninstalled) {
5348                for (PackageSetting ps : mSettings.mPackages.values()) {
5349                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5350                }
5351            } else {
5352                for (PackageParser.Package pkg : mPackages.values()) {
5353                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5354                    if (ps != null) {
5355                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5356                                userId);
5357                    }
5358                }
5359            }
5360
5361            return new ParceledListSlice<PackageInfo>(list);
5362        }
5363    }
5364
5365    @Override
5366    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5367        if (!sUserManager.exists(userId)) return null;
5368        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5369
5370        // writer
5371        synchronized (mPackages) {
5372            ArrayList<ApplicationInfo> list;
5373            if (listUninstalled) {
5374                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5375                for (PackageSetting ps : mSettings.mPackages.values()) {
5376                    ApplicationInfo ai;
5377                    if (ps.pkg != null) {
5378                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5379                                ps.readUserState(userId), userId);
5380                    } else {
5381                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5382                    }
5383                    if (ai != null) {
5384                        list.add(ai);
5385                    }
5386                }
5387            } else {
5388                list = new ArrayList<ApplicationInfo>(mPackages.size());
5389                for (PackageParser.Package p : mPackages.values()) {
5390                    if (p.mExtras != null) {
5391                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5392                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5393                        if (ai != null) {
5394                            list.add(ai);
5395                        }
5396                    }
5397                }
5398            }
5399
5400            return new ParceledListSlice<ApplicationInfo>(list);
5401        }
5402    }
5403
5404    public List<ApplicationInfo> getPersistentApplications(int flags) {
5405        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5406
5407        // reader
5408        synchronized (mPackages) {
5409            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5410            final int userId = UserHandle.getCallingUserId();
5411            while (i.hasNext()) {
5412                final PackageParser.Package p = i.next();
5413                if (p.applicationInfo != null
5414                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5415                        && (!mSafeMode || isSystemApp(p))) {
5416                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5417                    if (ps != null) {
5418                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5419                                ps.readUserState(userId), userId);
5420                        if (ai != null) {
5421                            finalList.add(ai);
5422                        }
5423                    }
5424                }
5425            }
5426        }
5427
5428        return finalList;
5429    }
5430
5431    @Override
5432    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5433        if (!sUserManager.exists(userId)) return null;
5434        // reader
5435        synchronized (mPackages) {
5436            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5437            PackageSetting ps = provider != null
5438                    ? mSettings.mPackages.get(provider.owner.packageName)
5439                    : null;
5440            return ps != null
5441                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5442                    && (!mSafeMode || (provider.info.applicationInfo.flags
5443                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5444                    ? PackageParser.generateProviderInfo(provider, flags,
5445                            ps.readUserState(userId), userId)
5446                    : null;
5447        }
5448    }
5449
5450    /**
5451     * @deprecated
5452     */
5453    @Deprecated
5454    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5455        // reader
5456        synchronized (mPackages) {
5457            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5458                    .entrySet().iterator();
5459            final int userId = UserHandle.getCallingUserId();
5460            while (i.hasNext()) {
5461                Map.Entry<String, PackageParser.Provider> entry = i.next();
5462                PackageParser.Provider p = entry.getValue();
5463                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5464
5465                if (ps != null && p.syncable
5466                        && (!mSafeMode || (p.info.applicationInfo.flags
5467                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5468                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5469                            ps.readUserState(userId), userId);
5470                    if (info != null) {
5471                        outNames.add(entry.getKey());
5472                        outInfo.add(info);
5473                    }
5474                }
5475            }
5476        }
5477    }
5478
5479    @Override
5480    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5481            int uid, int flags) {
5482        ArrayList<ProviderInfo> finalList = null;
5483        // reader
5484        synchronized (mPackages) {
5485            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5486            final int userId = processName != null ?
5487                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5488            while (i.hasNext()) {
5489                final PackageParser.Provider p = i.next();
5490                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5491                if (ps != null && p.info.authority != null
5492                        && (processName == null
5493                                || (p.info.processName.equals(processName)
5494                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5495                        && mSettings.isEnabledLPr(p.info, flags, userId)
5496                        && (!mSafeMode
5497                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5498                    if (finalList == null) {
5499                        finalList = new ArrayList<ProviderInfo>(3);
5500                    }
5501                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5502                            ps.readUserState(userId), userId);
5503                    if (info != null) {
5504                        finalList.add(info);
5505                    }
5506                }
5507            }
5508        }
5509
5510        if (finalList != null) {
5511            Collections.sort(finalList, mProviderInitOrderSorter);
5512            return new ParceledListSlice<ProviderInfo>(finalList);
5513        }
5514
5515        return null;
5516    }
5517
5518    @Override
5519    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5520            int flags) {
5521        // reader
5522        synchronized (mPackages) {
5523            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5524            return PackageParser.generateInstrumentationInfo(i, flags);
5525        }
5526    }
5527
5528    @Override
5529    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5530            int flags) {
5531        ArrayList<InstrumentationInfo> finalList =
5532            new ArrayList<InstrumentationInfo>();
5533
5534        // reader
5535        synchronized (mPackages) {
5536            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5537            while (i.hasNext()) {
5538                final PackageParser.Instrumentation p = i.next();
5539                if (targetPackage == null
5540                        || targetPackage.equals(p.info.targetPackage)) {
5541                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5542                            flags);
5543                    if (ii != null) {
5544                        finalList.add(ii);
5545                    }
5546                }
5547            }
5548        }
5549
5550        return finalList;
5551    }
5552
5553    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5554        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5555        if (overlays == null) {
5556            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5557            return;
5558        }
5559        for (PackageParser.Package opkg : overlays.values()) {
5560            // Not much to do if idmap fails: we already logged the error
5561            // and we certainly don't want to abort installation of pkg simply
5562            // because an overlay didn't fit properly. For these reasons,
5563            // ignore the return value of createIdmapForPackagePairLI.
5564            createIdmapForPackagePairLI(pkg, opkg);
5565        }
5566    }
5567
5568    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5569            PackageParser.Package opkg) {
5570        if (!opkg.mTrustedOverlay) {
5571            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5572                    opkg.baseCodePath + ": overlay not trusted");
5573            return false;
5574        }
5575        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5576        if (overlaySet == null) {
5577            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5578                    opkg.baseCodePath + " but target package has no known overlays");
5579            return false;
5580        }
5581        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5582        // TODO: generate idmap for split APKs
5583        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5584            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5585                    + opkg.baseCodePath);
5586            return false;
5587        }
5588        PackageParser.Package[] overlayArray =
5589            overlaySet.values().toArray(new PackageParser.Package[0]);
5590        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5591            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5592                return p1.mOverlayPriority - p2.mOverlayPriority;
5593            }
5594        };
5595        Arrays.sort(overlayArray, cmp);
5596
5597        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5598        int i = 0;
5599        for (PackageParser.Package p : overlayArray) {
5600            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5601        }
5602        return true;
5603    }
5604
5605    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5606        final File[] files = dir.listFiles();
5607        if (ArrayUtils.isEmpty(files)) {
5608            Log.d(TAG, "No files in app dir " + dir);
5609            return;
5610        }
5611
5612        if (DEBUG_PACKAGE_SCANNING) {
5613            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5614                    + " flags=0x" + Integer.toHexString(parseFlags));
5615        }
5616
5617        for (File file : files) {
5618            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5619                    && !PackageInstallerService.isStageName(file.getName());
5620            if (!isPackage) {
5621                // Ignore entries which are not packages
5622                continue;
5623            }
5624            try {
5625                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5626                        scanFlags, currentTime, null);
5627            } catch (PackageManagerException e) {
5628                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5629
5630                // Delete invalid userdata apps
5631                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5632                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5633                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5634                    if (file.isDirectory()) {
5635                        mInstaller.rmPackageDir(file.getAbsolutePath());
5636                    } else {
5637                        file.delete();
5638                    }
5639                }
5640            }
5641        }
5642    }
5643
5644    private static File getSettingsProblemFile() {
5645        File dataDir = Environment.getDataDirectory();
5646        File systemDir = new File(dataDir, "system");
5647        File fname = new File(systemDir, "uiderrors.txt");
5648        return fname;
5649    }
5650
5651    static void reportSettingsProblem(int priority, String msg) {
5652        logCriticalInfo(priority, msg);
5653    }
5654
5655    static void logCriticalInfo(int priority, String msg) {
5656        Slog.println(priority, TAG, msg);
5657        EventLogTags.writePmCriticalInfo(msg);
5658        try {
5659            File fname = getSettingsProblemFile();
5660            FileOutputStream out = new FileOutputStream(fname, true);
5661            PrintWriter pw = new FastPrintWriter(out);
5662            SimpleDateFormat formatter = new SimpleDateFormat();
5663            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5664            pw.println(dateString + ": " + msg);
5665            pw.close();
5666            FileUtils.setPermissions(
5667                    fname.toString(),
5668                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5669                    -1, -1);
5670        } catch (java.io.IOException e) {
5671        }
5672    }
5673
5674    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5675            PackageParser.Package pkg, File srcFile, int parseFlags)
5676            throws PackageManagerException {
5677        if (ps != null
5678                && ps.codePath.equals(srcFile)
5679                && ps.timeStamp == srcFile.lastModified()
5680                && !isCompatSignatureUpdateNeeded(pkg)
5681                && !isRecoverSignatureUpdateNeeded(pkg)) {
5682            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5683            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5684            ArraySet<PublicKey> signingKs;
5685            synchronized (mPackages) {
5686                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5687            }
5688            if (ps.signatures.mSignatures != null
5689                    && ps.signatures.mSignatures.length != 0
5690                    && signingKs != null) {
5691                // Optimization: reuse the existing cached certificates
5692                // if the package appears to be unchanged.
5693                pkg.mSignatures = ps.signatures.mSignatures;
5694                pkg.mSigningKeys = signingKs;
5695                return;
5696            }
5697
5698            Slog.w(TAG, "PackageSetting for " + ps.name
5699                    + " is missing signatures.  Collecting certs again to recover them.");
5700        } else {
5701            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5702        }
5703
5704        try {
5705            pp.collectCertificates(pkg, parseFlags);
5706            pp.collectManifestDigest(pkg);
5707        } catch (PackageParserException e) {
5708            throw PackageManagerException.from(e);
5709        }
5710    }
5711
5712    /*
5713     *  Scan a package and return the newly parsed package.
5714     *  Returns null in case of errors and the error code is stored in mLastScanError
5715     */
5716    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5717            long currentTime, UserHandle user) throws PackageManagerException {
5718        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5719        parseFlags |= mDefParseFlags;
5720        PackageParser pp = new PackageParser();
5721        pp.setSeparateProcesses(mSeparateProcesses);
5722        pp.setOnlyCoreApps(mOnlyCore);
5723        pp.setDisplayMetrics(mMetrics);
5724
5725        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5726            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5727        }
5728
5729        final PackageParser.Package pkg;
5730        try {
5731            pkg = pp.parsePackage(scanFile, parseFlags);
5732        } catch (PackageParserException e) {
5733            throw PackageManagerException.from(e);
5734        }
5735
5736        PackageSetting ps = null;
5737        PackageSetting updatedPkg;
5738        // reader
5739        synchronized (mPackages) {
5740            // Look to see if we already know about this package.
5741            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5742            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5743                // This package has been renamed to its original name.  Let's
5744                // use that.
5745                ps = mSettings.peekPackageLPr(oldName);
5746            }
5747            // If there was no original package, see one for the real package name.
5748            if (ps == null) {
5749                ps = mSettings.peekPackageLPr(pkg.packageName);
5750            }
5751            // Check to see if this package could be hiding/updating a system
5752            // package.  Must look for it either under the original or real
5753            // package name depending on our state.
5754            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5755            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5756        }
5757        boolean updatedPkgBetter = false;
5758        // First check if this is a system package that may involve an update
5759        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5760            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5761            // it needs to drop FLAG_PRIVILEGED.
5762            if (locationIsPrivileged(scanFile)) {
5763                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5764            } else {
5765                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5766            }
5767
5768            if (ps != null && !ps.codePath.equals(scanFile)) {
5769                // The path has changed from what was last scanned...  check the
5770                // version of the new path against what we have stored to determine
5771                // what to do.
5772                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5773                if (pkg.mVersionCode <= ps.versionCode) {
5774                    // The system package has been updated and the code path does not match
5775                    // Ignore entry. Skip it.
5776                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5777                            + " ignored: updated version " + ps.versionCode
5778                            + " better than this " + pkg.mVersionCode);
5779                    if (!updatedPkg.codePath.equals(scanFile)) {
5780                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5781                                + ps.name + " changing from " + updatedPkg.codePathString
5782                                + " to " + scanFile);
5783                        updatedPkg.codePath = scanFile;
5784                        updatedPkg.codePathString = scanFile.toString();
5785                        updatedPkg.resourcePath = scanFile;
5786                        updatedPkg.resourcePathString = scanFile.toString();
5787                    }
5788                    updatedPkg.pkg = pkg;
5789                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5790                            "Package " + ps.name + " at " + scanFile
5791                                    + " ignored: updated version " + ps.versionCode
5792                                    + " better than this " + pkg.mVersionCode);
5793                } else {
5794                    // The current app on the system partition is better than
5795                    // what we have updated to on the data partition; switch
5796                    // back to the system partition version.
5797                    // At this point, its safely assumed that package installation for
5798                    // apps in system partition will go through. If not there won't be a working
5799                    // version of the app
5800                    // writer
5801                    synchronized (mPackages) {
5802                        // Just remove the loaded entries from package lists.
5803                        mPackages.remove(ps.name);
5804                    }
5805
5806                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5807                            + " reverting from " + ps.codePathString
5808                            + ": new version " + pkg.mVersionCode
5809                            + " better than installed " + ps.versionCode);
5810
5811                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5812                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5813                    synchronized (mInstallLock) {
5814                        args.cleanUpResourcesLI();
5815                    }
5816                    synchronized (mPackages) {
5817                        mSettings.enableSystemPackageLPw(ps.name);
5818                    }
5819                    updatedPkgBetter = true;
5820                }
5821            }
5822        }
5823
5824        if (updatedPkg != null) {
5825            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5826            // initially
5827            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5828
5829            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5830            // flag set initially
5831            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5832                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5833            }
5834        }
5835
5836        // Verify certificates against what was last scanned
5837        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5838
5839        /*
5840         * A new system app appeared, but we already had a non-system one of the
5841         * same name installed earlier.
5842         */
5843        boolean shouldHideSystemApp = false;
5844        if (updatedPkg == null && ps != null
5845                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5846            /*
5847             * Check to make sure the signatures match first. If they don't,
5848             * wipe the installed application and its data.
5849             */
5850            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5851                    != PackageManager.SIGNATURE_MATCH) {
5852                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5853                        + " signatures don't match existing userdata copy; removing");
5854                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5855                ps = null;
5856            } else {
5857                /*
5858                 * If the newly-added system app is an older version than the
5859                 * already installed version, hide it. It will be scanned later
5860                 * and re-added like an update.
5861                 */
5862                if (pkg.mVersionCode <= ps.versionCode) {
5863                    shouldHideSystemApp = true;
5864                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5865                            + " but new version " + pkg.mVersionCode + " better than installed "
5866                            + ps.versionCode + "; hiding system");
5867                } else {
5868                    /*
5869                     * The newly found system app is a newer version that the
5870                     * one previously installed. Simply remove the
5871                     * already-installed application and replace it with our own
5872                     * while keeping the application data.
5873                     */
5874                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5875                            + " reverting from " + ps.codePathString + ": new version "
5876                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5877                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5878                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5879                    synchronized (mInstallLock) {
5880                        args.cleanUpResourcesLI();
5881                    }
5882                }
5883            }
5884        }
5885
5886        // The apk is forward locked (not public) if its code and resources
5887        // are kept in different files. (except for app in either system or
5888        // vendor path).
5889        // TODO grab this value from PackageSettings
5890        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5891            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5892                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5893            }
5894        }
5895
5896        // TODO: extend to support forward-locked splits
5897        String resourcePath = null;
5898        String baseResourcePath = null;
5899        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5900            if (ps != null && ps.resourcePathString != null) {
5901                resourcePath = ps.resourcePathString;
5902                baseResourcePath = ps.resourcePathString;
5903            } else {
5904                // Should not happen at all. Just log an error.
5905                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5906            }
5907        } else {
5908            resourcePath = pkg.codePath;
5909            baseResourcePath = pkg.baseCodePath;
5910        }
5911
5912        // Set application objects path explicitly.
5913        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5914        pkg.applicationInfo.setCodePath(pkg.codePath);
5915        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5916        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5917        pkg.applicationInfo.setResourcePath(resourcePath);
5918        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5919        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5920
5921        // Note that we invoke the following method only if we are about to unpack an application
5922        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5923                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5924
5925        /*
5926         * If the system app should be overridden by a previously installed
5927         * data, hide the system app now and let the /data/app scan pick it up
5928         * again.
5929         */
5930        if (shouldHideSystemApp) {
5931            synchronized (mPackages) {
5932                mSettings.disableSystemPackageLPw(pkg.packageName);
5933            }
5934        }
5935
5936        return scannedPkg;
5937    }
5938
5939    private static String fixProcessName(String defProcessName,
5940            String processName, int uid) {
5941        if (processName == null) {
5942            return defProcessName;
5943        }
5944        return processName;
5945    }
5946
5947    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5948            throws PackageManagerException {
5949        if (pkgSetting.signatures.mSignatures != null) {
5950            // Already existing package. Make sure signatures match
5951            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5952                    == PackageManager.SIGNATURE_MATCH;
5953            if (!match) {
5954                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5955                        == PackageManager.SIGNATURE_MATCH;
5956            }
5957            if (!match) {
5958                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5959                        == PackageManager.SIGNATURE_MATCH;
5960            }
5961            if (!match) {
5962                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5963                        + pkg.packageName + " signatures do not match the "
5964                        + "previously installed version; ignoring!");
5965            }
5966        }
5967
5968        // Check for shared user signatures
5969        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5970            // Already existing package. Make sure signatures match
5971            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5972                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5973            if (!match) {
5974                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5975                        == PackageManager.SIGNATURE_MATCH;
5976            }
5977            if (!match) {
5978                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5979                        == PackageManager.SIGNATURE_MATCH;
5980            }
5981            if (!match) {
5982                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5983                        "Package " + pkg.packageName
5984                        + " has no signatures that match those in shared user "
5985                        + pkgSetting.sharedUser.name + "; ignoring!");
5986            }
5987        }
5988    }
5989
5990    /**
5991     * Enforces that only the system UID or root's UID can call a method exposed
5992     * via Binder.
5993     *
5994     * @param message used as message if SecurityException is thrown
5995     * @throws SecurityException if the caller is not system or root
5996     */
5997    private static final void enforceSystemOrRoot(String message) {
5998        final int uid = Binder.getCallingUid();
5999        if (uid != Process.SYSTEM_UID && uid != 0) {
6000            throw new SecurityException(message);
6001        }
6002    }
6003
6004    @Override
6005    public void performBootDexOpt() {
6006        enforceSystemOrRoot("Only the system can request dexopt be performed");
6007
6008        // Before everything else, see whether we need to fstrim.
6009        try {
6010            IMountService ms = PackageHelper.getMountService();
6011            if (ms != null) {
6012                final boolean isUpgrade = isUpgrade();
6013                boolean doTrim = isUpgrade;
6014                if (doTrim) {
6015                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6016                } else {
6017                    final long interval = android.provider.Settings.Global.getLong(
6018                            mContext.getContentResolver(),
6019                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6020                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6021                    if (interval > 0) {
6022                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6023                        if (timeSinceLast > interval) {
6024                            doTrim = true;
6025                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6026                                    + "; running immediately");
6027                        }
6028                    }
6029                }
6030                if (doTrim) {
6031                    if (!isFirstBoot()) {
6032                        try {
6033                            ActivityManagerNative.getDefault().showBootMessage(
6034                                    mContext.getResources().getString(
6035                                            R.string.android_upgrading_fstrim), true);
6036                        } catch (RemoteException e) {
6037                        }
6038                    }
6039                    ms.runMaintenance();
6040                }
6041            } else {
6042                Slog.e(TAG, "Mount service unavailable!");
6043            }
6044        } catch (RemoteException e) {
6045            // Can't happen; MountService is local
6046        }
6047
6048        final ArraySet<PackageParser.Package> pkgs;
6049        synchronized (mPackages) {
6050            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6051        }
6052
6053        if (pkgs != null) {
6054            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6055            // in case the device runs out of space.
6056            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6057            // Give priority to core apps.
6058            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6059                PackageParser.Package pkg = it.next();
6060                if (pkg.coreApp) {
6061                    if (DEBUG_DEXOPT) {
6062                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6063                    }
6064                    sortedPkgs.add(pkg);
6065                    it.remove();
6066                }
6067            }
6068            // Give priority to system apps that listen for pre boot complete.
6069            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6070            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6071            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6072                PackageParser.Package pkg = it.next();
6073                if (pkgNames.contains(pkg.packageName)) {
6074                    if (DEBUG_DEXOPT) {
6075                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6076                    }
6077                    sortedPkgs.add(pkg);
6078                    it.remove();
6079                }
6080            }
6081            // Give priority to system apps.
6082            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6083                PackageParser.Package pkg = it.next();
6084                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6085                    if (DEBUG_DEXOPT) {
6086                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6087                    }
6088                    sortedPkgs.add(pkg);
6089                    it.remove();
6090                }
6091            }
6092            // Give priority to updated system apps.
6093            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6094                PackageParser.Package pkg = it.next();
6095                if (pkg.isUpdatedSystemApp()) {
6096                    if (DEBUG_DEXOPT) {
6097                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6098                    }
6099                    sortedPkgs.add(pkg);
6100                    it.remove();
6101                }
6102            }
6103            // Give priority to apps that listen for boot complete.
6104            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6105            pkgNames = getPackageNamesForIntent(intent);
6106            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6107                PackageParser.Package pkg = it.next();
6108                if (pkgNames.contains(pkg.packageName)) {
6109                    if (DEBUG_DEXOPT) {
6110                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6111                    }
6112                    sortedPkgs.add(pkg);
6113                    it.remove();
6114                }
6115            }
6116            // Filter out packages that aren't recently used.
6117            filterRecentlyUsedApps(pkgs);
6118            // Add all remaining apps.
6119            for (PackageParser.Package pkg : pkgs) {
6120                if (DEBUG_DEXOPT) {
6121                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6122                }
6123                sortedPkgs.add(pkg);
6124            }
6125
6126            // If we want to be lazy, filter everything that wasn't recently used.
6127            if (mLazyDexOpt) {
6128                filterRecentlyUsedApps(sortedPkgs);
6129            }
6130
6131            int i = 0;
6132            int total = sortedPkgs.size();
6133            File dataDir = Environment.getDataDirectory();
6134            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6135            if (lowThreshold == 0) {
6136                throw new IllegalStateException("Invalid low memory threshold");
6137            }
6138            for (PackageParser.Package pkg : sortedPkgs) {
6139                long usableSpace = dataDir.getUsableSpace();
6140                if (usableSpace < lowThreshold) {
6141                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6142                    break;
6143                }
6144                performBootDexOpt(pkg, ++i, total);
6145            }
6146        }
6147    }
6148
6149    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6150        // Filter out packages that aren't recently used.
6151        //
6152        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6153        // should do a full dexopt.
6154        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6155            int total = pkgs.size();
6156            int skipped = 0;
6157            long now = System.currentTimeMillis();
6158            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6159                PackageParser.Package pkg = i.next();
6160                long then = pkg.mLastPackageUsageTimeInMills;
6161                if (then + mDexOptLRUThresholdInMills < now) {
6162                    if (DEBUG_DEXOPT) {
6163                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6164                              ((then == 0) ? "never" : new Date(then)));
6165                    }
6166                    i.remove();
6167                    skipped++;
6168                }
6169            }
6170            if (DEBUG_DEXOPT) {
6171                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6172            }
6173        }
6174    }
6175
6176    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6177        List<ResolveInfo> ris = null;
6178        try {
6179            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6180                    intent, null, 0, UserHandle.USER_OWNER);
6181        } catch (RemoteException e) {
6182        }
6183        ArraySet<String> pkgNames = new ArraySet<String>();
6184        if (ris != null) {
6185            for (ResolveInfo ri : ris) {
6186                pkgNames.add(ri.activityInfo.packageName);
6187            }
6188        }
6189        return pkgNames;
6190    }
6191
6192    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6193        if (DEBUG_DEXOPT) {
6194            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6195        }
6196        if (!isFirstBoot()) {
6197            try {
6198                ActivityManagerNative.getDefault().showBootMessage(
6199                        mContext.getResources().getString(R.string.android_upgrading_apk,
6200                                curr, total), true);
6201            } catch (RemoteException e) {
6202            }
6203        }
6204        PackageParser.Package p = pkg;
6205        synchronized (mInstallLock) {
6206            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6207                    false /* force dex */, false /* defer */, true /* include dependencies */);
6208        }
6209    }
6210
6211    @Override
6212    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6213        return performDexOpt(packageName, instructionSet, false);
6214    }
6215
6216    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6217        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6218        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6219        if (!dexopt && !updateUsage) {
6220            // We aren't going to dexopt or update usage, so bail early.
6221            return false;
6222        }
6223        PackageParser.Package p;
6224        final String targetInstructionSet;
6225        synchronized (mPackages) {
6226            p = mPackages.get(packageName);
6227            if (p == null) {
6228                return false;
6229            }
6230            if (updateUsage) {
6231                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6232            }
6233            mPackageUsage.write(false);
6234            if (!dexopt) {
6235                // We aren't going to dexopt, so bail early.
6236                return false;
6237            }
6238
6239            targetInstructionSet = instructionSet != null ? instructionSet :
6240                    getPrimaryInstructionSet(p.applicationInfo);
6241            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6242                return false;
6243            }
6244        }
6245        long callingId = Binder.clearCallingIdentity();
6246        try {
6247            synchronized (mInstallLock) {
6248                final String[] instructionSets = new String[] { targetInstructionSet };
6249                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6250                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6251                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6252            }
6253        } finally {
6254            Binder.restoreCallingIdentity(callingId);
6255        }
6256    }
6257
6258    public ArraySet<String> getPackagesThatNeedDexOpt() {
6259        ArraySet<String> pkgs = null;
6260        synchronized (mPackages) {
6261            for (PackageParser.Package p : mPackages.values()) {
6262                if (DEBUG_DEXOPT) {
6263                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6264                }
6265                if (!p.mDexOptPerformed.isEmpty()) {
6266                    continue;
6267                }
6268                if (pkgs == null) {
6269                    pkgs = new ArraySet<String>();
6270                }
6271                pkgs.add(p.packageName);
6272            }
6273        }
6274        return pkgs;
6275    }
6276
6277    public void shutdown() {
6278        mPackageUsage.write(true);
6279    }
6280
6281    @Override
6282    public void forceDexOpt(String packageName) {
6283        enforceSystemOrRoot("forceDexOpt");
6284
6285        PackageParser.Package pkg;
6286        synchronized (mPackages) {
6287            pkg = mPackages.get(packageName);
6288            if (pkg == null) {
6289                throw new IllegalArgumentException("Missing package: " + packageName);
6290            }
6291        }
6292
6293        synchronized (mInstallLock) {
6294            final String[] instructionSets = new String[] {
6295                    getPrimaryInstructionSet(pkg.applicationInfo) };
6296            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6297                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6298            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6299                throw new IllegalStateException("Failed to dexopt: " + res);
6300            }
6301        }
6302    }
6303
6304    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6305        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6306            Slog.w(TAG, "Unable to update from " + oldPkg.name
6307                    + " to " + newPkg.packageName
6308                    + ": old package not in system partition");
6309            return false;
6310        } else if (mPackages.get(oldPkg.name) != null) {
6311            Slog.w(TAG, "Unable to update from " + oldPkg.name
6312                    + " to " + newPkg.packageName
6313                    + ": old package still exists");
6314            return false;
6315        }
6316        return true;
6317    }
6318
6319    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6320        int[] users = sUserManager.getUserIds();
6321        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6322        if (res < 0) {
6323            return res;
6324        }
6325        for (int user : users) {
6326            if (user != 0) {
6327                res = mInstaller.createUserData(volumeUuid, packageName,
6328                        UserHandle.getUid(user, uid), user, seinfo);
6329                if (res < 0) {
6330                    return res;
6331                }
6332            }
6333        }
6334        return res;
6335    }
6336
6337    private int removeDataDirsLI(String volumeUuid, String packageName) {
6338        int[] users = sUserManager.getUserIds();
6339        int res = 0;
6340        for (int user : users) {
6341            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6342            if (resInner < 0) {
6343                res = resInner;
6344            }
6345        }
6346
6347        return res;
6348    }
6349
6350    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6351        int[] users = sUserManager.getUserIds();
6352        int res = 0;
6353        for (int user : users) {
6354            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6355            if (resInner < 0) {
6356                res = resInner;
6357            }
6358        }
6359        return res;
6360    }
6361
6362    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6363            PackageParser.Package changingLib) {
6364        if (file.path != null) {
6365            usesLibraryFiles.add(file.path);
6366            return;
6367        }
6368        PackageParser.Package p = mPackages.get(file.apk);
6369        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6370            // If we are doing this while in the middle of updating a library apk,
6371            // then we need to make sure to use that new apk for determining the
6372            // dependencies here.  (We haven't yet finished committing the new apk
6373            // to the package manager state.)
6374            if (p == null || p.packageName.equals(changingLib.packageName)) {
6375                p = changingLib;
6376            }
6377        }
6378        if (p != null) {
6379            usesLibraryFiles.addAll(p.getAllCodePaths());
6380        }
6381    }
6382
6383    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6384            PackageParser.Package changingLib) throws PackageManagerException {
6385        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6386            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6387            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6388            for (int i=0; i<N; i++) {
6389                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6390                if (file == null) {
6391                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6392                            "Package " + pkg.packageName + " requires unavailable shared library "
6393                            + pkg.usesLibraries.get(i) + "; failing!");
6394                }
6395                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6396            }
6397            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6398            for (int i=0; i<N; i++) {
6399                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6400                if (file == null) {
6401                    Slog.w(TAG, "Package " + pkg.packageName
6402                            + " desires unavailable shared library "
6403                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6404                } else {
6405                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6406                }
6407            }
6408            N = usesLibraryFiles.size();
6409            if (N > 0) {
6410                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6411            } else {
6412                pkg.usesLibraryFiles = null;
6413            }
6414        }
6415    }
6416
6417    private static boolean hasString(List<String> list, List<String> which) {
6418        if (list == null) {
6419            return false;
6420        }
6421        for (int i=list.size()-1; i>=0; i--) {
6422            for (int j=which.size()-1; j>=0; j--) {
6423                if (which.get(j).equals(list.get(i))) {
6424                    return true;
6425                }
6426            }
6427        }
6428        return false;
6429    }
6430
6431    private void updateAllSharedLibrariesLPw() {
6432        for (PackageParser.Package pkg : mPackages.values()) {
6433            try {
6434                updateSharedLibrariesLPw(pkg, null);
6435            } catch (PackageManagerException e) {
6436                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6437            }
6438        }
6439    }
6440
6441    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6442            PackageParser.Package changingPkg) {
6443        ArrayList<PackageParser.Package> res = null;
6444        for (PackageParser.Package pkg : mPackages.values()) {
6445            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6446                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6447                if (res == null) {
6448                    res = new ArrayList<PackageParser.Package>();
6449                }
6450                res.add(pkg);
6451                try {
6452                    updateSharedLibrariesLPw(pkg, changingPkg);
6453                } catch (PackageManagerException e) {
6454                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6455                }
6456            }
6457        }
6458        return res;
6459    }
6460
6461    /**
6462     * Derive the value of the {@code cpuAbiOverride} based on the provided
6463     * value and an optional stored value from the package settings.
6464     */
6465    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6466        String cpuAbiOverride = null;
6467
6468        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6469            cpuAbiOverride = null;
6470        } else if (abiOverride != null) {
6471            cpuAbiOverride = abiOverride;
6472        } else if (settings != null) {
6473            cpuAbiOverride = settings.cpuAbiOverrideString;
6474        }
6475
6476        return cpuAbiOverride;
6477    }
6478
6479    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6480            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6481        boolean success = false;
6482        try {
6483            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6484                    currentTime, user);
6485            success = true;
6486            return res;
6487        } finally {
6488            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6489                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6490            }
6491        }
6492    }
6493
6494    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6495            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6496        final File scanFile = new File(pkg.codePath);
6497        if (pkg.applicationInfo.getCodePath() == null ||
6498                pkg.applicationInfo.getResourcePath() == null) {
6499            // Bail out. The resource and code paths haven't been set.
6500            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6501                    "Code and resource paths haven't been set correctly");
6502        }
6503
6504        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6505            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6506        } else {
6507            // Only allow system apps to be flagged as core apps.
6508            pkg.coreApp = false;
6509        }
6510
6511        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6512            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6513        }
6514
6515        if (mCustomResolverComponentName != null &&
6516                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6517            setUpCustomResolverActivity(pkg);
6518        }
6519
6520        if (pkg.packageName.equals("android")) {
6521            synchronized (mPackages) {
6522                if (mAndroidApplication != null) {
6523                    Slog.w(TAG, "*************************************************");
6524                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6525                    Slog.w(TAG, " file=" + scanFile);
6526                    Slog.w(TAG, "*************************************************");
6527                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6528                            "Core android package being redefined.  Skipping.");
6529                }
6530
6531                // Set up information for our fall-back user intent resolution activity.
6532                mPlatformPackage = pkg;
6533                pkg.mVersionCode = mSdkVersion;
6534                mAndroidApplication = pkg.applicationInfo;
6535
6536                if (!mResolverReplaced) {
6537                    mResolveActivity.applicationInfo = mAndroidApplication;
6538                    mResolveActivity.name = ResolverActivity.class.getName();
6539                    mResolveActivity.packageName = mAndroidApplication.packageName;
6540                    mResolveActivity.processName = "system:ui";
6541                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6542                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6543                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6544                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6545                    mResolveActivity.exported = true;
6546                    mResolveActivity.enabled = true;
6547                    mResolveInfo.activityInfo = mResolveActivity;
6548                    mResolveInfo.priority = 0;
6549                    mResolveInfo.preferredOrder = 0;
6550                    mResolveInfo.match = 0;
6551                    mResolveComponentName = new ComponentName(
6552                            mAndroidApplication.packageName, mResolveActivity.name);
6553                }
6554            }
6555        }
6556
6557        if (DEBUG_PACKAGE_SCANNING) {
6558            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6559                Log.d(TAG, "Scanning package " + pkg.packageName);
6560        }
6561
6562        if (mPackages.containsKey(pkg.packageName)
6563                || mSharedLibraries.containsKey(pkg.packageName)) {
6564            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6565                    "Application package " + pkg.packageName
6566                    + " already installed.  Skipping duplicate.");
6567        }
6568
6569        // If we're only installing presumed-existing packages, require that the
6570        // scanned APK is both already known and at the path previously established
6571        // for it.  Previously unknown packages we pick up normally, but if we have an
6572        // a priori expectation about this package's install presence, enforce it.
6573        // With a singular exception for new system packages. When an OTA contains
6574        // a new system package, we allow the codepath to change from a system location
6575        // to the user-installed location. If we don't allow this change, any newer,
6576        // user-installed version of the application will be ignored.
6577        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6578            if (mExpectingBetter.containsKey(pkg.packageName)) {
6579                logCriticalInfo(Log.WARN,
6580                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6581            } else {
6582                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6583                if (known != null) {
6584                    if (DEBUG_PACKAGE_SCANNING) {
6585                        Log.d(TAG, "Examining " + pkg.codePath
6586                                + " and requiring known paths " + known.codePathString
6587                                + " & " + known.resourcePathString);
6588                    }
6589                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6590                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6591                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6592                                "Application package " + pkg.packageName
6593                                + " found at " + pkg.applicationInfo.getCodePath()
6594                                + " but expected at " + known.codePathString + "; ignoring.");
6595                    }
6596                }
6597            }
6598        }
6599
6600        // Initialize package source and resource directories
6601        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6602        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6603
6604        SharedUserSetting suid = null;
6605        PackageSetting pkgSetting = null;
6606
6607        if (!isSystemApp(pkg)) {
6608            // Only system apps can use these features.
6609            pkg.mOriginalPackages = null;
6610            pkg.mRealPackage = null;
6611            pkg.mAdoptPermissions = null;
6612        }
6613
6614        // writer
6615        synchronized (mPackages) {
6616            if (pkg.mSharedUserId != null) {
6617                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6618                if (suid == null) {
6619                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6620                            "Creating application package " + pkg.packageName
6621                            + " for shared user failed");
6622                }
6623                if (DEBUG_PACKAGE_SCANNING) {
6624                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6625                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6626                                + "): packages=" + suid.packages);
6627                }
6628            }
6629
6630            // Check if we are renaming from an original package name.
6631            PackageSetting origPackage = null;
6632            String realName = null;
6633            if (pkg.mOriginalPackages != null) {
6634                // This package may need to be renamed to a previously
6635                // installed name.  Let's check on that...
6636                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6637                if (pkg.mOriginalPackages.contains(renamed)) {
6638                    // This package had originally been installed as the
6639                    // original name, and we have already taken care of
6640                    // transitioning to the new one.  Just update the new
6641                    // one to continue using the old name.
6642                    realName = pkg.mRealPackage;
6643                    if (!pkg.packageName.equals(renamed)) {
6644                        // Callers into this function may have already taken
6645                        // care of renaming the package; only do it here if
6646                        // it is not already done.
6647                        pkg.setPackageName(renamed);
6648                    }
6649
6650                } else {
6651                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6652                        if ((origPackage = mSettings.peekPackageLPr(
6653                                pkg.mOriginalPackages.get(i))) != null) {
6654                            // We do have the package already installed under its
6655                            // original name...  should we use it?
6656                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6657                                // New package is not compatible with original.
6658                                origPackage = null;
6659                                continue;
6660                            } else if (origPackage.sharedUser != null) {
6661                                // Make sure uid is compatible between packages.
6662                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6663                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6664                                            + " to " + pkg.packageName + ": old uid "
6665                                            + origPackage.sharedUser.name
6666                                            + " differs from " + pkg.mSharedUserId);
6667                                    origPackage = null;
6668                                    continue;
6669                                }
6670                            } else {
6671                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6672                                        + pkg.packageName + " to old name " + origPackage.name);
6673                            }
6674                            break;
6675                        }
6676                    }
6677                }
6678            }
6679
6680            if (mTransferedPackages.contains(pkg.packageName)) {
6681                Slog.w(TAG, "Package " + pkg.packageName
6682                        + " was transferred to another, but its .apk remains");
6683            }
6684
6685            // Just create the setting, don't add it yet. For already existing packages
6686            // the PkgSetting exists already and doesn't have to be created.
6687            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6688                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6689                    pkg.applicationInfo.primaryCpuAbi,
6690                    pkg.applicationInfo.secondaryCpuAbi,
6691                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6692                    user, false);
6693            if (pkgSetting == null) {
6694                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6695                        "Creating application package " + pkg.packageName + " failed");
6696            }
6697
6698            if (pkgSetting.origPackage != null) {
6699                // If we are first transitioning from an original package,
6700                // fix up the new package's name now.  We need to do this after
6701                // looking up the package under its new name, so getPackageLP
6702                // can take care of fiddling things correctly.
6703                pkg.setPackageName(origPackage.name);
6704
6705                // File a report about this.
6706                String msg = "New package " + pkgSetting.realName
6707                        + " renamed to replace old package " + pkgSetting.name;
6708                reportSettingsProblem(Log.WARN, msg);
6709
6710                // Make a note of it.
6711                mTransferedPackages.add(origPackage.name);
6712
6713                // No longer need to retain this.
6714                pkgSetting.origPackage = null;
6715            }
6716
6717            if (realName != null) {
6718                // Make a note of it.
6719                mTransferedPackages.add(pkg.packageName);
6720            }
6721
6722            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6723                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6724            }
6725
6726            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6727                // Check all shared libraries and map to their actual file path.
6728                // We only do this here for apps not on a system dir, because those
6729                // are the only ones that can fail an install due to this.  We
6730                // will take care of the system apps by updating all of their
6731                // library paths after the scan is done.
6732                updateSharedLibrariesLPw(pkg, null);
6733            }
6734
6735            if (mFoundPolicyFile) {
6736                SELinuxMMAC.assignSeinfoValue(pkg);
6737            }
6738
6739            pkg.applicationInfo.uid = pkgSetting.appId;
6740            pkg.mExtras = pkgSetting;
6741            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6742                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6743                    // We just determined the app is signed correctly, so bring
6744                    // over the latest parsed certs.
6745                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6746                } else {
6747                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6748                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6749                                "Package " + pkg.packageName + " upgrade keys do not match the "
6750                                + "previously installed version");
6751                    } else {
6752                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6753                        String msg = "System package " + pkg.packageName
6754                            + " signature changed; retaining data.";
6755                        reportSettingsProblem(Log.WARN, msg);
6756                    }
6757                }
6758            } else {
6759                try {
6760                    verifySignaturesLP(pkgSetting, pkg);
6761                    // We just determined the app is signed correctly, so bring
6762                    // over the latest parsed certs.
6763                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6764                } catch (PackageManagerException e) {
6765                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6766                        throw e;
6767                    }
6768                    // The signature has changed, but this package is in the system
6769                    // image...  let's recover!
6770                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6771                    // However...  if this package is part of a shared user, but it
6772                    // doesn't match the signature of the shared user, let's fail.
6773                    // What this means is that you can't change the signatures
6774                    // associated with an overall shared user, which doesn't seem all
6775                    // that unreasonable.
6776                    if (pkgSetting.sharedUser != null) {
6777                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6778                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6779                            throw new PackageManagerException(
6780                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6781                                            "Signature mismatch for shared user : "
6782                                            + pkgSetting.sharedUser);
6783                        }
6784                    }
6785                    // File a report about this.
6786                    String msg = "System package " + pkg.packageName
6787                        + " signature changed; retaining data.";
6788                    reportSettingsProblem(Log.WARN, msg);
6789                }
6790            }
6791            // Verify that this new package doesn't have any content providers
6792            // that conflict with existing packages.  Only do this if the
6793            // package isn't already installed, since we don't want to break
6794            // things that are installed.
6795            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6796                final int N = pkg.providers.size();
6797                int i;
6798                for (i=0; i<N; i++) {
6799                    PackageParser.Provider p = pkg.providers.get(i);
6800                    if (p.info.authority != null) {
6801                        String names[] = p.info.authority.split(";");
6802                        for (int j = 0; j < names.length; j++) {
6803                            if (mProvidersByAuthority.containsKey(names[j])) {
6804                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6805                                final String otherPackageName =
6806                                        ((other != null && other.getComponentName() != null) ?
6807                                                other.getComponentName().getPackageName() : "?");
6808                                throw new PackageManagerException(
6809                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6810                                                "Can't install because provider name " + names[j]
6811                                                + " (in package " + pkg.applicationInfo.packageName
6812                                                + ") is already used by " + otherPackageName);
6813                            }
6814                        }
6815                    }
6816                }
6817            }
6818
6819            if (pkg.mAdoptPermissions != null) {
6820                // This package wants to adopt ownership of permissions from
6821                // another package.
6822                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6823                    final String origName = pkg.mAdoptPermissions.get(i);
6824                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6825                    if (orig != null) {
6826                        if (verifyPackageUpdateLPr(orig, pkg)) {
6827                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6828                                    + pkg.packageName);
6829                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6830                        }
6831                    }
6832                }
6833            }
6834        }
6835
6836        final String pkgName = pkg.packageName;
6837
6838        final long scanFileTime = scanFile.lastModified();
6839        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6840        pkg.applicationInfo.processName = fixProcessName(
6841                pkg.applicationInfo.packageName,
6842                pkg.applicationInfo.processName,
6843                pkg.applicationInfo.uid);
6844
6845        File dataPath;
6846        if (mPlatformPackage == pkg) {
6847            // The system package is special.
6848            dataPath = new File(Environment.getDataDirectory(), "system");
6849
6850            pkg.applicationInfo.dataDir = dataPath.getPath();
6851
6852        } else {
6853            // This is a normal package, need to make its data directory.
6854            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6855                    UserHandle.USER_OWNER, pkg.packageName);
6856
6857            boolean uidError = false;
6858            if (dataPath.exists()) {
6859                int currentUid = 0;
6860                try {
6861                    StructStat stat = Os.stat(dataPath.getPath());
6862                    currentUid = stat.st_uid;
6863                } catch (ErrnoException e) {
6864                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6865                }
6866
6867                // If we have mismatched owners for the data path, we have a problem.
6868                if (currentUid != pkg.applicationInfo.uid) {
6869                    boolean recovered = false;
6870                    if (currentUid == 0) {
6871                        // The directory somehow became owned by root.  Wow.
6872                        // This is probably because the system was stopped while
6873                        // installd was in the middle of messing with its libs
6874                        // directory.  Ask installd to fix that.
6875                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6876                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6877                        if (ret >= 0) {
6878                            recovered = true;
6879                            String msg = "Package " + pkg.packageName
6880                                    + " unexpectedly changed to uid 0; recovered to " +
6881                                    + pkg.applicationInfo.uid;
6882                            reportSettingsProblem(Log.WARN, msg);
6883                        }
6884                    }
6885                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6886                            || (scanFlags&SCAN_BOOTING) != 0)) {
6887                        // If this is a system app, we can at least delete its
6888                        // current data so the application will still work.
6889                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6890                        if (ret >= 0) {
6891                            // TODO: Kill the processes first
6892                            // Old data gone!
6893                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6894                                    ? "System package " : "Third party package ";
6895                            String msg = prefix + pkg.packageName
6896                                    + " has changed from uid: "
6897                                    + currentUid + " to "
6898                                    + pkg.applicationInfo.uid + "; old data erased";
6899                            reportSettingsProblem(Log.WARN, msg);
6900                            recovered = true;
6901
6902                            // And now re-install the app.
6903                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6904                                    pkg.applicationInfo.seinfo);
6905                            if (ret == -1) {
6906                                // Ack should not happen!
6907                                msg = prefix + pkg.packageName
6908                                        + " could not have data directory re-created after delete.";
6909                                reportSettingsProblem(Log.WARN, msg);
6910                                throw new PackageManagerException(
6911                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6912                            }
6913                        }
6914                        if (!recovered) {
6915                            mHasSystemUidErrors = true;
6916                        }
6917                    } else if (!recovered) {
6918                        // If we allow this install to proceed, we will be broken.
6919                        // Abort, abort!
6920                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6921                                "scanPackageLI");
6922                    }
6923                    if (!recovered) {
6924                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6925                            + pkg.applicationInfo.uid + "/fs_"
6926                            + currentUid;
6927                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6928                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6929                        String msg = "Package " + pkg.packageName
6930                                + " has mismatched uid: "
6931                                + currentUid + " on disk, "
6932                                + pkg.applicationInfo.uid + " in settings";
6933                        // writer
6934                        synchronized (mPackages) {
6935                            mSettings.mReadMessages.append(msg);
6936                            mSettings.mReadMessages.append('\n');
6937                            uidError = true;
6938                            if (!pkgSetting.uidError) {
6939                                reportSettingsProblem(Log.ERROR, msg);
6940                            }
6941                        }
6942                    }
6943                }
6944                pkg.applicationInfo.dataDir = dataPath.getPath();
6945                if (mShouldRestoreconData) {
6946                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6947                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6948                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6949                }
6950            } else {
6951                if (DEBUG_PACKAGE_SCANNING) {
6952                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6953                        Log.v(TAG, "Want this data dir: " + dataPath);
6954                }
6955                //invoke installer to do the actual installation
6956                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6957                        pkg.applicationInfo.seinfo);
6958                if (ret < 0) {
6959                    // Error from installer
6960                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6961                            "Unable to create data dirs [errorCode=" + ret + "]");
6962                }
6963
6964                if (dataPath.exists()) {
6965                    pkg.applicationInfo.dataDir = dataPath.getPath();
6966                } else {
6967                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6968                    pkg.applicationInfo.dataDir = null;
6969                }
6970            }
6971
6972            pkgSetting.uidError = uidError;
6973        }
6974
6975        final String path = scanFile.getPath();
6976        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6977
6978        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6979            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6980
6981            // Some system apps still use directory structure for native libraries
6982            // in which case we might end up not detecting abi solely based on apk
6983            // structure. Try to detect abi based on directory structure.
6984            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6985                    pkg.applicationInfo.primaryCpuAbi == null) {
6986                setBundledAppAbisAndRoots(pkg, pkgSetting);
6987                setNativeLibraryPaths(pkg);
6988            }
6989
6990        } else {
6991            if ((scanFlags & SCAN_MOVE) != 0) {
6992                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6993                // but we already have this packages package info in the PackageSetting. We just
6994                // use that and derive the native library path based on the new codepath.
6995                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6996                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6997            }
6998
6999            // Set native library paths again. For moves, the path will be updated based on the
7000            // ABIs we've determined above. For non-moves, the path will be updated based on the
7001            // ABIs we determined during compilation, but the path will depend on the final
7002            // package path (after the rename away from the stage path).
7003            setNativeLibraryPaths(pkg);
7004        }
7005
7006        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7007        final int[] userIds = sUserManager.getUserIds();
7008        synchronized (mInstallLock) {
7009            // Make sure all user data directories are ready to roll; we're okay
7010            // if they already exist
7011            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7012                for (int userId : userIds) {
7013                    if (userId != 0) {
7014                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7015                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7016                                pkg.applicationInfo.seinfo);
7017                    }
7018                }
7019            }
7020
7021            // Create a native library symlink only if we have native libraries
7022            // and if the native libraries are 32 bit libraries. We do not provide
7023            // this symlink for 64 bit libraries.
7024            if (pkg.applicationInfo.primaryCpuAbi != null &&
7025                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7026                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7027                for (int userId : userIds) {
7028                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7029                            nativeLibPath, userId) < 0) {
7030                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7031                                "Failed linking native library dir (user=" + userId + ")");
7032                    }
7033                }
7034            }
7035        }
7036
7037        // This is a special case for the "system" package, where the ABI is
7038        // dictated by the zygote configuration (and init.rc). We should keep track
7039        // of this ABI so that we can deal with "normal" applications that run under
7040        // the same UID correctly.
7041        if (mPlatformPackage == pkg) {
7042            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7043                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7044        }
7045
7046        // If there's a mismatch between the abi-override in the package setting
7047        // and the abiOverride specified for the install. Warn about this because we
7048        // would've already compiled the app without taking the package setting into
7049        // account.
7050        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7051            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7052                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7053                        " for package: " + pkg.packageName);
7054            }
7055        }
7056
7057        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7058        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7059        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7060
7061        // Copy the derived override back to the parsed package, so that we can
7062        // update the package settings accordingly.
7063        pkg.cpuAbiOverride = cpuAbiOverride;
7064
7065        if (DEBUG_ABI_SELECTION) {
7066            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7067                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7068                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7069        }
7070
7071        // Push the derived path down into PackageSettings so we know what to
7072        // clean up at uninstall time.
7073        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7074
7075        if (DEBUG_ABI_SELECTION) {
7076            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7077                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7078                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7079        }
7080
7081        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7082            // We don't do this here during boot because we can do it all
7083            // at once after scanning all existing packages.
7084            //
7085            // We also do this *before* we perform dexopt on this package, so that
7086            // we can avoid redundant dexopts, and also to make sure we've got the
7087            // code and package path correct.
7088            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7089                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7090        }
7091
7092        if ((scanFlags & SCAN_NO_DEX) == 0) {
7093            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7094                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7095            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7096                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7097            }
7098        }
7099        if (mFactoryTest && pkg.requestedPermissions.contains(
7100                android.Manifest.permission.FACTORY_TEST)) {
7101            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7102        }
7103
7104        ArrayList<PackageParser.Package> clientLibPkgs = null;
7105
7106        // writer
7107        synchronized (mPackages) {
7108            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7109                // Only system apps can add new shared libraries.
7110                if (pkg.libraryNames != null) {
7111                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7112                        String name = pkg.libraryNames.get(i);
7113                        boolean allowed = false;
7114                        if (pkg.isUpdatedSystemApp()) {
7115                            // New library entries can only be added through the
7116                            // system image.  This is important to get rid of a lot
7117                            // of nasty edge cases: for example if we allowed a non-
7118                            // system update of the app to add a library, then uninstalling
7119                            // the update would make the library go away, and assumptions
7120                            // we made such as through app install filtering would now
7121                            // have allowed apps on the device which aren't compatible
7122                            // with it.  Better to just have the restriction here, be
7123                            // conservative, and create many fewer cases that can negatively
7124                            // impact the user experience.
7125                            final PackageSetting sysPs = mSettings
7126                                    .getDisabledSystemPkgLPr(pkg.packageName);
7127                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7128                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7129                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7130                                        allowed = true;
7131                                        allowed = true;
7132                                        break;
7133                                    }
7134                                }
7135                            }
7136                        } else {
7137                            allowed = true;
7138                        }
7139                        if (allowed) {
7140                            if (!mSharedLibraries.containsKey(name)) {
7141                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7142                            } else if (!name.equals(pkg.packageName)) {
7143                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7144                                        + name + " already exists; skipping");
7145                            }
7146                        } else {
7147                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7148                                    + name + " that is not declared on system image; skipping");
7149                        }
7150                    }
7151                    if ((scanFlags&SCAN_BOOTING) == 0) {
7152                        // If we are not booting, we need to update any applications
7153                        // that are clients of our shared library.  If we are booting,
7154                        // this will all be done once the scan is complete.
7155                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7156                    }
7157                }
7158            }
7159        }
7160
7161        // We also need to dexopt any apps that are dependent on this library.  Note that
7162        // if these fail, we should abort the install since installing the library will
7163        // result in some apps being broken.
7164        if (clientLibPkgs != null) {
7165            if ((scanFlags & SCAN_NO_DEX) == 0) {
7166                for (int i = 0; i < clientLibPkgs.size(); i++) {
7167                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7168                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7169                            null /* instruction sets */, forceDex,
7170                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7171                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7172                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7173                                "scanPackageLI failed to dexopt clientLibPkgs");
7174                    }
7175                }
7176            }
7177        }
7178
7179        // Request the ActivityManager to kill the process(only for existing packages)
7180        // so that we do not end up in a confused state while the user is still using the older
7181        // version of the application while the new one gets installed.
7182        if ((scanFlags & SCAN_REPLACING) != 0) {
7183            killApplication(pkg.applicationInfo.packageName,
7184                        pkg.applicationInfo.uid, "replace pkg");
7185        }
7186
7187        // Also need to kill any apps that are dependent on the library.
7188        if (clientLibPkgs != null) {
7189            for (int i=0; i<clientLibPkgs.size(); i++) {
7190                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7191                killApplication(clientPkg.applicationInfo.packageName,
7192                        clientPkg.applicationInfo.uid, "update lib");
7193            }
7194        }
7195
7196        // Make sure we're not adding any bogus keyset info
7197        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7198        ksms.assertScannedPackageValid(pkg);
7199
7200        // writer
7201        synchronized (mPackages) {
7202            // We don't expect installation to fail beyond this point
7203
7204            // Add the new setting to mSettings
7205            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7206            // Add the new setting to mPackages
7207            mPackages.put(pkg.applicationInfo.packageName, pkg);
7208            // Make sure we don't accidentally delete its data.
7209            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7210            while (iter.hasNext()) {
7211                PackageCleanItem item = iter.next();
7212                if (pkgName.equals(item.packageName)) {
7213                    iter.remove();
7214                }
7215            }
7216
7217            // Take care of first install / last update times.
7218            if (currentTime != 0) {
7219                if (pkgSetting.firstInstallTime == 0) {
7220                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7221                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7222                    pkgSetting.lastUpdateTime = currentTime;
7223                }
7224            } else if (pkgSetting.firstInstallTime == 0) {
7225                // We need *something*.  Take time time stamp of the file.
7226                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7227            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7228                if (scanFileTime != pkgSetting.timeStamp) {
7229                    // A package on the system image has changed; consider this
7230                    // to be an update.
7231                    pkgSetting.lastUpdateTime = scanFileTime;
7232                }
7233            }
7234
7235            // Add the package's KeySets to the global KeySetManagerService
7236            ksms.addScannedPackageLPw(pkg);
7237
7238            int N = pkg.providers.size();
7239            StringBuilder r = null;
7240            int i;
7241            for (i=0; i<N; i++) {
7242                PackageParser.Provider p = pkg.providers.get(i);
7243                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7244                        p.info.processName, pkg.applicationInfo.uid);
7245                mProviders.addProvider(p);
7246                p.syncable = p.info.isSyncable;
7247                if (p.info.authority != null) {
7248                    String names[] = p.info.authority.split(";");
7249                    p.info.authority = null;
7250                    for (int j = 0; j < names.length; j++) {
7251                        if (j == 1 && p.syncable) {
7252                            // We only want the first authority for a provider to possibly be
7253                            // syncable, so if we already added this provider using a different
7254                            // authority clear the syncable flag. We copy the provider before
7255                            // changing it because the mProviders object contains a reference
7256                            // to a provider that we don't want to change.
7257                            // Only do this for the second authority since the resulting provider
7258                            // object can be the same for all future authorities for this provider.
7259                            p = new PackageParser.Provider(p);
7260                            p.syncable = false;
7261                        }
7262                        if (!mProvidersByAuthority.containsKey(names[j])) {
7263                            mProvidersByAuthority.put(names[j], p);
7264                            if (p.info.authority == null) {
7265                                p.info.authority = names[j];
7266                            } else {
7267                                p.info.authority = p.info.authority + ";" + names[j];
7268                            }
7269                            if (DEBUG_PACKAGE_SCANNING) {
7270                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7271                                    Log.d(TAG, "Registered content provider: " + names[j]
7272                                            + ", className = " + p.info.name + ", isSyncable = "
7273                                            + p.info.isSyncable);
7274                            }
7275                        } else {
7276                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7277                            Slog.w(TAG, "Skipping provider name " + names[j] +
7278                                    " (in package " + pkg.applicationInfo.packageName +
7279                                    "): name already used by "
7280                                    + ((other != null && other.getComponentName() != null)
7281                                            ? other.getComponentName().getPackageName() : "?"));
7282                        }
7283                    }
7284                }
7285                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7286                    if (r == null) {
7287                        r = new StringBuilder(256);
7288                    } else {
7289                        r.append(' ');
7290                    }
7291                    r.append(p.info.name);
7292                }
7293            }
7294            if (r != null) {
7295                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7296            }
7297
7298            N = pkg.services.size();
7299            r = null;
7300            for (i=0; i<N; i++) {
7301                PackageParser.Service s = pkg.services.get(i);
7302                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7303                        s.info.processName, pkg.applicationInfo.uid);
7304                mServices.addService(s);
7305                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7306                    if (r == null) {
7307                        r = new StringBuilder(256);
7308                    } else {
7309                        r.append(' ');
7310                    }
7311                    r.append(s.info.name);
7312                }
7313            }
7314            if (r != null) {
7315                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7316            }
7317
7318            N = pkg.receivers.size();
7319            r = null;
7320            for (i=0; i<N; i++) {
7321                PackageParser.Activity a = pkg.receivers.get(i);
7322                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7323                        a.info.processName, pkg.applicationInfo.uid);
7324                mReceivers.addActivity(a, "receiver");
7325                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7326                    if (r == null) {
7327                        r = new StringBuilder(256);
7328                    } else {
7329                        r.append(' ');
7330                    }
7331                    r.append(a.info.name);
7332                }
7333            }
7334            if (r != null) {
7335                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7336            }
7337
7338            N = pkg.activities.size();
7339            r = null;
7340            for (i=0; i<N; i++) {
7341                PackageParser.Activity a = pkg.activities.get(i);
7342                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7343                        a.info.processName, pkg.applicationInfo.uid);
7344                mActivities.addActivity(a, "activity");
7345                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7346                    if (r == null) {
7347                        r = new StringBuilder(256);
7348                    } else {
7349                        r.append(' ');
7350                    }
7351                    r.append(a.info.name);
7352                }
7353            }
7354            if (r != null) {
7355                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7356            }
7357
7358            N = pkg.permissionGroups.size();
7359            r = null;
7360            for (i=0; i<N; i++) {
7361                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7362                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7363                if (cur == null) {
7364                    mPermissionGroups.put(pg.info.name, pg);
7365                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7366                        if (r == null) {
7367                            r = new StringBuilder(256);
7368                        } else {
7369                            r.append(' ');
7370                        }
7371                        r.append(pg.info.name);
7372                    }
7373                } else {
7374                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7375                            + pg.info.packageName + " ignored: original from "
7376                            + cur.info.packageName);
7377                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7378                        if (r == null) {
7379                            r = new StringBuilder(256);
7380                        } else {
7381                            r.append(' ');
7382                        }
7383                        r.append("DUP:");
7384                        r.append(pg.info.name);
7385                    }
7386                }
7387            }
7388            if (r != null) {
7389                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7390            }
7391
7392            N = pkg.permissions.size();
7393            r = null;
7394            for (i=0; i<N; i++) {
7395                PackageParser.Permission p = pkg.permissions.get(i);
7396
7397                // Assume by default that we did not install this permission into the system.
7398                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7399
7400                // Now that permission groups have a special meaning, we ignore permission
7401                // groups for legacy apps to prevent unexpected behavior. In particular,
7402                // permissions for one app being granted to someone just becuase they happen
7403                // to be in a group defined by another app (before this had no implications).
7404                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7405                    p.group = mPermissionGroups.get(p.info.group);
7406                    // Warn for a permission in an unknown group.
7407                    if (p.info.group != null && p.group == null) {
7408                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7409                                + p.info.packageName + " in an unknown group " + p.info.group);
7410                    }
7411                }
7412
7413                ArrayMap<String, BasePermission> permissionMap =
7414                        p.tree ? mSettings.mPermissionTrees
7415                                : mSettings.mPermissions;
7416                BasePermission bp = permissionMap.get(p.info.name);
7417
7418                // Allow system apps to redefine non-system permissions
7419                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7420                    final boolean currentOwnerIsSystem = (bp.perm != null
7421                            && isSystemApp(bp.perm.owner));
7422                    if (isSystemApp(p.owner)) {
7423                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7424                            // It's a built-in permission and no owner, take ownership now
7425                            bp.packageSetting = pkgSetting;
7426                            bp.perm = p;
7427                            bp.uid = pkg.applicationInfo.uid;
7428                            bp.sourcePackage = p.info.packageName;
7429                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7430                        } else if (!currentOwnerIsSystem) {
7431                            String msg = "New decl " + p.owner + " of permission  "
7432                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7433                            reportSettingsProblem(Log.WARN, msg);
7434                            bp = null;
7435                        }
7436                    }
7437                }
7438
7439                if (bp == null) {
7440                    bp = new BasePermission(p.info.name, p.info.packageName,
7441                            BasePermission.TYPE_NORMAL);
7442                    permissionMap.put(p.info.name, bp);
7443                }
7444
7445                if (bp.perm == null) {
7446                    if (bp.sourcePackage == null
7447                            || bp.sourcePackage.equals(p.info.packageName)) {
7448                        BasePermission tree = findPermissionTreeLP(p.info.name);
7449                        if (tree == null
7450                                || tree.sourcePackage.equals(p.info.packageName)) {
7451                            bp.packageSetting = pkgSetting;
7452                            bp.perm = p;
7453                            bp.uid = pkg.applicationInfo.uid;
7454                            bp.sourcePackage = p.info.packageName;
7455                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7456                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7457                                if (r == null) {
7458                                    r = new StringBuilder(256);
7459                                } else {
7460                                    r.append(' ');
7461                                }
7462                                r.append(p.info.name);
7463                            }
7464                        } else {
7465                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7466                                    + p.info.packageName + " ignored: base tree "
7467                                    + tree.name + " is from package "
7468                                    + tree.sourcePackage);
7469                        }
7470                    } else {
7471                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7472                                + p.info.packageName + " ignored: original from "
7473                                + bp.sourcePackage);
7474                    }
7475                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7476                    if (r == null) {
7477                        r = new StringBuilder(256);
7478                    } else {
7479                        r.append(' ');
7480                    }
7481                    r.append("DUP:");
7482                    r.append(p.info.name);
7483                }
7484                if (bp.perm == p) {
7485                    bp.protectionLevel = p.info.protectionLevel;
7486                }
7487            }
7488
7489            if (r != null) {
7490                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7491            }
7492
7493            N = pkg.instrumentation.size();
7494            r = null;
7495            for (i=0; i<N; i++) {
7496                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7497                a.info.packageName = pkg.applicationInfo.packageName;
7498                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7499                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7500                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7501                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7502                a.info.dataDir = pkg.applicationInfo.dataDir;
7503
7504                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7505                // need other information about the application, like the ABI and what not ?
7506                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7507                mInstrumentation.put(a.getComponentName(), a);
7508                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7509                    if (r == null) {
7510                        r = new StringBuilder(256);
7511                    } else {
7512                        r.append(' ');
7513                    }
7514                    r.append(a.info.name);
7515                }
7516            }
7517            if (r != null) {
7518                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7519            }
7520
7521            if (pkg.protectedBroadcasts != null) {
7522                N = pkg.protectedBroadcasts.size();
7523                for (i=0; i<N; i++) {
7524                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7525                }
7526            }
7527
7528            pkgSetting.setTimeStamp(scanFileTime);
7529
7530            // Create idmap files for pairs of (packages, overlay packages).
7531            // Note: "android", ie framework-res.apk, is handled by native layers.
7532            if (pkg.mOverlayTarget != null) {
7533                // This is an overlay package.
7534                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7535                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7536                        mOverlays.put(pkg.mOverlayTarget,
7537                                new ArrayMap<String, PackageParser.Package>());
7538                    }
7539                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7540                    map.put(pkg.packageName, pkg);
7541                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7542                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7543                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7544                                "scanPackageLI failed to createIdmap");
7545                    }
7546                }
7547            } else if (mOverlays.containsKey(pkg.packageName) &&
7548                    !pkg.packageName.equals("android")) {
7549                // This is a regular package, with one or more known overlay packages.
7550                createIdmapsForPackageLI(pkg);
7551            }
7552        }
7553
7554        return pkg;
7555    }
7556
7557    /**
7558     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7559     * is derived purely on the basis of the contents of {@code scanFile} and
7560     * {@code cpuAbiOverride}.
7561     *
7562     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7563     */
7564    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7565                                 String cpuAbiOverride, boolean extractLibs)
7566            throws PackageManagerException {
7567        // TODO: We can probably be smarter about this stuff. For installed apps,
7568        // we can calculate this information at install time once and for all. For
7569        // system apps, we can probably assume that this information doesn't change
7570        // after the first boot scan. As things stand, we do lots of unnecessary work.
7571
7572        // Give ourselves some initial paths; we'll come back for another
7573        // pass once we've determined ABI below.
7574        setNativeLibraryPaths(pkg);
7575
7576        // We would never need to extract libs for forward-locked and external packages,
7577        // since the container service will do it for us. We shouldn't attempt to
7578        // extract libs from system app when it was not updated.
7579        if (pkg.isForwardLocked() || isExternal(pkg) ||
7580            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7581            extractLibs = false;
7582        }
7583
7584        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7585        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7586
7587        NativeLibraryHelper.Handle handle = null;
7588        try {
7589            handle = NativeLibraryHelper.Handle.create(scanFile);
7590            // TODO(multiArch): This can be null for apps that didn't go through the
7591            // usual installation process. We can calculate it again, like we
7592            // do during install time.
7593            //
7594            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7595            // unnecessary.
7596            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7597
7598            // Null out the abis so that they can be recalculated.
7599            pkg.applicationInfo.primaryCpuAbi = null;
7600            pkg.applicationInfo.secondaryCpuAbi = null;
7601            if (isMultiArch(pkg.applicationInfo)) {
7602                // Warn if we've set an abiOverride for multi-lib packages..
7603                // By definition, we need to copy both 32 and 64 bit libraries for
7604                // such packages.
7605                if (pkg.cpuAbiOverride != null
7606                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7607                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7608                }
7609
7610                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7611                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7612                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7613                    if (extractLibs) {
7614                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7615                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7616                                useIsaSpecificSubdirs);
7617                    } else {
7618                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7619                    }
7620                }
7621
7622                maybeThrowExceptionForMultiArchCopy(
7623                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7624
7625                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7626                    if (extractLibs) {
7627                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7628                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7629                                useIsaSpecificSubdirs);
7630                    } else {
7631                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7632                    }
7633                }
7634
7635                maybeThrowExceptionForMultiArchCopy(
7636                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7637
7638                if (abi64 >= 0) {
7639                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7640                }
7641
7642                if (abi32 >= 0) {
7643                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7644                    if (abi64 >= 0) {
7645                        pkg.applicationInfo.secondaryCpuAbi = abi;
7646                    } else {
7647                        pkg.applicationInfo.primaryCpuAbi = abi;
7648                    }
7649                }
7650            } else {
7651                String[] abiList = (cpuAbiOverride != null) ?
7652                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7653
7654                // Enable gross and lame hacks for apps that are built with old
7655                // SDK tools. We must scan their APKs for renderscript bitcode and
7656                // not launch them if it's present. Don't bother checking on devices
7657                // that don't have 64 bit support.
7658                boolean needsRenderScriptOverride = false;
7659                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7660                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7661                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7662                    needsRenderScriptOverride = true;
7663                }
7664
7665                final int copyRet;
7666                if (extractLibs) {
7667                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7668                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7669                } else {
7670                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7671                }
7672
7673                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7674                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7675                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7676                }
7677
7678                if (copyRet >= 0) {
7679                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7680                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7681                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7682                } else if (needsRenderScriptOverride) {
7683                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7684                }
7685            }
7686        } catch (IOException ioe) {
7687            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7688        } finally {
7689            IoUtils.closeQuietly(handle);
7690        }
7691
7692        // Now that we've calculated the ABIs and determined if it's an internal app,
7693        // we will go ahead and populate the nativeLibraryPath.
7694        setNativeLibraryPaths(pkg);
7695    }
7696
7697    /**
7698     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7699     * i.e, so that all packages can be run inside a single process if required.
7700     *
7701     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7702     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7703     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7704     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7705     * updating a package that belongs to a shared user.
7706     *
7707     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7708     * adds unnecessary complexity.
7709     */
7710    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7711            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7712        String requiredInstructionSet = null;
7713        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7714            requiredInstructionSet = VMRuntime.getInstructionSet(
7715                     scannedPackage.applicationInfo.primaryCpuAbi);
7716        }
7717
7718        PackageSetting requirer = null;
7719        for (PackageSetting ps : packagesForUser) {
7720            // If packagesForUser contains scannedPackage, we skip it. This will happen
7721            // when scannedPackage is an update of an existing package. Without this check,
7722            // we will never be able to change the ABI of any package belonging to a shared
7723            // user, even if it's compatible with other packages.
7724            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7725                if (ps.primaryCpuAbiString == null) {
7726                    continue;
7727                }
7728
7729                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7730                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7731                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7732                    // this but there's not much we can do.
7733                    String errorMessage = "Instruction set mismatch, "
7734                            + ((requirer == null) ? "[caller]" : requirer)
7735                            + " requires " + requiredInstructionSet + " whereas " + ps
7736                            + " requires " + instructionSet;
7737                    Slog.w(TAG, errorMessage);
7738                }
7739
7740                if (requiredInstructionSet == null) {
7741                    requiredInstructionSet = instructionSet;
7742                    requirer = ps;
7743                }
7744            }
7745        }
7746
7747        if (requiredInstructionSet != null) {
7748            String adjustedAbi;
7749            if (requirer != null) {
7750                // requirer != null implies that either scannedPackage was null or that scannedPackage
7751                // did not require an ABI, in which case we have to adjust scannedPackage to match
7752                // the ABI of the set (which is the same as requirer's ABI)
7753                adjustedAbi = requirer.primaryCpuAbiString;
7754                if (scannedPackage != null) {
7755                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7756                }
7757            } else {
7758                // requirer == null implies that we're updating all ABIs in the set to
7759                // match scannedPackage.
7760                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7761            }
7762
7763            for (PackageSetting ps : packagesForUser) {
7764                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7765                    if (ps.primaryCpuAbiString != null) {
7766                        continue;
7767                    }
7768
7769                    ps.primaryCpuAbiString = adjustedAbi;
7770                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7771                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7772                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7773
7774                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7775                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7776                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7777                            ps.primaryCpuAbiString = null;
7778                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7779                            return;
7780                        } else {
7781                            mInstaller.rmdex(ps.codePathString,
7782                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7783                        }
7784                    }
7785                }
7786            }
7787        }
7788    }
7789
7790    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7791        synchronized (mPackages) {
7792            mResolverReplaced = true;
7793            // Set up information for custom user intent resolution activity.
7794            mResolveActivity.applicationInfo = pkg.applicationInfo;
7795            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7796            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7797            mResolveActivity.processName = pkg.applicationInfo.packageName;
7798            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7799            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7800                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7801            mResolveActivity.theme = 0;
7802            mResolveActivity.exported = true;
7803            mResolveActivity.enabled = true;
7804            mResolveInfo.activityInfo = mResolveActivity;
7805            mResolveInfo.priority = 0;
7806            mResolveInfo.preferredOrder = 0;
7807            mResolveInfo.match = 0;
7808            mResolveComponentName = mCustomResolverComponentName;
7809            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7810                    mResolveComponentName);
7811        }
7812    }
7813
7814    private static String calculateBundledApkRoot(final String codePathString) {
7815        final File codePath = new File(codePathString);
7816        final File codeRoot;
7817        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7818            codeRoot = Environment.getRootDirectory();
7819        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7820            codeRoot = Environment.getOemDirectory();
7821        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7822            codeRoot = Environment.getVendorDirectory();
7823        } else {
7824            // Unrecognized code path; take its top real segment as the apk root:
7825            // e.g. /something/app/blah.apk => /something
7826            try {
7827                File f = codePath.getCanonicalFile();
7828                File parent = f.getParentFile();    // non-null because codePath is a file
7829                File tmp;
7830                while ((tmp = parent.getParentFile()) != null) {
7831                    f = parent;
7832                    parent = tmp;
7833                }
7834                codeRoot = f;
7835                Slog.w(TAG, "Unrecognized code path "
7836                        + codePath + " - using " + codeRoot);
7837            } catch (IOException e) {
7838                // Can't canonicalize the code path -- shenanigans?
7839                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7840                return Environment.getRootDirectory().getPath();
7841            }
7842        }
7843        return codeRoot.getPath();
7844    }
7845
7846    /**
7847     * Derive and set the location of native libraries for the given package,
7848     * which varies depending on where and how the package was installed.
7849     */
7850    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7851        final ApplicationInfo info = pkg.applicationInfo;
7852        final String codePath = pkg.codePath;
7853        final File codeFile = new File(codePath);
7854        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7855        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7856
7857        info.nativeLibraryRootDir = null;
7858        info.nativeLibraryRootRequiresIsa = false;
7859        info.nativeLibraryDir = null;
7860        info.secondaryNativeLibraryDir = null;
7861
7862        if (isApkFile(codeFile)) {
7863            // Monolithic install
7864            if (bundledApp) {
7865                // If "/system/lib64/apkname" exists, assume that is the per-package
7866                // native library directory to use; otherwise use "/system/lib/apkname".
7867                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7868                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7869                        getPrimaryInstructionSet(info));
7870
7871                // This is a bundled system app so choose the path based on the ABI.
7872                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7873                // is just the default path.
7874                final String apkName = deriveCodePathName(codePath);
7875                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7876                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7877                        apkName).getAbsolutePath();
7878
7879                if (info.secondaryCpuAbi != null) {
7880                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7881                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7882                            secondaryLibDir, apkName).getAbsolutePath();
7883                }
7884            } else if (asecApp) {
7885                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7886                        .getAbsolutePath();
7887            } else {
7888                final String apkName = deriveCodePathName(codePath);
7889                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7890                        .getAbsolutePath();
7891            }
7892
7893            info.nativeLibraryRootRequiresIsa = false;
7894            info.nativeLibraryDir = info.nativeLibraryRootDir;
7895        } else {
7896            // Cluster install
7897            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7898            info.nativeLibraryRootRequiresIsa = true;
7899
7900            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7901                    getPrimaryInstructionSet(info)).getAbsolutePath();
7902
7903            if (info.secondaryCpuAbi != null) {
7904                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7905                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7906            }
7907        }
7908    }
7909
7910    /**
7911     * Calculate the abis and roots for a bundled app. These can uniquely
7912     * be determined from the contents of the system partition, i.e whether
7913     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7914     * of this information, and instead assume that the system was built
7915     * sensibly.
7916     */
7917    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7918                                           PackageSetting pkgSetting) {
7919        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7920
7921        // If "/system/lib64/apkname" exists, assume that is the per-package
7922        // native library directory to use; otherwise use "/system/lib/apkname".
7923        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7924        setBundledAppAbi(pkg, apkRoot, apkName);
7925        // pkgSetting might be null during rescan following uninstall of updates
7926        // to a bundled app, so accommodate that possibility.  The settings in
7927        // that case will be established later from the parsed package.
7928        //
7929        // If the settings aren't null, sync them up with what we've just derived.
7930        // note that apkRoot isn't stored in the package settings.
7931        if (pkgSetting != null) {
7932            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7933            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7934        }
7935    }
7936
7937    /**
7938     * Deduces the ABI of a bundled app and sets the relevant fields on the
7939     * parsed pkg object.
7940     *
7941     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7942     *        under which system libraries are installed.
7943     * @param apkName the name of the installed package.
7944     */
7945    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7946        final File codeFile = new File(pkg.codePath);
7947
7948        final boolean has64BitLibs;
7949        final boolean has32BitLibs;
7950        if (isApkFile(codeFile)) {
7951            // Monolithic install
7952            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7953            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7954        } else {
7955            // Cluster install
7956            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7957            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7958                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7959                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7960                has64BitLibs = (new File(rootDir, isa)).exists();
7961            } else {
7962                has64BitLibs = false;
7963            }
7964            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7965                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7966                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7967                has32BitLibs = (new File(rootDir, isa)).exists();
7968            } else {
7969                has32BitLibs = false;
7970            }
7971        }
7972
7973        if (has64BitLibs && !has32BitLibs) {
7974            // The package has 64 bit libs, but not 32 bit libs. Its primary
7975            // ABI should be 64 bit. We can safely assume here that the bundled
7976            // native libraries correspond to the most preferred ABI in the list.
7977
7978            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7979            pkg.applicationInfo.secondaryCpuAbi = null;
7980        } else if (has32BitLibs && !has64BitLibs) {
7981            // The package has 32 bit libs but not 64 bit libs. Its primary
7982            // ABI should be 32 bit.
7983
7984            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7985            pkg.applicationInfo.secondaryCpuAbi = null;
7986        } else if (has32BitLibs && has64BitLibs) {
7987            // The application has both 64 and 32 bit bundled libraries. We check
7988            // here that the app declares multiArch support, and warn if it doesn't.
7989            //
7990            // We will be lenient here and record both ABIs. The primary will be the
7991            // ABI that's higher on the list, i.e, a device that's configured to prefer
7992            // 64 bit apps will see a 64 bit primary ABI,
7993
7994            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7995                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7996            }
7997
7998            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7999                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8000                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8001            } else {
8002                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8003                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8004            }
8005        } else {
8006            pkg.applicationInfo.primaryCpuAbi = null;
8007            pkg.applicationInfo.secondaryCpuAbi = null;
8008        }
8009    }
8010
8011    private void killApplication(String pkgName, int appId, String reason) {
8012        // Request the ActivityManager to kill the process(only for existing packages)
8013        // so that we do not end up in a confused state while the user is still using the older
8014        // version of the application while the new one gets installed.
8015        IActivityManager am = ActivityManagerNative.getDefault();
8016        if (am != null) {
8017            try {
8018                am.killApplicationWithAppId(pkgName, appId, reason);
8019            } catch (RemoteException e) {
8020            }
8021        }
8022    }
8023
8024    void removePackageLI(PackageSetting ps, boolean chatty) {
8025        if (DEBUG_INSTALL) {
8026            if (chatty)
8027                Log.d(TAG, "Removing package " + ps.name);
8028        }
8029
8030        // writer
8031        synchronized (mPackages) {
8032            mPackages.remove(ps.name);
8033            final PackageParser.Package pkg = ps.pkg;
8034            if (pkg != null) {
8035                cleanPackageDataStructuresLILPw(pkg, chatty);
8036            }
8037        }
8038    }
8039
8040    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8041        if (DEBUG_INSTALL) {
8042            if (chatty)
8043                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8044        }
8045
8046        // writer
8047        synchronized (mPackages) {
8048            mPackages.remove(pkg.applicationInfo.packageName);
8049            cleanPackageDataStructuresLILPw(pkg, chatty);
8050        }
8051    }
8052
8053    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8054        int N = pkg.providers.size();
8055        StringBuilder r = null;
8056        int i;
8057        for (i=0; i<N; i++) {
8058            PackageParser.Provider p = pkg.providers.get(i);
8059            mProviders.removeProvider(p);
8060            if (p.info.authority == null) {
8061
8062                /* There was another ContentProvider with this authority when
8063                 * this app was installed so this authority is null,
8064                 * Ignore it as we don't have to unregister the provider.
8065                 */
8066                continue;
8067            }
8068            String names[] = p.info.authority.split(";");
8069            for (int j = 0; j < names.length; j++) {
8070                if (mProvidersByAuthority.get(names[j]) == p) {
8071                    mProvidersByAuthority.remove(names[j]);
8072                    if (DEBUG_REMOVE) {
8073                        if (chatty)
8074                            Log.d(TAG, "Unregistered content provider: " + names[j]
8075                                    + ", className = " + p.info.name + ", isSyncable = "
8076                                    + p.info.isSyncable);
8077                    }
8078                }
8079            }
8080            if (DEBUG_REMOVE && chatty) {
8081                if (r == null) {
8082                    r = new StringBuilder(256);
8083                } else {
8084                    r.append(' ');
8085                }
8086                r.append(p.info.name);
8087            }
8088        }
8089        if (r != null) {
8090            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8091        }
8092
8093        N = pkg.services.size();
8094        r = null;
8095        for (i=0; i<N; i++) {
8096            PackageParser.Service s = pkg.services.get(i);
8097            mServices.removeService(s);
8098            if (chatty) {
8099                if (r == null) {
8100                    r = new StringBuilder(256);
8101                } else {
8102                    r.append(' ');
8103                }
8104                r.append(s.info.name);
8105            }
8106        }
8107        if (r != null) {
8108            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8109        }
8110
8111        N = pkg.receivers.size();
8112        r = null;
8113        for (i=0; i<N; i++) {
8114            PackageParser.Activity a = pkg.receivers.get(i);
8115            mReceivers.removeActivity(a, "receiver");
8116            if (DEBUG_REMOVE && chatty) {
8117                if (r == null) {
8118                    r = new StringBuilder(256);
8119                } else {
8120                    r.append(' ');
8121                }
8122                r.append(a.info.name);
8123            }
8124        }
8125        if (r != null) {
8126            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8127        }
8128
8129        N = pkg.activities.size();
8130        r = null;
8131        for (i=0; i<N; i++) {
8132            PackageParser.Activity a = pkg.activities.get(i);
8133            mActivities.removeActivity(a, "activity");
8134            if (DEBUG_REMOVE && chatty) {
8135                if (r == null) {
8136                    r = new StringBuilder(256);
8137                } else {
8138                    r.append(' ');
8139                }
8140                r.append(a.info.name);
8141            }
8142        }
8143        if (r != null) {
8144            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8145        }
8146
8147        N = pkg.permissions.size();
8148        r = null;
8149        for (i=0; i<N; i++) {
8150            PackageParser.Permission p = pkg.permissions.get(i);
8151            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8152            if (bp == null) {
8153                bp = mSettings.mPermissionTrees.get(p.info.name);
8154            }
8155            if (bp != null && bp.perm == p) {
8156                bp.perm = null;
8157                if (DEBUG_REMOVE && chatty) {
8158                    if (r == null) {
8159                        r = new StringBuilder(256);
8160                    } else {
8161                        r.append(' ');
8162                    }
8163                    r.append(p.info.name);
8164                }
8165            }
8166            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8167                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8168                if (appOpPerms != null) {
8169                    appOpPerms.remove(pkg.packageName);
8170                }
8171            }
8172        }
8173        if (r != null) {
8174            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8175        }
8176
8177        N = pkg.requestedPermissions.size();
8178        r = null;
8179        for (i=0; i<N; i++) {
8180            String perm = pkg.requestedPermissions.get(i);
8181            BasePermission bp = mSettings.mPermissions.get(perm);
8182            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8183                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8184                if (appOpPerms != null) {
8185                    appOpPerms.remove(pkg.packageName);
8186                    if (appOpPerms.isEmpty()) {
8187                        mAppOpPermissionPackages.remove(perm);
8188                    }
8189                }
8190            }
8191        }
8192        if (r != null) {
8193            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8194        }
8195
8196        N = pkg.instrumentation.size();
8197        r = null;
8198        for (i=0; i<N; i++) {
8199            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8200            mInstrumentation.remove(a.getComponentName());
8201            if (DEBUG_REMOVE && chatty) {
8202                if (r == null) {
8203                    r = new StringBuilder(256);
8204                } else {
8205                    r.append(' ');
8206                }
8207                r.append(a.info.name);
8208            }
8209        }
8210        if (r != null) {
8211            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8212        }
8213
8214        r = null;
8215        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8216            // Only system apps can hold shared libraries.
8217            if (pkg.libraryNames != null) {
8218                for (i=0; i<pkg.libraryNames.size(); i++) {
8219                    String name = pkg.libraryNames.get(i);
8220                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8221                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8222                        mSharedLibraries.remove(name);
8223                        if (DEBUG_REMOVE && chatty) {
8224                            if (r == null) {
8225                                r = new StringBuilder(256);
8226                            } else {
8227                                r.append(' ');
8228                            }
8229                            r.append(name);
8230                        }
8231                    }
8232                }
8233            }
8234        }
8235        if (r != null) {
8236            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8237        }
8238    }
8239
8240    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8241        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8242            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8243                return true;
8244            }
8245        }
8246        return false;
8247    }
8248
8249    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8250    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8251    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8252
8253    private void updatePermissionsLPw(String changingPkg,
8254            PackageParser.Package pkgInfo, int flags) {
8255        // Make sure there are no dangling permission trees.
8256        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8257        while (it.hasNext()) {
8258            final BasePermission bp = it.next();
8259            if (bp.packageSetting == null) {
8260                // We may not yet have parsed the package, so just see if
8261                // we still know about its settings.
8262                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8263            }
8264            if (bp.packageSetting == null) {
8265                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8266                        + " from package " + bp.sourcePackage);
8267                it.remove();
8268            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8269                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8270                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8271                            + " from package " + bp.sourcePackage);
8272                    flags |= UPDATE_PERMISSIONS_ALL;
8273                    it.remove();
8274                }
8275            }
8276        }
8277
8278        // Make sure all dynamic permissions have been assigned to a package,
8279        // and make sure there are no dangling permissions.
8280        it = mSettings.mPermissions.values().iterator();
8281        while (it.hasNext()) {
8282            final BasePermission bp = it.next();
8283            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8284                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8285                        + bp.name + " pkg=" + bp.sourcePackage
8286                        + " info=" + bp.pendingInfo);
8287                if (bp.packageSetting == null && bp.pendingInfo != null) {
8288                    final BasePermission tree = findPermissionTreeLP(bp.name);
8289                    if (tree != null && tree.perm != null) {
8290                        bp.packageSetting = tree.packageSetting;
8291                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8292                                new PermissionInfo(bp.pendingInfo));
8293                        bp.perm.info.packageName = tree.perm.info.packageName;
8294                        bp.perm.info.name = bp.name;
8295                        bp.uid = tree.uid;
8296                    }
8297                }
8298            }
8299            if (bp.packageSetting == null) {
8300                // We may not yet have parsed the package, so just see if
8301                // we still know about its settings.
8302                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8303            }
8304            if (bp.packageSetting == null) {
8305                Slog.w(TAG, "Removing dangling permission: " + bp.name
8306                        + " from package " + bp.sourcePackage);
8307                it.remove();
8308            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8309                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8310                    Slog.i(TAG, "Removing old permission: " + bp.name
8311                            + " from package " + bp.sourcePackage);
8312                    flags |= UPDATE_PERMISSIONS_ALL;
8313                    it.remove();
8314                }
8315            }
8316        }
8317
8318        // Now update the permissions for all packages, in particular
8319        // replace the granted permissions of the system packages.
8320        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8321            for (PackageParser.Package pkg : mPackages.values()) {
8322                if (pkg != pkgInfo) {
8323                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8324                            changingPkg);
8325                }
8326            }
8327        }
8328
8329        if (pkgInfo != null) {
8330            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8331        }
8332    }
8333
8334    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8335            String packageOfInterest) {
8336        // IMPORTANT: There are two types of permissions: install and runtime.
8337        // Install time permissions are granted when the app is installed to
8338        // all device users and users added in the future. Runtime permissions
8339        // are granted at runtime explicitly to specific users. Normal and signature
8340        // protected permissions are install time permissions. Dangerous permissions
8341        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8342        // otherwise they are runtime permissions. This function does not manage
8343        // runtime permissions except for the case an app targeting Lollipop MR1
8344        // being upgraded to target a newer SDK, in which case dangerous permissions
8345        // are transformed from install time to runtime ones.
8346
8347        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8348        if (ps == null) {
8349            return;
8350        }
8351
8352        PermissionsState permissionsState = ps.getPermissionsState();
8353        PermissionsState origPermissions = permissionsState;
8354
8355        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8356
8357        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8358
8359        boolean changedInstallPermission = false;
8360
8361        if (replace) {
8362            ps.installPermissionsFixed = false;
8363            if (!ps.isSharedUser()) {
8364                origPermissions = new PermissionsState(permissionsState);
8365                permissionsState.reset();
8366            }
8367        }
8368
8369        permissionsState.setGlobalGids(mGlobalGids);
8370
8371        final int N = pkg.requestedPermissions.size();
8372        for (int i=0; i<N; i++) {
8373            final String name = pkg.requestedPermissions.get(i);
8374            final BasePermission bp = mSettings.mPermissions.get(name);
8375
8376            if (DEBUG_INSTALL) {
8377                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8378            }
8379
8380            if (bp == null || bp.packageSetting == null) {
8381                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8382                    Slog.w(TAG, "Unknown permission " + name
8383                            + " in package " + pkg.packageName);
8384                }
8385                continue;
8386            }
8387
8388            final String perm = bp.name;
8389            boolean allowedSig = false;
8390            int grant = GRANT_DENIED;
8391
8392            // Keep track of app op permissions.
8393            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8394                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8395                if (pkgs == null) {
8396                    pkgs = new ArraySet<>();
8397                    mAppOpPermissionPackages.put(bp.name, pkgs);
8398                }
8399                pkgs.add(pkg.packageName);
8400            }
8401
8402            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8403            switch (level) {
8404                case PermissionInfo.PROTECTION_NORMAL: {
8405                    // For all apps normal permissions are install time ones.
8406                    grant = GRANT_INSTALL;
8407                } break;
8408
8409                case PermissionInfo.PROTECTION_DANGEROUS: {
8410                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8411                        // For legacy apps dangerous permissions are install time ones.
8412                        grant = GRANT_INSTALL_LEGACY;
8413                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8414                        // For legacy apps that became modern, install becomes runtime.
8415                        grant = GRANT_UPGRADE;
8416                    } else if (mPromoteSystemApps
8417                            && isSystemApp(ps)
8418                            && mExistingSystemPackages.contains(ps.name)) {
8419                        // For legacy system apps, install becomes runtime.
8420                        // We cannot check hasInstallPermission() for system apps since those
8421                        // permissions were granted implicitly and not persisted pre-M.
8422                        grant = GRANT_UPGRADE;
8423                    } else {
8424                        // For modern apps keep runtime permissions unchanged.
8425                        grant = GRANT_RUNTIME;
8426                    }
8427                } break;
8428
8429                case PermissionInfo.PROTECTION_SIGNATURE: {
8430                    // For all apps signature permissions are install time ones.
8431                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8432                    if (allowedSig) {
8433                        grant = GRANT_INSTALL;
8434                    }
8435                } break;
8436            }
8437
8438            if (DEBUG_INSTALL) {
8439                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8440            }
8441
8442            if (grant != GRANT_DENIED) {
8443                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8444                    // If this is an existing, non-system package, then
8445                    // we can't add any new permissions to it.
8446                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8447                        // Except...  if this is a permission that was added
8448                        // to the platform (note: need to only do this when
8449                        // updating the platform).
8450                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8451                            grant = GRANT_DENIED;
8452                        }
8453                    }
8454                }
8455
8456                switch (grant) {
8457                    case GRANT_INSTALL: {
8458                        // Revoke this as runtime permission to handle the case of
8459                        // a runtime permission being downgraded to an install one.
8460                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8461                            if (origPermissions.getRuntimePermissionState(
8462                                    bp.name, userId) != null) {
8463                                // Revoke the runtime permission and clear the flags.
8464                                origPermissions.revokeRuntimePermission(bp, userId);
8465                                origPermissions.updatePermissionFlags(bp, userId,
8466                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8467                                // If we revoked a permission permission, we have to write.
8468                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8469                                        changedRuntimePermissionUserIds, userId);
8470                            }
8471                        }
8472                        // Grant an install permission.
8473                        if (permissionsState.grantInstallPermission(bp) !=
8474                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8475                            changedInstallPermission = true;
8476                        }
8477                    } break;
8478
8479                    case GRANT_INSTALL_LEGACY: {
8480                        // Grant an install permission.
8481                        if (permissionsState.grantInstallPermission(bp) !=
8482                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8483                            changedInstallPermission = true;
8484                        }
8485                    } break;
8486
8487                    case GRANT_RUNTIME: {
8488                        // Grant previously granted runtime permissions.
8489                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8490                            PermissionState permissionState = origPermissions
8491                                    .getRuntimePermissionState(bp.name, userId);
8492                            final int flags = permissionState != null
8493                                    ? permissionState.getFlags() : 0;
8494                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8495                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8496                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8497                                    // If we cannot put the permission as it was, we have to write.
8498                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8499                                            changedRuntimePermissionUserIds, userId);
8500                                }
8501                            }
8502                            // Propagate the permission flags.
8503                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8504                        }
8505                    } break;
8506
8507                    case GRANT_UPGRADE: {
8508                        // Grant runtime permissions for a previously held install permission.
8509                        PermissionState permissionState = origPermissions
8510                                .getInstallPermissionState(bp.name);
8511                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8512
8513                        if (origPermissions.revokeInstallPermission(bp)
8514                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8515                            // We will be transferring the permission flags, so clear them.
8516                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8517                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8518                            changedInstallPermission = true;
8519                        }
8520
8521                        // If the permission is not to be promoted to runtime we ignore it and
8522                        // also its other flags as they are not applicable to install permissions.
8523                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8524                            for (int userId : currentUserIds) {
8525                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8526                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8527                                    // Transfer the permission flags.
8528                                    permissionsState.updatePermissionFlags(bp, userId,
8529                                            flags, flags);
8530                                    // If we granted the permission, we have to write.
8531                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8532                                            changedRuntimePermissionUserIds, userId);
8533                                }
8534                            }
8535                        }
8536                    } break;
8537
8538                    default: {
8539                        if (packageOfInterest == null
8540                                || packageOfInterest.equals(pkg.packageName)) {
8541                            Slog.w(TAG, "Not granting permission " + perm
8542                                    + " to package " + pkg.packageName
8543                                    + " because it was previously installed without");
8544                        }
8545                    } break;
8546                }
8547            } else {
8548                if (permissionsState.revokeInstallPermission(bp) !=
8549                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8550                    // Also drop the permission flags.
8551                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8552                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8553                    changedInstallPermission = true;
8554                    Slog.i(TAG, "Un-granting permission " + perm
8555                            + " from package " + pkg.packageName
8556                            + " (protectionLevel=" + bp.protectionLevel
8557                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8558                            + ")");
8559                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8560                    // Don't print warning for app op permissions, since it is fine for them
8561                    // not to be granted, there is a UI for the user to decide.
8562                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8563                        Slog.w(TAG, "Not granting permission " + perm
8564                                + " to package " + pkg.packageName
8565                                + " (protectionLevel=" + bp.protectionLevel
8566                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8567                                + ")");
8568                    }
8569                }
8570            }
8571        }
8572
8573        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8574                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8575            // This is the first that we have heard about this package, so the
8576            // permissions we have now selected are fixed until explicitly
8577            // changed.
8578            ps.installPermissionsFixed = true;
8579        }
8580
8581        // Persist the runtime permissions state for users with changes.
8582        for (int userId : changedRuntimePermissionUserIds) {
8583            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8584        }
8585    }
8586
8587    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8588        boolean allowed = false;
8589        final int NP = PackageParser.NEW_PERMISSIONS.length;
8590        for (int ip=0; ip<NP; ip++) {
8591            final PackageParser.NewPermissionInfo npi
8592                    = PackageParser.NEW_PERMISSIONS[ip];
8593            if (npi.name.equals(perm)
8594                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8595                allowed = true;
8596                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8597                        + pkg.packageName);
8598                break;
8599            }
8600        }
8601        return allowed;
8602    }
8603
8604    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8605            BasePermission bp, PermissionsState origPermissions) {
8606        boolean allowed;
8607        allowed = (compareSignatures(
8608                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8609                        == PackageManager.SIGNATURE_MATCH)
8610                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8611                        == PackageManager.SIGNATURE_MATCH);
8612        if (!allowed && (bp.protectionLevel
8613                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8614            if (isSystemApp(pkg)) {
8615                // For updated system applications, a system permission
8616                // is granted only if it had been defined by the original application.
8617                if (pkg.isUpdatedSystemApp()) {
8618                    final PackageSetting sysPs = mSettings
8619                            .getDisabledSystemPkgLPr(pkg.packageName);
8620                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8621                        // If the original was granted this permission, we take
8622                        // that grant decision as read and propagate it to the
8623                        // update.
8624                        if (sysPs.isPrivileged()) {
8625                            allowed = true;
8626                        }
8627                    } else {
8628                        // The system apk may have been updated with an older
8629                        // version of the one on the data partition, but which
8630                        // granted a new system permission that it didn't have
8631                        // before.  In this case we do want to allow the app to
8632                        // now get the new permission if the ancestral apk is
8633                        // privileged to get it.
8634                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8635                            for (int j=0;
8636                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8637                                if (perm.equals(
8638                                        sysPs.pkg.requestedPermissions.get(j))) {
8639                                    allowed = true;
8640                                    break;
8641                                }
8642                            }
8643                        }
8644                    }
8645                } else {
8646                    allowed = isPrivilegedApp(pkg);
8647                }
8648            }
8649        }
8650        if (!allowed) {
8651            if (!allowed && (bp.protectionLevel
8652                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8653                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8654                // If this was a previously normal/dangerous permission that got moved
8655                // to a system permission as part of the runtime permission redesign, then
8656                // we still want to blindly grant it to old apps.
8657                allowed = true;
8658            }
8659            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8660                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8661                // If this permission is to be granted to the system installer and
8662                // this app is an installer, then it gets the permission.
8663                allowed = true;
8664            }
8665            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8666                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8667                // If this permission is to be granted to the system verifier and
8668                // this app is a verifier, then it gets the permission.
8669                allowed = true;
8670            }
8671            if (!allowed && (bp.protectionLevel
8672                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8673                    && isSystemApp(pkg)) {
8674                // Any pre-installed system app is allowed to get this permission.
8675                allowed = true;
8676            }
8677            if (!allowed && (bp.protectionLevel
8678                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8679                // For development permissions, a development permission
8680                // is granted only if it was already granted.
8681                allowed = origPermissions.hasInstallPermission(perm);
8682            }
8683        }
8684        return allowed;
8685    }
8686
8687    final class ActivityIntentResolver
8688            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8689        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8690                boolean defaultOnly, int userId) {
8691            if (!sUserManager.exists(userId)) return null;
8692            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8693            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8694        }
8695
8696        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8697                int userId) {
8698            if (!sUserManager.exists(userId)) return null;
8699            mFlags = flags;
8700            return super.queryIntent(intent, resolvedType,
8701                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8702        }
8703
8704        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8705                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8706            if (!sUserManager.exists(userId)) return null;
8707            if (packageActivities == null) {
8708                return null;
8709            }
8710            mFlags = flags;
8711            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8712            final int N = packageActivities.size();
8713            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8714                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8715
8716            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8717            for (int i = 0; i < N; ++i) {
8718                intentFilters = packageActivities.get(i).intents;
8719                if (intentFilters != null && intentFilters.size() > 0) {
8720                    PackageParser.ActivityIntentInfo[] array =
8721                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8722                    intentFilters.toArray(array);
8723                    listCut.add(array);
8724                }
8725            }
8726            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8727        }
8728
8729        public final void addActivity(PackageParser.Activity a, String type) {
8730            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8731            mActivities.put(a.getComponentName(), a);
8732            if (DEBUG_SHOW_INFO)
8733                Log.v(
8734                TAG, "  " + type + " " +
8735                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8736            if (DEBUG_SHOW_INFO)
8737                Log.v(TAG, "    Class=" + a.info.name);
8738            final int NI = a.intents.size();
8739            for (int j=0; j<NI; j++) {
8740                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8741                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8742                    intent.setPriority(0);
8743                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8744                            + a.className + " with priority > 0, forcing to 0");
8745                }
8746                if (DEBUG_SHOW_INFO) {
8747                    Log.v(TAG, "    IntentFilter:");
8748                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8749                }
8750                if (!intent.debugCheck()) {
8751                    Log.w(TAG, "==> For Activity " + a.info.name);
8752                }
8753                addFilter(intent);
8754            }
8755        }
8756
8757        public final void removeActivity(PackageParser.Activity a, String type) {
8758            mActivities.remove(a.getComponentName());
8759            if (DEBUG_SHOW_INFO) {
8760                Log.v(TAG, "  " + type + " "
8761                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8762                                : a.info.name) + ":");
8763                Log.v(TAG, "    Class=" + a.info.name);
8764            }
8765            final int NI = a.intents.size();
8766            for (int j=0; j<NI; j++) {
8767                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8768                if (DEBUG_SHOW_INFO) {
8769                    Log.v(TAG, "    IntentFilter:");
8770                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8771                }
8772                removeFilter(intent);
8773            }
8774        }
8775
8776        @Override
8777        protected boolean allowFilterResult(
8778                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8779            ActivityInfo filterAi = filter.activity.info;
8780            for (int i=dest.size()-1; i>=0; i--) {
8781                ActivityInfo destAi = dest.get(i).activityInfo;
8782                if (destAi.name == filterAi.name
8783                        && destAi.packageName == filterAi.packageName) {
8784                    return false;
8785                }
8786            }
8787            return true;
8788        }
8789
8790        @Override
8791        protected ActivityIntentInfo[] newArray(int size) {
8792            return new ActivityIntentInfo[size];
8793        }
8794
8795        @Override
8796        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8797            if (!sUserManager.exists(userId)) return true;
8798            PackageParser.Package p = filter.activity.owner;
8799            if (p != null) {
8800                PackageSetting ps = (PackageSetting)p.mExtras;
8801                if (ps != null) {
8802                    // System apps are never considered stopped for purposes of
8803                    // filtering, because there may be no way for the user to
8804                    // actually re-launch them.
8805                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8806                            && ps.getStopped(userId);
8807                }
8808            }
8809            return false;
8810        }
8811
8812        @Override
8813        protected boolean isPackageForFilter(String packageName,
8814                PackageParser.ActivityIntentInfo info) {
8815            return packageName.equals(info.activity.owner.packageName);
8816        }
8817
8818        @Override
8819        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8820                int match, int userId) {
8821            if (!sUserManager.exists(userId)) return null;
8822            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8823                return null;
8824            }
8825            final PackageParser.Activity activity = info.activity;
8826            if (mSafeMode && (activity.info.applicationInfo.flags
8827                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8828                return null;
8829            }
8830            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8831            if (ps == null) {
8832                return null;
8833            }
8834            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8835                    ps.readUserState(userId), userId);
8836            if (ai == null) {
8837                return null;
8838            }
8839            final ResolveInfo res = new ResolveInfo();
8840            res.activityInfo = ai;
8841            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8842                res.filter = info;
8843            }
8844            if (info != null) {
8845                res.handleAllWebDataURI = info.handleAllWebDataURI();
8846            }
8847            res.priority = info.getPriority();
8848            res.preferredOrder = activity.owner.mPreferredOrder;
8849            //System.out.println("Result: " + res.activityInfo.className +
8850            //                   " = " + res.priority);
8851            res.match = match;
8852            res.isDefault = info.hasDefault;
8853            res.labelRes = info.labelRes;
8854            res.nonLocalizedLabel = info.nonLocalizedLabel;
8855            if (userNeedsBadging(userId)) {
8856                res.noResourceId = true;
8857            } else {
8858                res.icon = info.icon;
8859            }
8860            res.iconResourceId = info.icon;
8861            res.system = res.activityInfo.applicationInfo.isSystemApp();
8862            return res;
8863        }
8864
8865        @Override
8866        protected void sortResults(List<ResolveInfo> results) {
8867            Collections.sort(results, mResolvePrioritySorter);
8868        }
8869
8870        @Override
8871        protected void dumpFilter(PrintWriter out, String prefix,
8872                PackageParser.ActivityIntentInfo filter) {
8873            out.print(prefix); out.print(
8874                    Integer.toHexString(System.identityHashCode(filter.activity)));
8875                    out.print(' ');
8876                    filter.activity.printComponentShortName(out);
8877                    out.print(" filter ");
8878                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8879        }
8880
8881        @Override
8882        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8883            return filter.activity;
8884        }
8885
8886        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8887            PackageParser.Activity activity = (PackageParser.Activity)label;
8888            out.print(prefix); out.print(
8889                    Integer.toHexString(System.identityHashCode(activity)));
8890                    out.print(' ');
8891                    activity.printComponentShortName(out);
8892            if (count > 1) {
8893                out.print(" ("); out.print(count); out.print(" filters)");
8894            }
8895            out.println();
8896        }
8897
8898//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8899//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8900//            final List<ResolveInfo> retList = Lists.newArrayList();
8901//            while (i.hasNext()) {
8902//                final ResolveInfo resolveInfo = i.next();
8903//                if (isEnabledLP(resolveInfo.activityInfo)) {
8904//                    retList.add(resolveInfo);
8905//                }
8906//            }
8907//            return retList;
8908//        }
8909
8910        // Keys are String (activity class name), values are Activity.
8911        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8912                = new ArrayMap<ComponentName, PackageParser.Activity>();
8913        private int mFlags;
8914    }
8915
8916    private final class ServiceIntentResolver
8917            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8918        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8919                boolean defaultOnly, int userId) {
8920            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8921            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8922        }
8923
8924        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8925                int userId) {
8926            if (!sUserManager.exists(userId)) return null;
8927            mFlags = flags;
8928            return super.queryIntent(intent, resolvedType,
8929                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8930        }
8931
8932        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8933                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8934            if (!sUserManager.exists(userId)) return null;
8935            if (packageServices == null) {
8936                return null;
8937            }
8938            mFlags = flags;
8939            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8940            final int N = packageServices.size();
8941            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8942                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8943
8944            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8945            for (int i = 0; i < N; ++i) {
8946                intentFilters = packageServices.get(i).intents;
8947                if (intentFilters != null && intentFilters.size() > 0) {
8948                    PackageParser.ServiceIntentInfo[] array =
8949                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8950                    intentFilters.toArray(array);
8951                    listCut.add(array);
8952                }
8953            }
8954            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8955        }
8956
8957        public final void addService(PackageParser.Service s) {
8958            mServices.put(s.getComponentName(), s);
8959            if (DEBUG_SHOW_INFO) {
8960                Log.v(TAG, "  "
8961                        + (s.info.nonLocalizedLabel != null
8962                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8963                Log.v(TAG, "    Class=" + s.info.name);
8964            }
8965            final int NI = s.intents.size();
8966            int j;
8967            for (j=0; j<NI; j++) {
8968                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8969                if (DEBUG_SHOW_INFO) {
8970                    Log.v(TAG, "    IntentFilter:");
8971                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8972                }
8973                if (!intent.debugCheck()) {
8974                    Log.w(TAG, "==> For Service " + s.info.name);
8975                }
8976                addFilter(intent);
8977            }
8978        }
8979
8980        public final void removeService(PackageParser.Service s) {
8981            mServices.remove(s.getComponentName());
8982            if (DEBUG_SHOW_INFO) {
8983                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8984                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8985                Log.v(TAG, "    Class=" + s.info.name);
8986            }
8987            final int NI = s.intents.size();
8988            int j;
8989            for (j=0; j<NI; j++) {
8990                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8991                if (DEBUG_SHOW_INFO) {
8992                    Log.v(TAG, "    IntentFilter:");
8993                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8994                }
8995                removeFilter(intent);
8996            }
8997        }
8998
8999        @Override
9000        protected boolean allowFilterResult(
9001                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9002            ServiceInfo filterSi = filter.service.info;
9003            for (int i=dest.size()-1; i>=0; i--) {
9004                ServiceInfo destAi = dest.get(i).serviceInfo;
9005                if (destAi.name == filterSi.name
9006                        && destAi.packageName == filterSi.packageName) {
9007                    return false;
9008                }
9009            }
9010            return true;
9011        }
9012
9013        @Override
9014        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9015            return new PackageParser.ServiceIntentInfo[size];
9016        }
9017
9018        @Override
9019        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9020            if (!sUserManager.exists(userId)) return true;
9021            PackageParser.Package p = filter.service.owner;
9022            if (p != null) {
9023                PackageSetting ps = (PackageSetting)p.mExtras;
9024                if (ps != null) {
9025                    // System apps are never considered stopped for purposes of
9026                    // filtering, because there may be no way for the user to
9027                    // actually re-launch them.
9028                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9029                            && ps.getStopped(userId);
9030                }
9031            }
9032            return false;
9033        }
9034
9035        @Override
9036        protected boolean isPackageForFilter(String packageName,
9037                PackageParser.ServiceIntentInfo info) {
9038            return packageName.equals(info.service.owner.packageName);
9039        }
9040
9041        @Override
9042        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9043                int match, int userId) {
9044            if (!sUserManager.exists(userId)) return null;
9045            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9046            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9047                return null;
9048            }
9049            final PackageParser.Service service = info.service;
9050            if (mSafeMode && (service.info.applicationInfo.flags
9051                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9052                return null;
9053            }
9054            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9055            if (ps == null) {
9056                return null;
9057            }
9058            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9059                    ps.readUserState(userId), userId);
9060            if (si == null) {
9061                return null;
9062            }
9063            final ResolveInfo res = new ResolveInfo();
9064            res.serviceInfo = si;
9065            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9066                res.filter = filter;
9067            }
9068            res.priority = info.getPriority();
9069            res.preferredOrder = service.owner.mPreferredOrder;
9070            res.match = match;
9071            res.isDefault = info.hasDefault;
9072            res.labelRes = info.labelRes;
9073            res.nonLocalizedLabel = info.nonLocalizedLabel;
9074            res.icon = info.icon;
9075            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9076            return res;
9077        }
9078
9079        @Override
9080        protected void sortResults(List<ResolveInfo> results) {
9081            Collections.sort(results, mResolvePrioritySorter);
9082        }
9083
9084        @Override
9085        protected void dumpFilter(PrintWriter out, String prefix,
9086                PackageParser.ServiceIntentInfo filter) {
9087            out.print(prefix); out.print(
9088                    Integer.toHexString(System.identityHashCode(filter.service)));
9089                    out.print(' ');
9090                    filter.service.printComponentShortName(out);
9091                    out.print(" filter ");
9092                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9093        }
9094
9095        @Override
9096        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9097            return filter.service;
9098        }
9099
9100        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9101            PackageParser.Service service = (PackageParser.Service)label;
9102            out.print(prefix); out.print(
9103                    Integer.toHexString(System.identityHashCode(service)));
9104                    out.print(' ');
9105                    service.printComponentShortName(out);
9106            if (count > 1) {
9107                out.print(" ("); out.print(count); out.print(" filters)");
9108            }
9109            out.println();
9110        }
9111
9112//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9113//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9114//            final List<ResolveInfo> retList = Lists.newArrayList();
9115//            while (i.hasNext()) {
9116//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9117//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9118//                    retList.add(resolveInfo);
9119//                }
9120//            }
9121//            return retList;
9122//        }
9123
9124        // Keys are String (activity class name), values are Activity.
9125        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9126                = new ArrayMap<ComponentName, PackageParser.Service>();
9127        private int mFlags;
9128    };
9129
9130    private final class ProviderIntentResolver
9131            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9132        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9133                boolean defaultOnly, int userId) {
9134            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9135            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9136        }
9137
9138        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9139                int userId) {
9140            if (!sUserManager.exists(userId))
9141                return null;
9142            mFlags = flags;
9143            return super.queryIntent(intent, resolvedType,
9144                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9145        }
9146
9147        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9148                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9149            if (!sUserManager.exists(userId))
9150                return null;
9151            if (packageProviders == null) {
9152                return null;
9153            }
9154            mFlags = flags;
9155            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9156            final int N = packageProviders.size();
9157            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9158                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9159
9160            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9161            for (int i = 0; i < N; ++i) {
9162                intentFilters = packageProviders.get(i).intents;
9163                if (intentFilters != null && intentFilters.size() > 0) {
9164                    PackageParser.ProviderIntentInfo[] array =
9165                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9166                    intentFilters.toArray(array);
9167                    listCut.add(array);
9168                }
9169            }
9170            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9171        }
9172
9173        public final void addProvider(PackageParser.Provider p) {
9174            if (mProviders.containsKey(p.getComponentName())) {
9175                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9176                return;
9177            }
9178
9179            mProviders.put(p.getComponentName(), p);
9180            if (DEBUG_SHOW_INFO) {
9181                Log.v(TAG, "  "
9182                        + (p.info.nonLocalizedLabel != null
9183                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9184                Log.v(TAG, "    Class=" + p.info.name);
9185            }
9186            final int NI = p.intents.size();
9187            int j;
9188            for (j = 0; j < NI; j++) {
9189                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9190                if (DEBUG_SHOW_INFO) {
9191                    Log.v(TAG, "    IntentFilter:");
9192                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9193                }
9194                if (!intent.debugCheck()) {
9195                    Log.w(TAG, "==> For Provider " + p.info.name);
9196                }
9197                addFilter(intent);
9198            }
9199        }
9200
9201        public final void removeProvider(PackageParser.Provider p) {
9202            mProviders.remove(p.getComponentName());
9203            if (DEBUG_SHOW_INFO) {
9204                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9205                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9206                Log.v(TAG, "    Class=" + p.info.name);
9207            }
9208            final int NI = p.intents.size();
9209            int j;
9210            for (j = 0; j < NI; j++) {
9211                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9212                if (DEBUG_SHOW_INFO) {
9213                    Log.v(TAG, "    IntentFilter:");
9214                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9215                }
9216                removeFilter(intent);
9217            }
9218        }
9219
9220        @Override
9221        protected boolean allowFilterResult(
9222                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9223            ProviderInfo filterPi = filter.provider.info;
9224            for (int i = dest.size() - 1; i >= 0; i--) {
9225                ProviderInfo destPi = dest.get(i).providerInfo;
9226                if (destPi.name == filterPi.name
9227                        && destPi.packageName == filterPi.packageName) {
9228                    return false;
9229                }
9230            }
9231            return true;
9232        }
9233
9234        @Override
9235        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9236            return new PackageParser.ProviderIntentInfo[size];
9237        }
9238
9239        @Override
9240        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9241            if (!sUserManager.exists(userId))
9242                return true;
9243            PackageParser.Package p = filter.provider.owner;
9244            if (p != null) {
9245                PackageSetting ps = (PackageSetting) p.mExtras;
9246                if (ps != null) {
9247                    // System apps are never considered stopped for purposes of
9248                    // filtering, because there may be no way for the user to
9249                    // actually re-launch them.
9250                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9251                            && ps.getStopped(userId);
9252                }
9253            }
9254            return false;
9255        }
9256
9257        @Override
9258        protected boolean isPackageForFilter(String packageName,
9259                PackageParser.ProviderIntentInfo info) {
9260            return packageName.equals(info.provider.owner.packageName);
9261        }
9262
9263        @Override
9264        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9265                int match, int userId) {
9266            if (!sUserManager.exists(userId))
9267                return null;
9268            final PackageParser.ProviderIntentInfo info = filter;
9269            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9270                return null;
9271            }
9272            final PackageParser.Provider provider = info.provider;
9273            if (mSafeMode && (provider.info.applicationInfo.flags
9274                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9275                return null;
9276            }
9277            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9278            if (ps == null) {
9279                return null;
9280            }
9281            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9282                    ps.readUserState(userId), userId);
9283            if (pi == null) {
9284                return null;
9285            }
9286            final ResolveInfo res = new ResolveInfo();
9287            res.providerInfo = pi;
9288            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9289                res.filter = filter;
9290            }
9291            res.priority = info.getPriority();
9292            res.preferredOrder = provider.owner.mPreferredOrder;
9293            res.match = match;
9294            res.isDefault = info.hasDefault;
9295            res.labelRes = info.labelRes;
9296            res.nonLocalizedLabel = info.nonLocalizedLabel;
9297            res.icon = info.icon;
9298            res.system = res.providerInfo.applicationInfo.isSystemApp();
9299            return res;
9300        }
9301
9302        @Override
9303        protected void sortResults(List<ResolveInfo> results) {
9304            Collections.sort(results, mResolvePrioritySorter);
9305        }
9306
9307        @Override
9308        protected void dumpFilter(PrintWriter out, String prefix,
9309                PackageParser.ProviderIntentInfo filter) {
9310            out.print(prefix);
9311            out.print(
9312                    Integer.toHexString(System.identityHashCode(filter.provider)));
9313            out.print(' ');
9314            filter.provider.printComponentShortName(out);
9315            out.print(" filter ");
9316            out.println(Integer.toHexString(System.identityHashCode(filter)));
9317        }
9318
9319        @Override
9320        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9321            return filter.provider;
9322        }
9323
9324        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9325            PackageParser.Provider provider = (PackageParser.Provider)label;
9326            out.print(prefix); out.print(
9327                    Integer.toHexString(System.identityHashCode(provider)));
9328                    out.print(' ');
9329                    provider.printComponentShortName(out);
9330            if (count > 1) {
9331                out.print(" ("); out.print(count); out.print(" filters)");
9332            }
9333            out.println();
9334        }
9335
9336        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9337                = new ArrayMap<ComponentName, PackageParser.Provider>();
9338        private int mFlags;
9339    };
9340
9341    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9342            new Comparator<ResolveInfo>() {
9343        public int compare(ResolveInfo r1, ResolveInfo r2) {
9344            int v1 = r1.priority;
9345            int v2 = r2.priority;
9346            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9347            if (v1 != v2) {
9348                return (v1 > v2) ? -1 : 1;
9349            }
9350            v1 = r1.preferredOrder;
9351            v2 = r2.preferredOrder;
9352            if (v1 != v2) {
9353                return (v1 > v2) ? -1 : 1;
9354            }
9355            if (r1.isDefault != r2.isDefault) {
9356                return r1.isDefault ? -1 : 1;
9357            }
9358            v1 = r1.match;
9359            v2 = r2.match;
9360            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9361            if (v1 != v2) {
9362                return (v1 > v2) ? -1 : 1;
9363            }
9364            if (r1.system != r2.system) {
9365                return r1.system ? -1 : 1;
9366            }
9367            return 0;
9368        }
9369    };
9370
9371    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9372            new Comparator<ProviderInfo>() {
9373        public int compare(ProviderInfo p1, ProviderInfo p2) {
9374            final int v1 = p1.initOrder;
9375            final int v2 = p2.initOrder;
9376            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9377        }
9378    };
9379
9380    final void sendPackageBroadcast(final String action, final String pkg,
9381            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9382            final int[] userIds) {
9383        mHandler.post(new Runnable() {
9384            @Override
9385            public void run() {
9386                try {
9387                    final IActivityManager am = ActivityManagerNative.getDefault();
9388                    if (am == null) return;
9389                    final int[] resolvedUserIds;
9390                    if (userIds == null) {
9391                        resolvedUserIds = am.getRunningUserIds();
9392                    } else {
9393                        resolvedUserIds = userIds;
9394                    }
9395                    for (int id : resolvedUserIds) {
9396                        final Intent intent = new Intent(action,
9397                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9398                        if (extras != null) {
9399                            intent.putExtras(extras);
9400                        }
9401                        if (targetPkg != null) {
9402                            intent.setPackage(targetPkg);
9403                        }
9404                        // Modify the UID when posting to other users
9405                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9406                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9407                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9408                            intent.putExtra(Intent.EXTRA_UID, uid);
9409                        }
9410                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9411                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9412                        if (DEBUG_BROADCASTS) {
9413                            RuntimeException here = new RuntimeException("here");
9414                            here.fillInStackTrace();
9415                            Slog.d(TAG, "Sending to user " + id + ": "
9416                                    + intent.toShortString(false, true, false, false)
9417                                    + " " + intent.getExtras(), here);
9418                        }
9419                        am.broadcastIntent(null, intent, null, finishedReceiver,
9420                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9421                                null, finishedReceiver != null, false, id);
9422                    }
9423                } catch (RemoteException ex) {
9424                }
9425            }
9426        });
9427    }
9428
9429    /**
9430     * Check if the external storage media is available. This is true if there
9431     * is a mounted external storage medium or if the external storage is
9432     * emulated.
9433     */
9434    private boolean isExternalMediaAvailable() {
9435        return mMediaMounted || Environment.isExternalStorageEmulated();
9436    }
9437
9438    @Override
9439    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9440        // writer
9441        synchronized (mPackages) {
9442            if (!isExternalMediaAvailable()) {
9443                // If the external storage is no longer mounted at this point,
9444                // the caller may not have been able to delete all of this
9445                // packages files and can not delete any more.  Bail.
9446                return null;
9447            }
9448            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9449            if (lastPackage != null) {
9450                pkgs.remove(lastPackage);
9451            }
9452            if (pkgs.size() > 0) {
9453                return pkgs.get(0);
9454            }
9455        }
9456        return null;
9457    }
9458
9459    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9460        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9461                userId, andCode ? 1 : 0, packageName);
9462        if (mSystemReady) {
9463            msg.sendToTarget();
9464        } else {
9465            if (mPostSystemReadyMessages == null) {
9466                mPostSystemReadyMessages = new ArrayList<>();
9467            }
9468            mPostSystemReadyMessages.add(msg);
9469        }
9470    }
9471
9472    void startCleaningPackages() {
9473        // reader
9474        synchronized (mPackages) {
9475            if (!isExternalMediaAvailable()) {
9476                return;
9477            }
9478            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9479                return;
9480            }
9481        }
9482        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9483        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9484        IActivityManager am = ActivityManagerNative.getDefault();
9485        if (am != null) {
9486            try {
9487                am.startService(null, intent, null, mContext.getOpPackageName(),
9488                        UserHandle.USER_OWNER);
9489            } catch (RemoteException e) {
9490            }
9491        }
9492    }
9493
9494    @Override
9495    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9496            int installFlags, String installerPackageName, VerificationParams verificationParams,
9497            String packageAbiOverride) {
9498        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9499                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9500    }
9501
9502    @Override
9503    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9504            int installFlags, String installerPackageName, VerificationParams verificationParams,
9505            String packageAbiOverride, int userId) {
9506        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9507
9508        final int callingUid = Binder.getCallingUid();
9509        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9510
9511        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9512            try {
9513                if (observer != null) {
9514                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9515                }
9516            } catch (RemoteException re) {
9517            }
9518            return;
9519        }
9520
9521        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9522            installFlags |= PackageManager.INSTALL_FROM_ADB;
9523
9524        } else {
9525            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9526            // about installerPackageName.
9527
9528            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9529            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9530        }
9531
9532        UserHandle user;
9533        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9534            user = UserHandle.ALL;
9535        } else {
9536            user = new UserHandle(userId);
9537        }
9538
9539        // Only system components can circumvent runtime permissions when installing.
9540        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9541                && mContext.checkCallingOrSelfPermission(Manifest.permission
9542                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9543            throw new SecurityException("You need the "
9544                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9545                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9546        }
9547
9548        verificationParams.setInstallerUid(callingUid);
9549
9550        final File originFile = new File(originPath);
9551        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9552
9553        final Message msg = mHandler.obtainMessage(INIT_COPY);
9554        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9555                null, verificationParams, user, packageAbiOverride, null);
9556        mHandler.sendMessage(msg);
9557    }
9558
9559    void installStage(String packageName, File stagedDir, String stagedCid,
9560            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9561            String installerPackageName, int installerUid, UserHandle user) {
9562        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9563                params.referrerUri, installerUid, null);
9564        verifParams.setInstallerUid(installerUid);
9565
9566        final OriginInfo origin;
9567        if (stagedDir != null) {
9568            origin = OriginInfo.fromStagedFile(stagedDir);
9569        } else {
9570            origin = OriginInfo.fromStagedContainer(stagedCid);
9571        }
9572
9573        final Message msg = mHandler.obtainMessage(INIT_COPY);
9574        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9575                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9576                params.grantedRuntimePermissions);
9577        mHandler.sendMessage(msg);
9578    }
9579
9580    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9581        Bundle extras = new Bundle(1);
9582        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9583
9584        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9585                packageName, extras, null, null, new int[] {userId});
9586        try {
9587            IActivityManager am = ActivityManagerNative.getDefault();
9588            final boolean isSystem =
9589                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9590            if (isSystem && am.isUserRunning(userId, false)) {
9591                // The just-installed/enabled app is bundled on the system, so presumed
9592                // to be able to run automatically without needing an explicit launch.
9593                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9594                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9595                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9596                        .setPackage(packageName);
9597                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9598                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9599            }
9600        } catch (RemoteException e) {
9601            // shouldn't happen
9602            Slog.w(TAG, "Unable to bootstrap installed package", e);
9603        }
9604    }
9605
9606    @Override
9607    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9608            int userId) {
9609        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9610        PackageSetting pkgSetting;
9611        final int uid = Binder.getCallingUid();
9612        enforceCrossUserPermission(uid, userId, true, true,
9613                "setApplicationHiddenSetting for user " + userId);
9614
9615        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9616            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9617            return false;
9618        }
9619
9620        long callingId = Binder.clearCallingIdentity();
9621        try {
9622            boolean sendAdded = false;
9623            boolean sendRemoved = false;
9624            // writer
9625            synchronized (mPackages) {
9626                pkgSetting = mSettings.mPackages.get(packageName);
9627                if (pkgSetting == null) {
9628                    return false;
9629                }
9630                if (pkgSetting.getHidden(userId) != hidden) {
9631                    pkgSetting.setHidden(hidden, userId);
9632                    mSettings.writePackageRestrictionsLPr(userId);
9633                    if (hidden) {
9634                        sendRemoved = true;
9635                    } else {
9636                        sendAdded = true;
9637                    }
9638                }
9639            }
9640            if (sendAdded) {
9641                sendPackageAddedForUser(packageName, pkgSetting, userId);
9642                return true;
9643            }
9644            if (sendRemoved) {
9645                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9646                        "hiding pkg");
9647                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9648                return true;
9649            }
9650        } finally {
9651            Binder.restoreCallingIdentity(callingId);
9652        }
9653        return false;
9654    }
9655
9656    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9657            int userId) {
9658        final PackageRemovedInfo info = new PackageRemovedInfo();
9659        info.removedPackage = packageName;
9660        info.removedUsers = new int[] {userId};
9661        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9662        info.sendBroadcast(false, false, false);
9663    }
9664
9665    /**
9666     * Returns true if application is not found or there was an error. Otherwise it returns
9667     * the hidden state of the package for the given user.
9668     */
9669    @Override
9670    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9671        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9672        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9673                false, "getApplicationHidden for user " + userId);
9674        PackageSetting pkgSetting;
9675        long callingId = Binder.clearCallingIdentity();
9676        try {
9677            // writer
9678            synchronized (mPackages) {
9679                pkgSetting = mSettings.mPackages.get(packageName);
9680                if (pkgSetting == null) {
9681                    return true;
9682                }
9683                return pkgSetting.getHidden(userId);
9684            }
9685        } finally {
9686            Binder.restoreCallingIdentity(callingId);
9687        }
9688    }
9689
9690    /**
9691     * @hide
9692     */
9693    @Override
9694    public int installExistingPackageAsUser(String packageName, int userId) {
9695        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9696                null);
9697        PackageSetting pkgSetting;
9698        final int uid = Binder.getCallingUid();
9699        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9700                + userId);
9701        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9702            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9703        }
9704
9705        long callingId = Binder.clearCallingIdentity();
9706        try {
9707            boolean sendAdded = false;
9708
9709            // writer
9710            synchronized (mPackages) {
9711                pkgSetting = mSettings.mPackages.get(packageName);
9712                if (pkgSetting == null) {
9713                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9714                }
9715                if (!pkgSetting.getInstalled(userId)) {
9716                    pkgSetting.setInstalled(true, userId);
9717                    pkgSetting.setHidden(false, userId);
9718                    mSettings.writePackageRestrictionsLPr(userId);
9719                    sendAdded = true;
9720                }
9721            }
9722
9723            if (sendAdded) {
9724                sendPackageAddedForUser(packageName, pkgSetting, userId);
9725            }
9726        } finally {
9727            Binder.restoreCallingIdentity(callingId);
9728        }
9729
9730        return PackageManager.INSTALL_SUCCEEDED;
9731    }
9732
9733    boolean isUserRestricted(int userId, String restrictionKey) {
9734        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9735        if (restrictions.getBoolean(restrictionKey, false)) {
9736            Log.w(TAG, "User is restricted: " + restrictionKey);
9737            return true;
9738        }
9739        return false;
9740    }
9741
9742    @Override
9743    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9744        mContext.enforceCallingOrSelfPermission(
9745                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9746                "Only package verification agents can verify applications");
9747
9748        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9749        final PackageVerificationResponse response = new PackageVerificationResponse(
9750                verificationCode, Binder.getCallingUid());
9751        msg.arg1 = id;
9752        msg.obj = response;
9753        mHandler.sendMessage(msg);
9754    }
9755
9756    @Override
9757    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9758            long millisecondsToDelay) {
9759        mContext.enforceCallingOrSelfPermission(
9760                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9761                "Only package verification agents can extend verification timeouts");
9762
9763        final PackageVerificationState state = mPendingVerification.get(id);
9764        final PackageVerificationResponse response = new PackageVerificationResponse(
9765                verificationCodeAtTimeout, Binder.getCallingUid());
9766
9767        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9768            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9769        }
9770        if (millisecondsToDelay < 0) {
9771            millisecondsToDelay = 0;
9772        }
9773        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9774                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9775            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9776        }
9777
9778        if ((state != null) && !state.timeoutExtended()) {
9779            state.extendTimeout();
9780
9781            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9782            msg.arg1 = id;
9783            msg.obj = response;
9784            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9785        }
9786    }
9787
9788    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9789            int verificationCode, UserHandle user) {
9790        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9791        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9792        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9793        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9794        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9795
9796        mContext.sendBroadcastAsUser(intent, user,
9797                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9798    }
9799
9800    private ComponentName matchComponentForVerifier(String packageName,
9801            List<ResolveInfo> receivers) {
9802        ActivityInfo targetReceiver = null;
9803
9804        final int NR = receivers.size();
9805        for (int i = 0; i < NR; i++) {
9806            final ResolveInfo info = receivers.get(i);
9807            if (info.activityInfo == null) {
9808                continue;
9809            }
9810
9811            if (packageName.equals(info.activityInfo.packageName)) {
9812                targetReceiver = info.activityInfo;
9813                break;
9814            }
9815        }
9816
9817        if (targetReceiver == null) {
9818            return null;
9819        }
9820
9821        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9822    }
9823
9824    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9825            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9826        if (pkgInfo.verifiers.length == 0) {
9827            return null;
9828        }
9829
9830        final int N = pkgInfo.verifiers.length;
9831        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9832        for (int i = 0; i < N; i++) {
9833            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9834
9835            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9836                    receivers);
9837            if (comp == null) {
9838                continue;
9839            }
9840
9841            final int verifierUid = getUidForVerifier(verifierInfo);
9842            if (verifierUid == -1) {
9843                continue;
9844            }
9845
9846            if (DEBUG_VERIFY) {
9847                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9848                        + " with the correct signature");
9849            }
9850            sufficientVerifiers.add(comp);
9851            verificationState.addSufficientVerifier(verifierUid);
9852        }
9853
9854        return sufficientVerifiers;
9855    }
9856
9857    private int getUidForVerifier(VerifierInfo verifierInfo) {
9858        synchronized (mPackages) {
9859            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9860            if (pkg == null) {
9861                return -1;
9862            } else if (pkg.mSignatures.length != 1) {
9863                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9864                        + " has more than one signature; ignoring");
9865                return -1;
9866            }
9867
9868            /*
9869             * If the public key of the package's signature does not match
9870             * our expected public key, then this is a different package and
9871             * we should skip.
9872             */
9873
9874            final byte[] expectedPublicKey;
9875            try {
9876                final Signature verifierSig = pkg.mSignatures[0];
9877                final PublicKey publicKey = verifierSig.getPublicKey();
9878                expectedPublicKey = publicKey.getEncoded();
9879            } catch (CertificateException e) {
9880                return -1;
9881            }
9882
9883            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9884
9885            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9886                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9887                        + " does not have the expected public key; ignoring");
9888                return -1;
9889            }
9890
9891            return pkg.applicationInfo.uid;
9892        }
9893    }
9894
9895    @Override
9896    public void finishPackageInstall(int token) {
9897        enforceSystemOrRoot("Only the system is allowed to finish installs");
9898
9899        if (DEBUG_INSTALL) {
9900            Slog.v(TAG, "BM finishing package install for " + token);
9901        }
9902
9903        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9904        mHandler.sendMessage(msg);
9905    }
9906
9907    /**
9908     * Get the verification agent timeout.
9909     *
9910     * @return verification timeout in milliseconds
9911     */
9912    private long getVerificationTimeout() {
9913        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9914                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9915                DEFAULT_VERIFICATION_TIMEOUT);
9916    }
9917
9918    /**
9919     * Get the default verification agent response code.
9920     *
9921     * @return default verification response code
9922     */
9923    private int getDefaultVerificationResponse() {
9924        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9925                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9926                DEFAULT_VERIFICATION_RESPONSE);
9927    }
9928
9929    /**
9930     * Check whether or not package verification has been enabled.
9931     *
9932     * @return true if verification should be performed
9933     */
9934    private boolean isVerificationEnabled(int userId, int installFlags) {
9935        if (!DEFAULT_VERIFY_ENABLE) {
9936            return false;
9937        }
9938
9939        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9940
9941        // Check if installing from ADB
9942        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9943            // Do not run verification in a test harness environment
9944            if (ActivityManager.isRunningInTestHarness()) {
9945                return false;
9946            }
9947            if (ensureVerifyAppsEnabled) {
9948                return true;
9949            }
9950            // Check if the developer does not want package verification for ADB installs
9951            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9952                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9953                return false;
9954            }
9955        }
9956
9957        if (ensureVerifyAppsEnabled) {
9958            return true;
9959        }
9960
9961        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9962                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9963    }
9964
9965    @Override
9966    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9967            throws RemoteException {
9968        mContext.enforceCallingOrSelfPermission(
9969                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9970                "Only intentfilter verification agents can verify applications");
9971
9972        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9973        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9974                Binder.getCallingUid(), verificationCode, failedDomains);
9975        msg.arg1 = id;
9976        msg.obj = response;
9977        mHandler.sendMessage(msg);
9978    }
9979
9980    @Override
9981    public int getIntentVerificationStatus(String packageName, int userId) {
9982        synchronized (mPackages) {
9983            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9984        }
9985    }
9986
9987    @Override
9988    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9989        mContext.enforceCallingOrSelfPermission(
9990                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9991
9992        boolean result = false;
9993        synchronized (mPackages) {
9994            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9995        }
9996        if (result) {
9997            scheduleWritePackageRestrictionsLocked(userId);
9998        }
9999        return result;
10000    }
10001
10002    @Override
10003    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10004        synchronized (mPackages) {
10005            return mSettings.getIntentFilterVerificationsLPr(packageName);
10006        }
10007    }
10008
10009    @Override
10010    public List<IntentFilter> getAllIntentFilters(String packageName) {
10011        if (TextUtils.isEmpty(packageName)) {
10012            return Collections.<IntentFilter>emptyList();
10013        }
10014        synchronized (mPackages) {
10015            PackageParser.Package pkg = mPackages.get(packageName);
10016            if (pkg == null || pkg.activities == null) {
10017                return Collections.<IntentFilter>emptyList();
10018            }
10019            final int count = pkg.activities.size();
10020            ArrayList<IntentFilter> result = new ArrayList<>();
10021            for (int n=0; n<count; n++) {
10022                PackageParser.Activity activity = pkg.activities.get(n);
10023                if (activity.intents != null || activity.intents.size() > 0) {
10024                    result.addAll(activity.intents);
10025                }
10026            }
10027            return result;
10028        }
10029    }
10030
10031    @Override
10032    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10033        mContext.enforceCallingOrSelfPermission(
10034                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10035
10036        synchronized (mPackages) {
10037            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10038            if (packageName != null) {
10039                result |= updateIntentVerificationStatus(packageName,
10040                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10041                        userId);
10042                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10043                        packageName, userId);
10044            }
10045            return result;
10046        }
10047    }
10048
10049    @Override
10050    public String getDefaultBrowserPackageName(int userId) {
10051        synchronized (mPackages) {
10052            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10053        }
10054    }
10055
10056    /**
10057     * Get the "allow unknown sources" setting.
10058     *
10059     * @return the current "allow unknown sources" setting
10060     */
10061    private int getUnknownSourcesSettings() {
10062        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10063                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10064                -1);
10065    }
10066
10067    @Override
10068    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10069        final int uid = Binder.getCallingUid();
10070        // writer
10071        synchronized (mPackages) {
10072            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10073            if (targetPackageSetting == null) {
10074                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10075            }
10076
10077            PackageSetting installerPackageSetting;
10078            if (installerPackageName != null) {
10079                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10080                if (installerPackageSetting == null) {
10081                    throw new IllegalArgumentException("Unknown installer package: "
10082                            + installerPackageName);
10083                }
10084            } else {
10085                installerPackageSetting = null;
10086            }
10087
10088            Signature[] callerSignature;
10089            Object obj = mSettings.getUserIdLPr(uid);
10090            if (obj != null) {
10091                if (obj instanceof SharedUserSetting) {
10092                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10093                } else if (obj instanceof PackageSetting) {
10094                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10095                } else {
10096                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10097                }
10098            } else {
10099                throw new SecurityException("Unknown calling uid " + uid);
10100            }
10101
10102            // Verify: can't set installerPackageName to a package that is
10103            // not signed with the same cert as the caller.
10104            if (installerPackageSetting != null) {
10105                if (compareSignatures(callerSignature,
10106                        installerPackageSetting.signatures.mSignatures)
10107                        != PackageManager.SIGNATURE_MATCH) {
10108                    throw new SecurityException(
10109                            "Caller does not have same cert as new installer package "
10110                            + installerPackageName);
10111                }
10112            }
10113
10114            // Verify: if target already has an installer package, it must
10115            // be signed with the same cert as the caller.
10116            if (targetPackageSetting.installerPackageName != null) {
10117                PackageSetting setting = mSettings.mPackages.get(
10118                        targetPackageSetting.installerPackageName);
10119                // If the currently set package isn't valid, then it's always
10120                // okay to change it.
10121                if (setting != null) {
10122                    if (compareSignatures(callerSignature,
10123                            setting.signatures.mSignatures)
10124                            != PackageManager.SIGNATURE_MATCH) {
10125                        throw new SecurityException(
10126                                "Caller does not have same cert as old installer package "
10127                                + targetPackageSetting.installerPackageName);
10128                    }
10129                }
10130            }
10131
10132            // Okay!
10133            targetPackageSetting.installerPackageName = installerPackageName;
10134            scheduleWriteSettingsLocked();
10135        }
10136    }
10137
10138    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10139        // Queue up an async operation since the package installation may take a little while.
10140        mHandler.post(new Runnable() {
10141            public void run() {
10142                mHandler.removeCallbacks(this);
10143                 // Result object to be returned
10144                PackageInstalledInfo res = new PackageInstalledInfo();
10145                res.returnCode = currentStatus;
10146                res.uid = -1;
10147                res.pkg = null;
10148                res.removedInfo = new PackageRemovedInfo();
10149                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10150                    args.doPreInstall(res.returnCode);
10151                    synchronized (mInstallLock) {
10152                        installPackageLI(args, res);
10153                    }
10154                    args.doPostInstall(res.returnCode, res.uid);
10155                }
10156
10157                // A restore should be performed at this point if (a) the install
10158                // succeeded, (b) the operation is not an update, and (c) the new
10159                // package has not opted out of backup participation.
10160                final boolean update = res.removedInfo.removedPackage != null;
10161                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10162                boolean doRestore = !update
10163                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10164
10165                // Set up the post-install work request bookkeeping.  This will be used
10166                // and cleaned up by the post-install event handling regardless of whether
10167                // there's a restore pass performed.  Token values are >= 1.
10168                int token;
10169                if (mNextInstallToken < 0) mNextInstallToken = 1;
10170                token = mNextInstallToken++;
10171
10172                PostInstallData data = new PostInstallData(args, res);
10173                mRunningInstalls.put(token, data);
10174                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10175
10176                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10177                    // Pass responsibility to the Backup Manager.  It will perform a
10178                    // restore if appropriate, then pass responsibility back to the
10179                    // Package Manager to run the post-install observer callbacks
10180                    // and broadcasts.
10181                    IBackupManager bm = IBackupManager.Stub.asInterface(
10182                            ServiceManager.getService(Context.BACKUP_SERVICE));
10183                    if (bm != null) {
10184                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10185                                + " to BM for possible restore");
10186                        try {
10187                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10188                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10189                            } else {
10190                                doRestore = false;
10191                            }
10192                        } catch (RemoteException e) {
10193                            // can't happen; the backup manager is local
10194                        } catch (Exception e) {
10195                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10196                            doRestore = false;
10197                        }
10198                    } else {
10199                        Slog.e(TAG, "Backup Manager not found!");
10200                        doRestore = false;
10201                    }
10202                }
10203
10204                if (!doRestore) {
10205                    // No restore possible, or the Backup Manager was mysteriously not
10206                    // available -- just fire the post-install work request directly.
10207                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10208                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10209                    mHandler.sendMessage(msg);
10210                }
10211            }
10212        });
10213    }
10214
10215    private abstract class HandlerParams {
10216        private static final int MAX_RETRIES = 4;
10217
10218        /**
10219         * Number of times startCopy() has been attempted and had a non-fatal
10220         * error.
10221         */
10222        private int mRetries = 0;
10223
10224        /** User handle for the user requesting the information or installation. */
10225        private final UserHandle mUser;
10226
10227        HandlerParams(UserHandle user) {
10228            mUser = user;
10229        }
10230
10231        UserHandle getUser() {
10232            return mUser;
10233        }
10234
10235        final boolean startCopy() {
10236            boolean res;
10237            try {
10238                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10239
10240                if (++mRetries > MAX_RETRIES) {
10241                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10242                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10243                    handleServiceError();
10244                    return false;
10245                } else {
10246                    handleStartCopy();
10247                    res = true;
10248                }
10249            } catch (RemoteException e) {
10250                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10251                mHandler.sendEmptyMessage(MCS_RECONNECT);
10252                res = false;
10253            }
10254            handleReturnCode();
10255            return res;
10256        }
10257
10258        final void serviceError() {
10259            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10260            handleServiceError();
10261            handleReturnCode();
10262        }
10263
10264        abstract void handleStartCopy() throws RemoteException;
10265        abstract void handleServiceError();
10266        abstract void handleReturnCode();
10267    }
10268
10269    class MeasureParams extends HandlerParams {
10270        private final PackageStats mStats;
10271        private boolean mSuccess;
10272
10273        private final IPackageStatsObserver mObserver;
10274
10275        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10276            super(new UserHandle(stats.userHandle));
10277            mObserver = observer;
10278            mStats = stats;
10279        }
10280
10281        @Override
10282        public String toString() {
10283            return "MeasureParams{"
10284                + Integer.toHexString(System.identityHashCode(this))
10285                + " " + mStats.packageName + "}";
10286        }
10287
10288        @Override
10289        void handleStartCopy() throws RemoteException {
10290            synchronized (mInstallLock) {
10291                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10292            }
10293
10294            if (mSuccess) {
10295                final boolean mounted;
10296                if (Environment.isExternalStorageEmulated()) {
10297                    mounted = true;
10298                } else {
10299                    final String status = Environment.getExternalStorageState();
10300                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10301                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10302                }
10303
10304                if (mounted) {
10305                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10306
10307                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10308                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10309
10310                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10311                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10312
10313                    // Always subtract cache size, since it's a subdirectory
10314                    mStats.externalDataSize -= mStats.externalCacheSize;
10315
10316                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10317                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10318
10319                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10320                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10321                }
10322            }
10323        }
10324
10325        @Override
10326        void handleReturnCode() {
10327            if (mObserver != null) {
10328                try {
10329                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10330                } catch (RemoteException e) {
10331                    Slog.i(TAG, "Observer no longer exists.");
10332                }
10333            }
10334        }
10335
10336        @Override
10337        void handleServiceError() {
10338            Slog.e(TAG, "Could not measure application " + mStats.packageName
10339                            + " external storage");
10340        }
10341    }
10342
10343    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10344            throws RemoteException {
10345        long result = 0;
10346        for (File path : paths) {
10347            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10348        }
10349        return result;
10350    }
10351
10352    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10353        for (File path : paths) {
10354            try {
10355                mcs.clearDirectory(path.getAbsolutePath());
10356            } catch (RemoteException e) {
10357            }
10358        }
10359    }
10360
10361    static class OriginInfo {
10362        /**
10363         * Location where install is coming from, before it has been
10364         * copied/renamed into place. This could be a single monolithic APK
10365         * file, or a cluster directory. This location may be untrusted.
10366         */
10367        final File file;
10368        final String cid;
10369
10370        /**
10371         * Flag indicating that {@link #file} or {@link #cid} has already been
10372         * staged, meaning downstream users don't need to defensively copy the
10373         * contents.
10374         */
10375        final boolean staged;
10376
10377        /**
10378         * Flag indicating that {@link #file} or {@link #cid} is an already
10379         * installed app that is being moved.
10380         */
10381        final boolean existing;
10382
10383        final String resolvedPath;
10384        final File resolvedFile;
10385
10386        static OriginInfo fromNothing() {
10387            return new OriginInfo(null, null, false, false);
10388        }
10389
10390        static OriginInfo fromUntrustedFile(File file) {
10391            return new OriginInfo(file, null, false, false);
10392        }
10393
10394        static OriginInfo fromExistingFile(File file) {
10395            return new OriginInfo(file, null, false, true);
10396        }
10397
10398        static OriginInfo fromStagedFile(File file) {
10399            return new OriginInfo(file, null, true, false);
10400        }
10401
10402        static OriginInfo fromStagedContainer(String cid) {
10403            return new OriginInfo(null, cid, true, false);
10404        }
10405
10406        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10407            this.file = file;
10408            this.cid = cid;
10409            this.staged = staged;
10410            this.existing = existing;
10411
10412            if (cid != null) {
10413                resolvedPath = PackageHelper.getSdDir(cid);
10414                resolvedFile = new File(resolvedPath);
10415            } else if (file != null) {
10416                resolvedPath = file.getAbsolutePath();
10417                resolvedFile = file;
10418            } else {
10419                resolvedPath = null;
10420                resolvedFile = null;
10421            }
10422        }
10423    }
10424
10425    class MoveInfo {
10426        final int moveId;
10427        final String fromUuid;
10428        final String toUuid;
10429        final String packageName;
10430        final String dataAppName;
10431        final int appId;
10432        final String seinfo;
10433
10434        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10435                String dataAppName, int appId, String seinfo) {
10436            this.moveId = moveId;
10437            this.fromUuid = fromUuid;
10438            this.toUuid = toUuid;
10439            this.packageName = packageName;
10440            this.dataAppName = dataAppName;
10441            this.appId = appId;
10442            this.seinfo = seinfo;
10443        }
10444    }
10445
10446    class InstallParams extends HandlerParams {
10447        final OriginInfo origin;
10448        final MoveInfo move;
10449        final IPackageInstallObserver2 observer;
10450        int installFlags;
10451        final String installerPackageName;
10452        final String volumeUuid;
10453        final VerificationParams verificationParams;
10454        private InstallArgs mArgs;
10455        private int mRet;
10456        final String packageAbiOverride;
10457        final String[] grantedRuntimePermissions;
10458
10459
10460        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10461                int installFlags, String installerPackageName, String volumeUuid,
10462                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10463                String[] grantedPermissions) {
10464            super(user);
10465            this.origin = origin;
10466            this.move = move;
10467            this.observer = observer;
10468            this.installFlags = installFlags;
10469            this.installerPackageName = installerPackageName;
10470            this.volumeUuid = volumeUuid;
10471            this.verificationParams = verificationParams;
10472            this.packageAbiOverride = packageAbiOverride;
10473            this.grantedRuntimePermissions = grantedPermissions;
10474        }
10475
10476        @Override
10477        public String toString() {
10478            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10479                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10480        }
10481
10482        public ManifestDigest getManifestDigest() {
10483            if (verificationParams == null) {
10484                return null;
10485            }
10486            return verificationParams.getManifestDigest();
10487        }
10488
10489        private int installLocationPolicy(PackageInfoLite pkgLite) {
10490            String packageName = pkgLite.packageName;
10491            int installLocation = pkgLite.installLocation;
10492            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10493            // reader
10494            synchronized (mPackages) {
10495                PackageParser.Package pkg = mPackages.get(packageName);
10496                if (pkg != null) {
10497                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10498                        // Check for downgrading.
10499                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10500                            try {
10501                                checkDowngrade(pkg, pkgLite);
10502                            } catch (PackageManagerException e) {
10503                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10504                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10505                            }
10506                        }
10507                        // Check for updated system application.
10508                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10509                            if (onSd) {
10510                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10511                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10512                            }
10513                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10514                        } else {
10515                            if (onSd) {
10516                                // Install flag overrides everything.
10517                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10518                            }
10519                            // If current upgrade specifies particular preference
10520                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10521                                // Application explicitly specified internal.
10522                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10523                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10524                                // App explictly prefers external. Let policy decide
10525                            } else {
10526                                // Prefer previous location
10527                                if (isExternal(pkg)) {
10528                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10529                                }
10530                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10531                            }
10532                        }
10533                    } else {
10534                        // Invalid install. Return error code
10535                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10536                    }
10537                }
10538            }
10539            // All the special cases have been taken care of.
10540            // Return result based on recommended install location.
10541            if (onSd) {
10542                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10543            }
10544            return pkgLite.recommendedInstallLocation;
10545        }
10546
10547        /*
10548         * Invoke remote method to get package information and install
10549         * location values. Override install location based on default
10550         * policy if needed and then create install arguments based
10551         * on the install location.
10552         */
10553        public void handleStartCopy() throws RemoteException {
10554            int ret = PackageManager.INSTALL_SUCCEEDED;
10555
10556            // If we're already staged, we've firmly committed to an install location
10557            if (origin.staged) {
10558                if (origin.file != null) {
10559                    installFlags |= PackageManager.INSTALL_INTERNAL;
10560                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10561                } else if (origin.cid != null) {
10562                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10563                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10564                } else {
10565                    throw new IllegalStateException("Invalid stage location");
10566                }
10567            }
10568
10569            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10570            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10571
10572            PackageInfoLite pkgLite = null;
10573
10574            if (onInt && onSd) {
10575                // Check if both bits are set.
10576                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10577                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10578            } else {
10579                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10580                        packageAbiOverride);
10581
10582                /*
10583                 * If we have too little free space, try to free cache
10584                 * before giving up.
10585                 */
10586                if (!origin.staged && pkgLite.recommendedInstallLocation
10587                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10588                    // TODO: focus freeing disk space on the target device
10589                    final StorageManager storage = StorageManager.from(mContext);
10590                    final long lowThreshold = storage.getStorageLowBytes(
10591                            Environment.getDataDirectory());
10592
10593                    final long sizeBytes = mContainerService.calculateInstalledSize(
10594                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10595
10596                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10597                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10598                                installFlags, packageAbiOverride);
10599                    }
10600
10601                    /*
10602                     * The cache free must have deleted the file we
10603                     * downloaded to install.
10604                     *
10605                     * TODO: fix the "freeCache" call to not delete
10606                     *       the file we care about.
10607                     */
10608                    if (pkgLite.recommendedInstallLocation
10609                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10610                        pkgLite.recommendedInstallLocation
10611                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10612                    }
10613                }
10614            }
10615
10616            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10617                int loc = pkgLite.recommendedInstallLocation;
10618                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10619                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10620                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10621                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10622                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10623                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10624                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10625                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10626                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10627                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10628                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10629                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10630                } else {
10631                    // Override with defaults if needed.
10632                    loc = installLocationPolicy(pkgLite);
10633                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10634                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10635                    } else if (!onSd && !onInt) {
10636                        // Override install location with flags
10637                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10638                            // Set the flag to install on external media.
10639                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10640                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10641                        } else {
10642                            // Make sure the flag for installing on external
10643                            // media is unset
10644                            installFlags |= PackageManager.INSTALL_INTERNAL;
10645                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10646                        }
10647                    }
10648                }
10649            }
10650
10651            final InstallArgs args = createInstallArgs(this);
10652            mArgs = args;
10653
10654            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10655                 /*
10656                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10657                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10658                 */
10659                int userIdentifier = getUser().getIdentifier();
10660                if (userIdentifier == UserHandle.USER_ALL
10661                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10662                    userIdentifier = UserHandle.USER_OWNER;
10663                }
10664
10665                /*
10666                 * Determine if we have any installed package verifiers. If we
10667                 * do, then we'll defer to them to verify the packages.
10668                 */
10669                final int requiredUid = mRequiredVerifierPackage == null ? -1
10670                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10671                if (!origin.existing && requiredUid != -1
10672                        && isVerificationEnabled(userIdentifier, installFlags)) {
10673                    final Intent verification = new Intent(
10674                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10675                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10676                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10677                            PACKAGE_MIME_TYPE);
10678                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10679
10680                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10681                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10682                            0 /* TODO: Which userId? */);
10683
10684                    if (DEBUG_VERIFY) {
10685                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10686                                + verification.toString() + " with " + pkgLite.verifiers.length
10687                                + " optional verifiers");
10688                    }
10689
10690                    final int verificationId = mPendingVerificationToken++;
10691
10692                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10693
10694                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10695                            installerPackageName);
10696
10697                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10698                            installFlags);
10699
10700                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10701                            pkgLite.packageName);
10702
10703                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10704                            pkgLite.versionCode);
10705
10706                    if (verificationParams != null) {
10707                        if (verificationParams.getVerificationURI() != null) {
10708                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10709                                 verificationParams.getVerificationURI());
10710                        }
10711                        if (verificationParams.getOriginatingURI() != null) {
10712                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10713                                  verificationParams.getOriginatingURI());
10714                        }
10715                        if (verificationParams.getReferrer() != null) {
10716                            verification.putExtra(Intent.EXTRA_REFERRER,
10717                                  verificationParams.getReferrer());
10718                        }
10719                        if (verificationParams.getOriginatingUid() >= 0) {
10720                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10721                                  verificationParams.getOriginatingUid());
10722                        }
10723                        if (verificationParams.getInstallerUid() >= 0) {
10724                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10725                                  verificationParams.getInstallerUid());
10726                        }
10727                    }
10728
10729                    final PackageVerificationState verificationState = new PackageVerificationState(
10730                            requiredUid, args);
10731
10732                    mPendingVerification.append(verificationId, verificationState);
10733
10734                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10735                            receivers, verificationState);
10736
10737                    // Apps installed for "all" users use the device owner to verify the app
10738                    UserHandle verifierUser = getUser();
10739                    if (verifierUser == UserHandle.ALL) {
10740                        verifierUser = UserHandle.OWNER;
10741                    }
10742
10743                    /*
10744                     * If any sufficient verifiers were listed in the package
10745                     * manifest, attempt to ask them.
10746                     */
10747                    if (sufficientVerifiers != null) {
10748                        final int N = sufficientVerifiers.size();
10749                        if (N == 0) {
10750                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10751                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10752                        } else {
10753                            for (int i = 0; i < N; i++) {
10754                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10755
10756                                final Intent sufficientIntent = new Intent(verification);
10757                                sufficientIntent.setComponent(verifierComponent);
10758                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10759                            }
10760                        }
10761                    }
10762
10763                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10764                            mRequiredVerifierPackage, receivers);
10765                    if (ret == PackageManager.INSTALL_SUCCEEDED
10766                            && mRequiredVerifierPackage != null) {
10767                        /*
10768                         * Send the intent to the required verification agent,
10769                         * but only start the verification timeout after the
10770                         * target BroadcastReceivers have run.
10771                         */
10772                        verification.setComponent(requiredVerifierComponent);
10773                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10774                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10775                                new BroadcastReceiver() {
10776                                    @Override
10777                                    public void onReceive(Context context, Intent intent) {
10778                                        final Message msg = mHandler
10779                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10780                                        msg.arg1 = verificationId;
10781                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10782                                    }
10783                                }, null, 0, null, null);
10784
10785                        /*
10786                         * We don't want the copy to proceed until verification
10787                         * succeeds, so null out this field.
10788                         */
10789                        mArgs = null;
10790                    }
10791                } else {
10792                    /*
10793                     * No package verification is enabled, so immediately start
10794                     * the remote call to initiate copy using temporary file.
10795                     */
10796                    ret = args.copyApk(mContainerService, true);
10797                }
10798            }
10799
10800            mRet = ret;
10801        }
10802
10803        @Override
10804        void handleReturnCode() {
10805            // If mArgs is null, then MCS couldn't be reached. When it
10806            // reconnects, it will try again to install. At that point, this
10807            // will succeed.
10808            if (mArgs != null) {
10809                processPendingInstall(mArgs, mRet);
10810            }
10811        }
10812
10813        @Override
10814        void handleServiceError() {
10815            mArgs = createInstallArgs(this);
10816            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10817        }
10818
10819        public boolean isForwardLocked() {
10820            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10821        }
10822    }
10823
10824    /**
10825     * Used during creation of InstallArgs
10826     *
10827     * @param installFlags package installation flags
10828     * @return true if should be installed on external storage
10829     */
10830    private static boolean installOnExternalAsec(int installFlags) {
10831        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10832            return false;
10833        }
10834        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10835            return true;
10836        }
10837        return false;
10838    }
10839
10840    /**
10841     * Used during creation of InstallArgs
10842     *
10843     * @param installFlags package installation flags
10844     * @return true if should be installed as forward locked
10845     */
10846    private static boolean installForwardLocked(int installFlags) {
10847        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10848    }
10849
10850    private InstallArgs createInstallArgs(InstallParams params) {
10851        if (params.move != null) {
10852            return new MoveInstallArgs(params);
10853        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10854            return new AsecInstallArgs(params);
10855        } else {
10856            return new FileInstallArgs(params);
10857        }
10858    }
10859
10860    /**
10861     * Create args that describe an existing installed package. Typically used
10862     * when cleaning up old installs, or used as a move source.
10863     */
10864    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10865            String resourcePath, String[] instructionSets) {
10866        final boolean isInAsec;
10867        if (installOnExternalAsec(installFlags)) {
10868            /* Apps on SD card are always in ASEC containers. */
10869            isInAsec = true;
10870        } else if (installForwardLocked(installFlags)
10871                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10872            /*
10873             * Forward-locked apps are only in ASEC containers if they're the
10874             * new style
10875             */
10876            isInAsec = true;
10877        } else {
10878            isInAsec = false;
10879        }
10880
10881        if (isInAsec) {
10882            return new AsecInstallArgs(codePath, instructionSets,
10883                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10884        } else {
10885            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10886        }
10887    }
10888
10889    static abstract class InstallArgs {
10890        /** @see InstallParams#origin */
10891        final OriginInfo origin;
10892        /** @see InstallParams#move */
10893        final MoveInfo move;
10894
10895        final IPackageInstallObserver2 observer;
10896        // Always refers to PackageManager flags only
10897        final int installFlags;
10898        final String installerPackageName;
10899        final String volumeUuid;
10900        final ManifestDigest manifestDigest;
10901        final UserHandle user;
10902        final String abiOverride;
10903        final String[] installGrantPermissions;
10904
10905        // The list of instruction sets supported by this app. This is currently
10906        // only used during the rmdex() phase to clean up resources. We can get rid of this
10907        // if we move dex files under the common app path.
10908        /* nullable */ String[] instructionSets;
10909
10910        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10911                int installFlags, String installerPackageName, String volumeUuid,
10912                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10913                String abiOverride, String[] installGrantPermissions) {
10914            this.origin = origin;
10915            this.move = move;
10916            this.installFlags = installFlags;
10917            this.observer = observer;
10918            this.installerPackageName = installerPackageName;
10919            this.volumeUuid = volumeUuid;
10920            this.manifestDigest = manifestDigest;
10921            this.user = user;
10922            this.instructionSets = instructionSets;
10923            this.abiOverride = abiOverride;
10924            this.installGrantPermissions = installGrantPermissions;
10925        }
10926
10927        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10928        abstract int doPreInstall(int status);
10929
10930        /**
10931         * Rename package into final resting place. All paths on the given
10932         * scanned package should be updated to reflect the rename.
10933         */
10934        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10935        abstract int doPostInstall(int status, int uid);
10936
10937        /** @see PackageSettingBase#codePathString */
10938        abstract String getCodePath();
10939        /** @see PackageSettingBase#resourcePathString */
10940        abstract String getResourcePath();
10941
10942        // Need installer lock especially for dex file removal.
10943        abstract void cleanUpResourcesLI();
10944        abstract boolean doPostDeleteLI(boolean delete);
10945
10946        /**
10947         * Called before the source arguments are copied. This is used mostly
10948         * for MoveParams when it needs to read the source file to put it in the
10949         * destination.
10950         */
10951        int doPreCopy() {
10952            return PackageManager.INSTALL_SUCCEEDED;
10953        }
10954
10955        /**
10956         * Called after the source arguments are copied. This is used mostly for
10957         * MoveParams when it needs to read the source file to put it in the
10958         * destination.
10959         *
10960         * @return
10961         */
10962        int doPostCopy(int uid) {
10963            return PackageManager.INSTALL_SUCCEEDED;
10964        }
10965
10966        protected boolean isFwdLocked() {
10967            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10968        }
10969
10970        protected boolean isExternalAsec() {
10971            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10972        }
10973
10974        UserHandle getUser() {
10975            return user;
10976        }
10977    }
10978
10979    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10980        if (!allCodePaths.isEmpty()) {
10981            if (instructionSets == null) {
10982                throw new IllegalStateException("instructionSet == null");
10983            }
10984            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10985            for (String codePath : allCodePaths) {
10986                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10987                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10988                    if (retCode < 0) {
10989                        Slog.w(TAG, "Couldn't remove dex file for package: "
10990                                + " at location " + codePath + ", retcode=" + retCode);
10991                        // we don't consider this to be a failure of the core package deletion
10992                    }
10993                }
10994            }
10995        }
10996    }
10997
10998    /**
10999     * Logic to handle installation of non-ASEC applications, including copying
11000     * and renaming logic.
11001     */
11002    class FileInstallArgs extends InstallArgs {
11003        private File codeFile;
11004        private File resourceFile;
11005
11006        // Example topology:
11007        // /data/app/com.example/base.apk
11008        // /data/app/com.example/split_foo.apk
11009        // /data/app/com.example/lib/arm/libfoo.so
11010        // /data/app/com.example/lib/arm64/libfoo.so
11011        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11012
11013        /** New install */
11014        FileInstallArgs(InstallParams params) {
11015            super(params.origin, params.move, params.observer, params.installFlags,
11016                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11017                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11018                    params.grantedRuntimePermissions);
11019            if (isFwdLocked()) {
11020                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11021            }
11022        }
11023
11024        /** Existing install */
11025        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11026            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11027                    null, null);
11028            this.codeFile = (codePath != null) ? new File(codePath) : null;
11029            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11030        }
11031
11032        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11033            if (origin.staged) {
11034                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11035                codeFile = origin.file;
11036                resourceFile = origin.file;
11037                return PackageManager.INSTALL_SUCCEEDED;
11038            }
11039
11040            try {
11041                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11042                codeFile = tempDir;
11043                resourceFile = tempDir;
11044            } catch (IOException e) {
11045                Slog.w(TAG, "Failed to create copy file: " + e);
11046                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11047            }
11048
11049            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11050                @Override
11051                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11052                    if (!FileUtils.isValidExtFilename(name)) {
11053                        throw new IllegalArgumentException("Invalid filename: " + name);
11054                    }
11055                    try {
11056                        final File file = new File(codeFile, name);
11057                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11058                                O_RDWR | O_CREAT, 0644);
11059                        Os.chmod(file.getAbsolutePath(), 0644);
11060                        return new ParcelFileDescriptor(fd);
11061                    } catch (ErrnoException e) {
11062                        throw new RemoteException("Failed to open: " + e.getMessage());
11063                    }
11064                }
11065            };
11066
11067            int ret = PackageManager.INSTALL_SUCCEEDED;
11068            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11069            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11070                Slog.e(TAG, "Failed to copy package");
11071                return ret;
11072            }
11073
11074            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11075            NativeLibraryHelper.Handle handle = null;
11076            try {
11077                handle = NativeLibraryHelper.Handle.create(codeFile);
11078                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11079                        abiOverride);
11080            } catch (IOException e) {
11081                Slog.e(TAG, "Copying native libraries failed", e);
11082                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11083            } finally {
11084                IoUtils.closeQuietly(handle);
11085            }
11086
11087            return ret;
11088        }
11089
11090        int doPreInstall(int status) {
11091            if (status != PackageManager.INSTALL_SUCCEEDED) {
11092                cleanUp();
11093            }
11094            return status;
11095        }
11096
11097        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11098            if (status != PackageManager.INSTALL_SUCCEEDED) {
11099                cleanUp();
11100                return false;
11101            }
11102
11103            final File targetDir = codeFile.getParentFile();
11104            final File beforeCodeFile = codeFile;
11105            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11106
11107            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11108            try {
11109                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11110            } catch (ErrnoException e) {
11111                Slog.w(TAG, "Failed to rename", e);
11112                return false;
11113            }
11114
11115            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11116                Slog.w(TAG, "Failed to restorecon");
11117                return false;
11118            }
11119
11120            // Reflect the rename internally
11121            codeFile = afterCodeFile;
11122            resourceFile = afterCodeFile;
11123
11124            // Reflect the rename in scanned details
11125            pkg.codePath = afterCodeFile.getAbsolutePath();
11126            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11127                    pkg.baseCodePath);
11128            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11129                    pkg.splitCodePaths);
11130
11131            // Reflect the rename in app info
11132            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11133            pkg.applicationInfo.setCodePath(pkg.codePath);
11134            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11135            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11136            pkg.applicationInfo.setResourcePath(pkg.codePath);
11137            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11138            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11139
11140            return true;
11141        }
11142
11143        int doPostInstall(int status, int uid) {
11144            if (status != PackageManager.INSTALL_SUCCEEDED) {
11145                cleanUp();
11146            }
11147            return status;
11148        }
11149
11150        @Override
11151        String getCodePath() {
11152            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11153        }
11154
11155        @Override
11156        String getResourcePath() {
11157            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11158        }
11159
11160        private boolean cleanUp() {
11161            if (codeFile == null || !codeFile.exists()) {
11162                return false;
11163            }
11164
11165            if (codeFile.isDirectory()) {
11166                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11167            } else {
11168                codeFile.delete();
11169            }
11170
11171            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11172                resourceFile.delete();
11173            }
11174
11175            return true;
11176        }
11177
11178        void cleanUpResourcesLI() {
11179            // Try enumerating all code paths before deleting
11180            List<String> allCodePaths = Collections.EMPTY_LIST;
11181            if (codeFile != null && codeFile.exists()) {
11182                try {
11183                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11184                    allCodePaths = pkg.getAllCodePaths();
11185                } catch (PackageParserException e) {
11186                    // Ignored; we tried our best
11187                }
11188            }
11189
11190            cleanUp();
11191            removeDexFiles(allCodePaths, instructionSets);
11192        }
11193
11194        boolean doPostDeleteLI(boolean delete) {
11195            // XXX err, shouldn't we respect the delete flag?
11196            cleanUpResourcesLI();
11197            return true;
11198        }
11199    }
11200
11201    private boolean isAsecExternal(String cid) {
11202        final String asecPath = PackageHelper.getSdFilesystem(cid);
11203        return !asecPath.startsWith(mAsecInternalPath);
11204    }
11205
11206    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11207            PackageManagerException {
11208        if (copyRet < 0) {
11209            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11210                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11211                throw new PackageManagerException(copyRet, message);
11212            }
11213        }
11214    }
11215
11216    /**
11217     * Extract the MountService "container ID" from the full code path of an
11218     * .apk.
11219     */
11220    static String cidFromCodePath(String fullCodePath) {
11221        int eidx = fullCodePath.lastIndexOf("/");
11222        String subStr1 = fullCodePath.substring(0, eidx);
11223        int sidx = subStr1.lastIndexOf("/");
11224        return subStr1.substring(sidx+1, eidx);
11225    }
11226
11227    /**
11228     * Logic to handle installation of ASEC applications, including copying and
11229     * renaming logic.
11230     */
11231    class AsecInstallArgs extends InstallArgs {
11232        static final String RES_FILE_NAME = "pkg.apk";
11233        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11234
11235        String cid;
11236        String packagePath;
11237        String resourcePath;
11238
11239        /** New install */
11240        AsecInstallArgs(InstallParams params) {
11241            super(params.origin, params.move, params.observer, params.installFlags,
11242                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11243                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11244                    params.grantedRuntimePermissions);
11245        }
11246
11247        /** Existing install */
11248        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11249                        boolean isExternal, boolean isForwardLocked) {
11250            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11251                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11252                    instructionSets, null, null);
11253            // Hackily pretend we're still looking at a full code path
11254            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11255                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11256            }
11257
11258            // Extract cid from fullCodePath
11259            int eidx = fullCodePath.lastIndexOf("/");
11260            String subStr1 = fullCodePath.substring(0, eidx);
11261            int sidx = subStr1.lastIndexOf("/");
11262            cid = subStr1.substring(sidx+1, eidx);
11263            setMountPath(subStr1);
11264        }
11265
11266        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11267            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11268                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11269                    instructionSets, null, null);
11270            this.cid = cid;
11271            setMountPath(PackageHelper.getSdDir(cid));
11272        }
11273
11274        void createCopyFile() {
11275            cid = mInstallerService.allocateExternalStageCidLegacy();
11276        }
11277
11278        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11279            if (origin.staged) {
11280                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11281                cid = origin.cid;
11282                setMountPath(PackageHelper.getSdDir(cid));
11283                return PackageManager.INSTALL_SUCCEEDED;
11284            }
11285
11286            if (temp) {
11287                createCopyFile();
11288            } else {
11289                /*
11290                 * Pre-emptively destroy the container since it's destroyed if
11291                 * copying fails due to it existing anyway.
11292                 */
11293                PackageHelper.destroySdDir(cid);
11294            }
11295
11296            final String newMountPath = imcs.copyPackageToContainer(
11297                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11298                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11299
11300            if (newMountPath != null) {
11301                setMountPath(newMountPath);
11302                return PackageManager.INSTALL_SUCCEEDED;
11303            } else {
11304                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11305            }
11306        }
11307
11308        @Override
11309        String getCodePath() {
11310            return packagePath;
11311        }
11312
11313        @Override
11314        String getResourcePath() {
11315            return resourcePath;
11316        }
11317
11318        int doPreInstall(int status) {
11319            if (status != PackageManager.INSTALL_SUCCEEDED) {
11320                // Destroy container
11321                PackageHelper.destroySdDir(cid);
11322            } else {
11323                boolean mounted = PackageHelper.isContainerMounted(cid);
11324                if (!mounted) {
11325                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11326                            Process.SYSTEM_UID);
11327                    if (newMountPath != null) {
11328                        setMountPath(newMountPath);
11329                    } else {
11330                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11331                    }
11332                }
11333            }
11334            return status;
11335        }
11336
11337        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11338            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11339            String newMountPath = null;
11340            if (PackageHelper.isContainerMounted(cid)) {
11341                // Unmount the container
11342                if (!PackageHelper.unMountSdDir(cid)) {
11343                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11344                    return false;
11345                }
11346            }
11347            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11348                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11349                        " which might be stale. Will try to clean up.");
11350                // Clean up the stale container and proceed to recreate.
11351                if (!PackageHelper.destroySdDir(newCacheId)) {
11352                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11353                    return false;
11354                }
11355                // Successfully cleaned up stale container. Try to rename again.
11356                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11357                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11358                            + " inspite of cleaning it up.");
11359                    return false;
11360                }
11361            }
11362            if (!PackageHelper.isContainerMounted(newCacheId)) {
11363                Slog.w(TAG, "Mounting container " + newCacheId);
11364                newMountPath = PackageHelper.mountSdDir(newCacheId,
11365                        getEncryptKey(), Process.SYSTEM_UID);
11366            } else {
11367                newMountPath = PackageHelper.getSdDir(newCacheId);
11368            }
11369            if (newMountPath == null) {
11370                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11371                return false;
11372            }
11373            Log.i(TAG, "Succesfully renamed " + cid +
11374                    " to " + newCacheId +
11375                    " at new path: " + newMountPath);
11376            cid = newCacheId;
11377
11378            final File beforeCodeFile = new File(packagePath);
11379            setMountPath(newMountPath);
11380            final File afterCodeFile = new File(packagePath);
11381
11382            // Reflect the rename in scanned details
11383            pkg.codePath = afterCodeFile.getAbsolutePath();
11384            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11385                    pkg.baseCodePath);
11386            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11387                    pkg.splitCodePaths);
11388
11389            // Reflect the rename in app info
11390            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11391            pkg.applicationInfo.setCodePath(pkg.codePath);
11392            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11393            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11394            pkg.applicationInfo.setResourcePath(pkg.codePath);
11395            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11396            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11397
11398            return true;
11399        }
11400
11401        private void setMountPath(String mountPath) {
11402            final File mountFile = new File(mountPath);
11403
11404            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11405            if (monolithicFile.exists()) {
11406                packagePath = monolithicFile.getAbsolutePath();
11407                if (isFwdLocked()) {
11408                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11409                } else {
11410                    resourcePath = packagePath;
11411                }
11412            } else {
11413                packagePath = mountFile.getAbsolutePath();
11414                resourcePath = packagePath;
11415            }
11416        }
11417
11418        int doPostInstall(int status, int uid) {
11419            if (status != PackageManager.INSTALL_SUCCEEDED) {
11420                cleanUp();
11421            } else {
11422                final int groupOwner;
11423                final String protectedFile;
11424                if (isFwdLocked()) {
11425                    groupOwner = UserHandle.getSharedAppGid(uid);
11426                    protectedFile = RES_FILE_NAME;
11427                } else {
11428                    groupOwner = -1;
11429                    protectedFile = null;
11430                }
11431
11432                if (uid < Process.FIRST_APPLICATION_UID
11433                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11434                    Slog.e(TAG, "Failed to finalize " + cid);
11435                    PackageHelper.destroySdDir(cid);
11436                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11437                }
11438
11439                boolean mounted = PackageHelper.isContainerMounted(cid);
11440                if (!mounted) {
11441                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11442                }
11443            }
11444            return status;
11445        }
11446
11447        private void cleanUp() {
11448            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11449
11450            // Destroy secure container
11451            PackageHelper.destroySdDir(cid);
11452        }
11453
11454        private List<String> getAllCodePaths() {
11455            final File codeFile = new File(getCodePath());
11456            if (codeFile != null && codeFile.exists()) {
11457                try {
11458                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11459                    return pkg.getAllCodePaths();
11460                } catch (PackageParserException e) {
11461                    // Ignored; we tried our best
11462                }
11463            }
11464            return Collections.EMPTY_LIST;
11465        }
11466
11467        void cleanUpResourcesLI() {
11468            // Enumerate all code paths before deleting
11469            cleanUpResourcesLI(getAllCodePaths());
11470        }
11471
11472        private void cleanUpResourcesLI(List<String> allCodePaths) {
11473            cleanUp();
11474            removeDexFiles(allCodePaths, instructionSets);
11475        }
11476
11477        String getPackageName() {
11478            return getAsecPackageName(cid);
11479        }
11480
11481        boolean doPostDeleteLI(boolean delete) {
11482            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11483            final List<String> allCodePaths = getAllCodePaths();
11484            boolean mounted = PackageHelper.isContainerMounted(cid);
11485            if (mounted) {
11486                // Unmount first
11487                if (PackageHelper.unMountSdDir(cid)) {
11488                    mounted = false;
11489                }
11490            }
11491            if (!mounted && delete) {
11492                cleanUpResourcesLI(allCodePaths);
11493            }
11494            return !mounted;
11495        }
11496
11497        @Override
11498        int doPreCopy() {
11499            if (isFwdLocked()) {
11500                if (!PackageHelper.fixSdPermissions(cid,
11501                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11502                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11503                }
11504            }
11505
11506            return PackageManager.INSTALL_SUCCEEDED;
11507        }
11508
11509        @Override
11510        int doPostCopy(int uid) {
11511            if (isFwdLocked()) {
11512                if (uid < Process.FIRST_APPLICATION_UID
11513                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11514                                RES_FILE_NAME)) {
11515                    Slog.e(TAG, "Failed to finalize " + cid);
11516                    PackageHelper.destroySdDir(cid);
11517                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11518                }
11519            }
11520
11521            return PackageManager.INSTALL_SUCCEEDED;
11522        }
11523    }
11524
11525    /**
11526     * Logic to handle movement of existing installed applications.
11527     */
11528    class MoveInstallArgs extends InstallArgs {
11529        private File codeFile;
11530        private File resourceFile;
11531
11532        /** New install */
11533        MoveInstallArgs(InstallParams params) {
11534            super(params.origin, params.move, params.observer, params.installFlags,
11535                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11536                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11537                    params.grantedRuntimePermissions);
11538        }
11539
11540        int copyApk(IMediaContainerService imcs, boolean temp) {
11541            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11542                    + move.fromUuid + " to " + move.toUuid);
11543            synchronized (mInstaller) {
11544                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11545                        move.dataAppName, move.appId, move.seinfo) != 0) {
11546                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11547                }
11548            }
11549
11550            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11551            resourceFile = codeFile;
11552            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11553
11554            return PackageManager.INSTALL_SUCCEEDED;
11555        }
11556
11557        int doPreInstall(int status) {
11558            if (status != PackageManager.INSTALL_SUCCEEDED) {
11559                cleanUp(move.toUuid);
11560            }
11561            return status;
11562        }
11563
11564        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11565            if (status != PackageManager.INSTALL_SUCCEEDED) {
11566                cleanUp(move.toUuid);
11567                return false;
11568            }
11569
11570            // Reflect the move in app info
11571            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11572            pkg.applicationInfo.setCodePath(pkg.codePath);
11573            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11574            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11575            pkg.applicationInfo.setResourcePath(pkg.codePath);
11576            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11577            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11578
11579            return true;
11580        }
11581
11582        int doPostInstall(int status, int uid) {
11583            if (status == PackageManager.INSTALL_SUCCEEDED) {
11584                cleanUp(move.fromUuid);
11585            } else {
11586                cleanUp(move.toUuid);
11587            }
11588            return status;
11589        }
11590
11591        @Override
11592        String getCodePath() {
11593            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11594        }
11595
11596        @Override
11597        String getResourcePath() {
11598            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11599        }
11600
11601        private boolean cleanUp(String volumeUuid) {
11602            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11603                    move.dataAppName);
11604            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11605            synchronized (mInstallLock) {
11606                // Clean up both app data and code
11607                removeDataDirsLI(volumeUuid, move.packageName);
11608                if (codeFile.isDirectory()) {
11609                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11610                } else {
11611                    codeFile.delete();
11612                }
11613            }
11614            return true;
11615        }
11616
11617        void cleanUpResourcesLI() {
11618            throw new UnsupportedOperationException();
11619        }
11620
11621        boolean doPostDeleteLI(boolean delete) {
11622            throw new UnsupportedOperationException();
11623        }
11624    }
11625
11626    static String getAsecPackageName(String packageCid) {
11627        int idx = packageCid.lastIndexOf("-");
11628        if (idx == -1) {
11629            return packageCid;
11630        }
11631        return packageCid.substring(0, idx);
11632    }
11633
11634    // Utility method used to create code paths based on package name and available index.
11635    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11636        String idxStr = "";
11637        int idx = 1;
11638        // Fall back to default value of idx=1 if prefix is not
11639        // part of oldCodePath
11640        if (oldCodePath != null) {
11641            String subStr = oldCodePath;
11642            // Drop the suffix right away
11643            if (suffix != null && subStr.endsWith(suffix)) {
11644                subStr = subStr.substring(0, subStr.length() - suffix.length());
11645            }
11646            // If oldCodePath already contains prefix find out the
11647            // ending index to either increment or decrement.
11648            int sidx = subStr.lastIndexOf(prefix);
11649            if (sidx != -1) {
11650                subStr = subStr.substring(sidx + prefix.length());
11651                if (subStr != null) {
11652                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11653                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11654                    }
11655                    try {
11656                        idx = Integer.parseInt(subStr);
11657                        if (idx <= 1) {
11658                            idx++;
11659                        } else {
11660                            idx--;
11661                        }
11662                    } catch(NumberFormatException e) {
11663                    }
11664                }
11665            }
11666        }
11667        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11668        return prefix + idxStr;
11669    }
11670
11671    private File getNextCodePath(File targetDir, String packageName) {
11672        int suffix = 1;
11673        File result;
11674        do {
11675            result = new File(targetDir, packageName + "-" + suffix);
11676            suffix++;
11677        } while (result.exists());
11678        return result;
11679    }
11680
11681    // Utility method that returns the relative package path with respect
11682    // to the installation directory. Like say for /data/data/com.test-1.apk
11683    // string com.test-1 is returned.
11684    static String deriveCodePathName(String codePath) {
11685        if (codePath == null) {
11686            return null;
11687        }
11688        final File codeFile = new File(codePath);
11689        final String name = codeFile.getName();
11690        if (codeFile.isDirectory()) {
11691            return name;
11692        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11693            final int lastDot = name.lastIndexOf('.');
11694            return name.substring(0, lastDot);
11695        } else {
11696            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11697            return null;
11698        }
11699    }
11700
11701    class PackageInstalledInfo {
11702        String name;
11703        int uid;
11704        // The set of users that originally had this package installed.
11705        int[] origUsers;
11706        // The set of users that now have this package installed.
11707        int[] newUsers;
11708        PackageParser.Package pkg;
11709        int returnCode;
11710        String returnMsg;
11711        PackageRemovedInfo removedInfo;
11712
11713        public void setError(int code, String msg) {
11714            returnCode = code;
11715            returnMsg = msg;
11716            Slog.w(TAG, msg);
11717        }
11718
11719        public void setError(String msg, PackageParserException e) {
11720            returnCode = e.error;
11721            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11722            Slog.w(TAG, msg, e);
11723        }
11724
11725        public void setError(String msg, PackageManagerException e) {
11726            returnCode = e.error;
11727            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11728            Slog.w(TAG, msg, e);
11729        }
11730
11731        // In some error cases we want to convey more info back to the observer
11732        String origPackage;
11733        String origPermission;
11734    }
11735
11736    /*
11737     * Install a non-existing package.
11738     */
11739    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11740            UserHandle user, String installerPackageName, String volumeUuid,
11741            PackageInstalledInfo res) {
11742        // Remember this for later, in case we need to rollback this install
11743        String pkgName = pkg.packageName;
11744
11745        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11746        final boolean dataDirExists = Environment
11747                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11748        synchronized(mPackages) {
11749            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11750                // A package with the same name is already installed, though
11751                // it has been renamed to an older name.  The package we
11752                // are trying to install should be installed as an update to
11753                // the existing one, but that has not been requested, so bail.
11754                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11755                        + " without first uninstalling package running as "
11756                        + mSettings.mRenamedPackages.get(pkgName));
11757                return;
11758            }
11759            if (mPackages.containsKey(pkgName)) {
11760                // Don't allow installation over an existing package with the same name.
11761                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11762                        + " without first uninstalling.");
11763                return;
11764            }
11765        }
11766
11767        try {
11768            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11769                    System.currentTimeMillis(), user);
11770
11771            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11772            // delete the partially installed application. the data directory will have to be
11773            // restored if it was already existing
11774            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11775                // remove package from internal structures.  Note that we want deletePackageX to
11776                // delete the package data and cache directories that it created in
11777                // scanPackageLocked, unless those directories existed before we even tried to
11778                // install.
11779                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11780                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11781                                res.removedInfo, true);
11782            }
11783
11784        } catch (PackageManagerException e) {
11785            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11786        }
11787    }
11788
11789    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11790        // Can't rotate keys during boot or if sharedUser.
11791        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11792                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11793            return false;
11794        }
11795        // app is using upgradeKeySets; make sure all are valid
11796        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11797        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11798        for (int i = 0; i < upgradeKeySets.length; i++) {
11799            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11800                Slog.wtf(TAG, "Package "
11801                         + (oldPs.name != null ? oldPs.name : "<null>")
11802                         + " contains upgrade-key-set reference to unknown key-set: "
11803                         + upgradeKeySets[i]
11804                         + " reverting to signatures check.");
11805                return false;
11806            }
11807        }
11808        return true;
11809    }
11810
11811    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11812        // Upgrade keysets are being used.  Determine if new package has a superset of the
11813        // required keys.
11814        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11815        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11816        for (int i = 0; i < upgradeKeySets.length; i++) {
11817            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11818            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11819                return true;
11820            }
11821        }
11822        return false;
11823    }
11824
11825    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11826            UserHandle user, String installerPackageName, String volumeUuid,
11827            PackageInstalledInfo res) {
11828        final PackageParser.Package oldPackage;
11829        final String pkgName = pkg.packageName;
11830        final int[] allUsers;
11831        final boolean[] perUserInstalled;
11832
11833        // First find the old package info and check signatures
11834        synchronized(mPackages) {
11835            oldPackage = mPackages.get(pkgName);
11836            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11837            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11838            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11839                if(!checkUpgradeKeySetLP(ps, pkg)) {
11840                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11841                            "New package not signed by keys specified by upgrade-keysets: "
11842                            + pkgName);
11843                    return;
11844                }
11845            } else {
11846                // default to original signature matching
11847                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11848                    != PackageManager.SIGNATURE_MATCH) {
11849                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11850                            "New package has a different signature: " + pkgName);
11851                    return;
11852                }
11853            }
11854
11855            // In case of rollback, remember per-user/profile install state
11856            allUsers = sUserManager.getUserIds();
11857            perUserInstalled = new boolean[allUsers.length];
11858            for (int i = 0; i < allUsers.length; i++) {
11859                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11860            }
11861        }
11862
11863        boolean sysPkg = (isSystemApp(oldPackage));
11864        if (sysPkg) {
11865            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11866                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11867        } else {
11868            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11869                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11870        }
11871    }
11872
11873    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11874            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11875            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11876            String volumeUuid, PackageInstalledInfo res) {
11877        String pkgName = deletedPackage.packageName;
11878        boolean deletedPkg = true;
11879        boolean updatedSettings = false;
11880
11881        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11882                + deletedPackage);
11883        long origUpdateTime;
11884        if (pkg.mExtras != null) {
11885            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11886        } else {
11887            origUpdateTime = 0;
11888        }
11889
11890        // First delete the existing package while retaining the data directory
11891        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11892                res.removedInfo, true)) {
11893            // If the existing package wasn't successfully deleted
11894            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11895            deletedPkg = false;
11896        } else {
11897            // Successfully deleted the old package; proceed with replace.
11898
11899            // If deleted package lived in a container, give users a chance to
11900            // relinquish resources before killing.
11901            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11902                if (DEBUG_INSTALL) {
11903                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11904                }
11905                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11906                final ArrayList<String> pkgList = new ArrayList<String>(1);
11907                pkgList.add(deletedPackage.applicationInfo.packageName);
11908                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11909            }
11910
11911            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11912            try {
11913                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11914                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11915                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11916                        perUserInstalled, res, user);
11917                updatedSettings = true;
11918            } catch (PackageManagerException e) {
11919                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11920            }
11921        }
11922
11923        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11924            // remove package from internal structures.  Note that we want deletePackageX to
11925            // delete the package data and cache directories that it created in
11926            // scanPackageLocked, unless those directories existed before we even tried to
11927            // install.
11928            if(updatedSettings) {
11929                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11930                deletePackageLI(
11931                        pkgName, null, true, allUsers, perUserInstalled,
11932                        PackageManager.DELETE_KEEP_DATA,
11933                                res.removedInfo, true);
11934            }
11935            // Since we failed to install the new package we need to restore the old
11936            // package that we deleted.
11937            if (deletedPkg) {
11938                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11939                File restoreFile = new File(deletedPackage.codePath);
11940                // Parse old package
11941                boolean oldExternal = isExternal(deletedPackage);
11942                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11943                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11944                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11945                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11946                try {
11947                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11948                } catch (PackageManagerException e) {
11949                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11950                            + e.getMessage());
11951                    return;
11952                }
11953                // Restore of old package succeeded. Update permissions.
11954                // writer
11955                synchronized (mPackages) {
11956                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11957                            UPDATE_PERMISSIONS_ALL);
11958                    // can downgrade to reader
11959                    mSettings.writeLPr();
11960                }
11961                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11962            }
11963        }
11964    }
11965
11966    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11967            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11968            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11969            String volumeUuid, PackageInstalledInfo res) {
11970        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11971                + ", old=" + deletedPackage);
11972        boolean disabledSystem = false;
11973        boolean updatedSettings = false;
11974        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11975        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11976                != 0) {
11977            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11978        }
11979        String packageName = deletedPackage.packageName;
11980        if (packageName == null) {
11981            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11982                    "Attempt to delete null packageName.");
11983            return;
11984        }
11985        PackageParser.Package oldPkg;
11986        PackageSetting oldPkgSetting;
11987        // reader
11988        synchronized (mPackages) {
11989            oldPkg = mPackages.get(packageName);
11990            oldPkgSetting = mSettings.mPackages.get(packageName);
11991            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11992                    (oldPkgSetting == null)) {
11993                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11994                        "Couldn't find package:" + packageName + " information");
11995                return;
11996            }
11997        }
11998
11999        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12000
12001        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12002        res.removedInfo.removedPackage = packageName;
12003        // Remove existing system package
12004        removePackageLI(oldPkgSetting, true);
12005        // writer
12006        synchronized (mPackages) {
12007            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12008            if (!disabledSystem && deletedPackage != null) {
12009                // We didn't need to disable the .apk as a current system package,
12010                // which means we are replacing another update that is already
12011                // installed.  We need to make sure to delete the older one's .apk.
12012                res.removedInfo.args = createInstallArgsForExisting(0,
12013                        deletedPackage.applicationInfo.getCodePath(),
12014                        deletedPackage.applicationInfo.getResourcePath(),
12015                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12016            } else {
12017                res.removedInfo.args = null;
12018            }
12019        }
12020
12021        // Successfully disabled the old package. Now proceed with re-installation
12022        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12023
12024        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12025        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12026
12027        PackageParser.Package newPackage = null;
12028        try {
12029            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12030            if (newPackage.mExtras != null) {
12031                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12032                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12033                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12034
12035                // is the update attempting to change shared user? that isn't going to work...
12036                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12037                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12038                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12039                            + " to " + newPkgSetting.sharedUser);
12040                    updatedSettings = true;
12041                }
12042            }
12043
12044            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12045                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12046                        perUserInstalled, res, user);
12047                updatedSettings = true;
12048            }
12049
12050        } catch (PackageManagerException e) {
12051            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12052        }
12053
12054        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12055            // Re installation failed. Restore old information
12056            // Remove new pkg information
12057            if (newPackage != null) {
12058                removeInstalledPackageLI(newPackage, true);
12059            }
12060            // Add back the old system package
12061            try {
12062                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12063            } catch (PackageManagerException e) {
12064                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12065            }
12066            // Restore the old system information in Settings
12067            synchronized (mPackages) {
12068                if (disabledSystem) {
12069                    mSettings.enableSystemPackageLPw(packageName);
12070                }
12071                if (updatedSettings) {
12072                    mSettings.setInstallerPackageName(packageName,
12073                            oldPkgSetting.installerPackageName);
12074                }
12075                mSettings.writeLPr();
12076            }
12077        }
12078    }
12079
12080    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12081            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12082            UserHandle user) {
12083        String pkgName = newPackage.packageName;
12084        synchronized (mPackages) {
12085            //write settings. the installStatus will be incomplete at this stage.
12086            //note that the new package setting would have already been
12087            //added to mPackages. It hasn't been persisted yet.
12088            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12089            mSettings.writeLPr();
12090        }
12091
12092        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12093
12094        synchronized (mPackages) {
12095            updatePermissionsLPw(newPackage.packageName, newPackage,
12096                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12097                            ? UPDATE_PERMISSIONS_ALL : 0));
12098            // For system-bundled packages, we assume that installing an upgraded version
12099            // of the package implies that the user actually wants to run that new code,
12100            // so we enable the package.
12101            PackageSetting ps = mSettings.mPackages.get(pkgName);
12102            if (ps != null) {
12103                if (isSystemApp(newPackage)) {
12104                    // NB: implicit assumption that system package upgrades apply to all users
12105                    if (DEBUG_INSTALL) {
12106                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12107                    }
12108                    if (res.origUsers != null) {
12109                        for (int userHandle : res.origUsers) {
12110                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12111                                    userHandle, installerPackageName);
12112                        }
12113                    }
12114                    // Also convey the prior install/uninstall state
12115                    if (allUsers != null && perUserInstalled != null) {
12116                        for (int i = 0; i < allUsers.length; i++) {
12117                            if (DEBUG_INSTALL) {
12118                                Slog.d(TAG, "    user " + allUsers[i]
12119                                        + " => " + perUserInstalled[i]);
12120                            }
12121                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12122                        }
12123                        // these install state changes will be persisted in the
12124                        // upcoming call to mSettings.writeLPr().
12125                    }
12126                }
12127                // It's implied that when a user requests installation, they want the app to be
12128                // installed and enabled.
12129                int userId = user.getIdentifier();
12130                if (userId != UserHandle.USER_ALL) {
12131                    ps.setInstalled(true, userId);
12132                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12133                }
12134            }
12135            res.name = pkgName;
12136            res.uid = newPackage.applicationInfo.uid;
12137            res.pkg = newPackage;
12138            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12139            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12140            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12141            //to update install status
12142            mSettings.writeLPr();
12143        }
12144    }
12145
12146    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12147        final int installFlags = args.installFlags;
12148        final String installerPackageName = args.installerPackageName;
12149        final String volumeUuid = args.volumeUuid;
12150        final File tmpPackageFile = new File(args.getCodePath());
12151        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12152        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12153                || (args.volumeUuid != null));
12154        boolean replace = false;
12155        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12156        if (args.move != null) {
12157            // moving a complete application; perfom an initial scan on the new install location
12158            scanFlags |= SCAN_INITIAL;
12159        }
12160        // Result object to be returned
12161        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12162
12163        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12164        // Retrieve PackageSettings and parse package
12165        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12166                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12167                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12168        PackageParser pp = new PackageParser();
12169        pp.setSeparateProcesses(mSeparateProcesses);
12170        pp.setDisplayMetrics(mMetrics);
12171
12172        final PackageParser.Package pkg;
12173        try {
12174            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12175        } catch (PackageParserException e) {
12176            res.setError("Failed parse during installPackageLI", e);
12177            return;
12178        }
12179
12180        // Mark that we have an install time CPU ABI override.
12181        pkg.cpuAbiOverride = args.abiOverride;
12182
12183        String pkgName = res.name = pkg.packageName;
12184        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12185            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12186                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12187                return;
12188            }
12189        }
12190
12191        try {
12192            pp.collectCertificates(pkg, parseFlags);
12193            pp.collectManifestDigest(pkg);
12194        } catch (PackageParserException e) {
12195            res.setError("Failed collect during installPackageLI", e);
12196            return;
12197        }
12198
12199        /* If the installer passed in a manifest digest, compare it now. */
12200        if (args.manifestDigest != null) {
12201            if (DEBUG_INSTALL) {
12202                final String parsedManifest = pkg.manifestDigest == null ? "null"
12203                        : pkg.manifestDigest.toString();
12204                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12205                        + parsedManifest);
12206            }
12207
12208            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12209                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12210                return;
12211            }
12212        } else if (DEBUG_INSTALL) {
12213            final String parsedManifest = pkg.manifestDigest == null
12214                    ? "null" : pkg.manifestDigest.toString();
12215            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12216        }
12217
12218        // Get rid of all references to package scan path via parser.
12219        pp = null;
12220        String oldCodePath = null;
12221        boolean systemApp = false;
12222        synchronized (mPackages) {
12223            // Check if installing already existing package
12224            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12225                String oldName = mSettings.mRenamedPackages.get(pkgName);
12226                if (pkg.mOriginalPackages != null
12227                        && pkg.mOriginalPackages.contains(oldName)
12228                        && mPackages.containsKey(oldName)) {
12229                    // This package is derived from an original package,
12230                    // and this device has been updating from that original
12231                    // name.  We must continue using the original name, so
12232                    // rename the new package here.
12233                    pkg.setPackageName(oldName);
12234                    pkgName = pkg.packageName;
12235                    replace = true;
12236                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12237                            + oldName + " pkgName=" + pkgName);
12238                } else if (mPackages.containsKey(pkgName)) {
12239                    // This package, under its official name, already exists
12240                    // on the device; we should replace it.
12241                    replace = true;
12242                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12243                }
12244
12245                // Prevent apps opting out from runtime permissions
12246                if (replace) {
12247                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12248                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12249                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12250                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12251                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12252                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12253                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12254                                        + " doesn't support runtime permissions but the old"
12255                                        + " target SDK " + oldTargetSdk + " does.");
12256                        return;
12257                    }
12258                }
12259            }
12260
12261            PackageSetting ps = mSettings.mPackages.get(pkgName);
12262            if (ps != null) {
12263                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12264
12265                // Quick sanity check that we're signed correctly if updating;
12266                // we'll check this again later when scanning, but we want to
12267                // bail early here before tripping over redefined permissions.
12268                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12269                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12270                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12271                                + pkg.packageName + " upgrade keys do not match the "
12272                                + "previously installed version");
12273                        return;
12274                    }
12275                } else {
12276                    try {
12277                        verifySignaturesLP(ps, pkg);
12278                    } catch (PackageManagerException e) {
12279                        res.setError(e.error, e.getMessage());
12280                        return;
12281                    }
12282                }
12283
12284                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12285                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12286                    systemApp = (ps.pkg.applicationInfo.flags &
12287                            ApplicationInfo.FLAG_SYSTEM) != 0;
12288                }
12289                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12290            }
12291
12292            // Check whether the newly-scanned package wants to define an already-defined perm
12293            int N = pkg.permissions.size();
12294            for (int i = N-1; i >= 0; i--) {
12295                PackageParser.Permission perm = pkg.permissions.get(i);
12296                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12297                if (bp != null) {
12298                    // If the defining package is signed with our cert, it's okay.  This
12299                    // also includes the "updating the same package" case, of course.
12300                    // "updating same package" could also involve key-rotation.
12301                    final boolean sigsOk;
12302                    if (bp.sourcePackage.equals(pkg.packageName)
12303                            && (bp.packageSetting instanceof PackageSetting)
12304                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12305                                    scanFlags))) {
12306                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12307                    } else {
12308                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12309                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12310                    }
12311                    if (!sigsOk) {
12312                        // If the owning package is the system itself, we log but allow
12313                        // install to proceed; we fail the install on all other permission
12314                        // redefinitions.
12315                        if (!bp.sourcePackage.equals("android")) {
12316                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12317                                    + pkg.packageName + " attempting to redeclare permission "
12318                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12319                            res.origPermission = perm.info.name;
12320                            res.origPackage = bp.sourcePackage;
12321                            return;
12322                        } else {
12323                            Slog.w(TAG, "Package " + pkg.packageName
12324                                    + " attempting to redeclare system permission "
12325                                    + perm.info.name + "; ignoring new declaration");
12326                            pkg.permissions.remove(i);
12327                        }
12328                    }
12329                }
12330            }
12331
12332        }
12333
12334        if (systemApp && onExternal) {
12335            // Disable updates to system apps on sdcard
12336            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12337                    "Cannot install updates to system apps on sdcard");
12338            return;
12339        }
12340
12341        if (args.move != null) {
12342            // We did an in-place move, so dex is ready to roll
12343            scanFlags |= SCAN_NO_DEX;
12344            scanFlags |= SCAN_MOVE;
12345
12346            synchronized (mPackages) {
12347                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12348                if (ps == null) {
12349                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12350                            "Missing settings for moved package " + pkgName);
12351                }
12352
12353                // We moved the entire application as-is, so bring over the
12354                // previously derived ABI information.
12355                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12356                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12357            }
12358
12359        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12360            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12361            scanFlags |= SCAN_NO_DEX;
12362
12363            try {
12364                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12365                        true /* extract libs */);
12366            } catch (PackageManagerException pme) {
12367                Slog.e(TAG, "Error deriving application ABI", pme);
12368                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12369                return;
12370            }
12371
12372            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12373            int result = mPackageDexOptimizer
12374                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12375                            false /* defer */, false /* inclDependencies */);
12376            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12377                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12378                return;
12379            }
12380        }
12381
12382        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12383            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12384            return;
12385        }
12386
12387        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12388
12389        if (replace) {
12390            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12391                    installerPackageName, volumeUuid, res);
12392        } else {
12393            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12394                    args.user, installerPackageName, volumeUuid, res);
12395        }
12396        synchronized (mPackages) {
12397            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12398            if (ps != null) {
12399                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12400            }
12401        }
12402    }
12403
12404    private void startIntentFilterVerifications(int userId, boolean replacing,
12405            PackageParser.Package pkg) {
12406        if (mIntentFilterVerifierComponent == null) {
12407            Slog.w(TAG, "No IntentFilter verification will not be done as "
12408                    + "there is no IntentFilterVerifier available!");
12409            return;
12410        }
12411
12412        final int verifierUid = getPackageUid(
12413                mIntentFilterVerifierComponent.getPackageName(),
12414                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12415
12416        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12417        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12418        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12419        mHandler.sendMessage(msg);
12420    }
12421
12422    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12423            PackageParser.Package pkg) {
12424        int size = pkg.activities.size();
12425        if (size == 0) {
12426            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12427                    "No activity, so no need to verify any IntentFilter!");
12428            return;
12429        }
12430
12431        final boolean hasDomainURLs = hasDomainURLs(pkg);
12432        if (!hasDomainURLs) {
12433            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12434                    "No domain URLs, so no need to verify any IntentFilter!");
12435            return;
12436        }
12437
12438        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12439                + " if any IntentFilter from the " + size
12440                + " Activities needs verification ...");
12441
12442        int count = 0;
12443        final String packageName = pkg.packageName;
12444
12445        synchronized (mPackages) {
12446            // If this is a new install and we see that we've already run verification for this
12447            // package, we have nothing to do: it means the state was restored from backup.
12448            if (!replacing) {
12449                IntentFilterVerificationInfo ivi =
12450                        mSettings.getIntentFilterVerificationLPr(packageName);
12451                if (ivi != null) {
12452                    if (DEBUG_DOMAIN_VERIFICATION) {
12453                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12454                                + ivi.getStatusString());
12455                    }
12456                    return;
12457                }
12458            }
12459
12460            // If any filters need to be verified, then all need to be.
12461            boolean needToVerify = false;
12462            for (PackageParser.Activity a : pkg.activities) {
12463                for (ActivityIntentInfo filter : a.intents) {
12464                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12465                        if (DEBUG_DOMAIN_VERIFICATION) {
12466                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12467                        }
12468                        needToVerify = true;
12469                        break;
12470                    }
12471                }
12472            }
12473
12474            if (needToVerify) {
12475                final int verificationId = mIntentFilterVerificationToken++;
12476                for (PackageParser.Activity a : pkg.activities) {
12477                    for (ActivityIntentInfo filter : a.intents) {
12478                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12479                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12480                                    "Verification needed for IntentFilter:" + filter.toString());
12481                            mIntentFilterVerifier.addOneIntentFilterVerification(
12482                                    verifierUid, userId, verificationId, filter, packageName);
12483                            count++;
12484                        }
12485                    }
12486                }
12487            }
12488        }
12489
12490        if (count > 0) {
12491            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12492                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12493                    +  " for userId:" + userId);
12494            mIntentFilterVerifier.startVerifications(userId);
12495        } else {
12496            if (DEBUG_DOMAIN_VERIFICATION) {
12497                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12498            }
12499        }
12500    }
12501
12502    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12503        final ComponentName cn  = filter.activity.getComponentName();
12504        final String packageName = cn.getPackageName();
12505
12506        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12507                packageName);
12508        if (ivi == null) {
12509            return true;
12510        }
12511        int status = ivi.getStatus();
12512        switch (status) {
12513            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12514            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12515                return true;
12516
12517            default:
12518                // Nothing to do
12519                return false;
12520        }
12521    }
12522
12523    private static boolean isMultiArch(PackageSetting ps) {
12524        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12525    }
12526
12527    private static boolean isMultiArch(ApplicationInfo info) {
12528        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12529    }
12530
12531    private static boolean isExternal(PackageParser.Package pkg) {
12532        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12533    }
12534
12535    private static boolean isExternal(PackageSetting ps) {
12536        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12537    }
12538
12539    private static boolean isExternal(ApplicationInfo info) {
12540        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12541    }
12542
12543    private static boolean isSystemApp(PackageParser.Package pkg) {
12544        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12545    }
12546
12547    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12548        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12549    }
12550
12551    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12552        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12553    }
12554
12555    private static boolean isSystemApp(PackageSetting ps) {
12556        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12557    }
12558
12559    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12560        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12561    }
12562
12563    private int packageFlagsToInstallFlags(PackageSetting ps) {
12564        int installFlags = 0;
12565        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12566            // This existing package was an external ASEC install when we have
12567            // the external flag without a UUID
12568            installFlags |= PackageManager.INSTALL_EXTERNAL;
12569        }
12570        if (ps.isForwardLocked()) {
12571            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12572        }
12573        return installFlags;
12574    }
12575
12576    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12577        if (isExternal(pkg)) {
12578            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12579                return mSettings.getExternalVersion();
12580            } else {
12581                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12582            }
12583        } else {
12584            return mSettings.getInternalVersion();
12585        }
12586    }
12587
12588    private void deleteTempPackageFiles() {
12589        final FilenameFilter filter = new FilenameFilter() {
12590            public boolean accept(File dir, String name) {
12591                return name.startsWith("vmdl") && name.endsWith(".tmp");
12592            }
12593        };
12594        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12595            file.delete();
12596        }
12597    }
12598
12599    @Override
12600    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12601            int flags) {
12602        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12603                flags);
12604    }
12605
12606    @Override
12607    public void deletePackage(final String packageName,
12608            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12609        mContext.enforceCallingOrSelfPermission(
12610                android.Manifest.permission.DELETE_PACKAGES, null);
12611        Preconditions.checkNotNull(packageName);
12612        Preconditions.checkNotNull(observer);
12613        final int uid = Binder.getCallingUid();
12614        if (UserHandle.getUserId(uid) != userId) {
12615            mContext.enforceCallingPermission(
12616                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12617                    "deletePackage for user " + userId);
12618        }
12619        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12620            try {
12621                observer.onPackageDeleted(packageName,
12622                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12623            } catch (RemoteException re) {
12624            }
12625            return;
12626        }
12627
12628        boolean uninstallBlocked = false;
12629        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12630            int[] users = sUserManager.getUserIds();
12631            for (int i = 0; i < users.length; ++i) {
12632                if (getBlockUninstallForUser(packageName, users[i])) {
12633                    uninstallBlocked = true;
12634                    break;
12635                }
12636            }
12637        } else {
12638            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12639        }
12640        if (uninstallBlocked) {
12641            try {
12642                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12643                        null);
12644            } catch (RemoteException re) {
12645            }
12646            return;
12647        }
12648
12649        if (DEBUG_REMOVE) {
12650            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12651        }
12652        // Queue up an async operation since the package deletion may take a little while.
12653        mHandler.post(new Runnable() {
12654            public void run() {
12655                mHandler.removeCallbacks(this);
12656                final int returnCode = deletePackageX(packageName, userId, flags);
12657                if (observer != null) {
12658                    try {
12659                        observer.onPackageDeleted(packageName, returnCode, null);
12660                    } catch (RemoteException e) {
12661                        Log.i(TAG, "Observer no longer exists.");
12662                    } //end catch
12663                } //end if
12664            } //end run
12665        });
12666    }
12667
12668    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12669        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12670                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12671        try {
12672            if (dpm != null) {
12673                if (dpm.isDeviceOwner(packageName)) {
12674                    return true;
12675                }
12676                int[] users;
12677                if (userId == UserHandle.USER_ALL) {
12678                    users = sUserManager.getUserIds();
12679                } else {
12680                    users = new int[]{userId};
12681                }
12682                for (int i = 0; i < users.length; ++i) {
12683                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12684                        return true;
12685                    }
12686                }
12687            }
12688        } catch (RemoteException e) {
12689        }
12690        return false;
12691    }
12692
12693    /**
12694     *  This method is an internal method that could be get invoked either
12695     *  to delete an installed package or to clean up a failed installation.
12696     *  After deleting an installed package, a broadcast is sent to notify any
12697     *  listeners that the package has been installed. For cleaning up a failed
12698     *  installation, the broadcast is not necessary since the package's
12699     *  installation wouldn't have sent the initial broadcast either
12700     *  The key steps in deleting a package are
12701     *  deleting the package information in internal structures like mPackages,
12702     *  deleting the packages base directories through installd
12703     *  updating mSettings to reflect current status
12704     *  persisting settings for later use
12705     *  sending a broadcast if necessary
12706     */
12707    private int deletePackageX(String packageName, int userId, int flags) {
12708        final PackageRemovedInfo info = new PackageRemovedInfo();
12709        final boolean res;
12710
12711        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12712                ? UserHandle.ALL : new UserHandle(userId);
12713
12714        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12715            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12716            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12717        }
12718
12719        boolean removedForAllUsers = false;
12720        boolean systemUpdate = false;
12721
12722        // for the uninstall-updates case and restricted profiles, remember the per-
12723        // userhandle installed state
12724        int[] allUsers;
12725        boolean[] perUserInstalled;
12726        synchronized (mPackages) {
12727            PackageSetting ps = mSettings.mPackages.get(packageName);
12728            allUsers = sUserManager.getUserIds();
12729            perUserInstalled = new boolean[allUsers.length];
12730            for (int i = 0; i < allUsers.length; i++) {
12731                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12732            }
12733        }
12734
12735        synchronized (mInstallLock) {
12736            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12737            res = deletePackageLI(packageName, removeForUser,
12738                    true, allUsers, perUserInstalled,
12739                    flags | REMOVE_CHATTY, info, true);
12740            systemUpdate = info.isRemovedPackageSystemUpdate;
12741            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12742                removedForAllUsers = true;
12743            }
12744            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12745                    + " removedForAllUsers=" + removedForAllUsers);
12746        }
12747
12748        if (res) {
12749            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12750
12751            // If the removed package was a system update, the old system package
12752            // was re-enabled; we need to broadcast this information
12753            if (systemUpdate) {
12754                Bundle extras = new Bundle(1);
12755                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12756                        ? info.removedAppId : info.uid);
12757                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12758
12759                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12760                        extras, null, null, null);
12761                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12762                        extras, null, null, null);
12763                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12764                        null, packageName, null, null);
12765            }
12766        }
12767        // Force a gc here.
12768        Runtime.getRuntime().gc();
12769        // Delete the resources here after sending the broadcast to let
12770        // other processes clean up before deleting resources.
12771        if (info.args != null) {
12772            synchronized (mInstallLock) {
12773                info.args.doPostDeleteLI(true);
12774            }
12775        }
12776
12777        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12778    }
12779
12780    class PackageRemovedInfo {
12781        String removedPackage;
12782        int uid = -1;
12783        int removedAppId = -1;
12784        int[] removedUsers = null;
12785        boolean isRemovedPackageSystemUpdate = false;
12786        // Clean up resources deleted packages.
12787        InstallArgs args = null;
12788
12789        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12790            Bundle extras = new Bundle(1);
12791            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12792            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12793            if (replacing) {
12794                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12795            }
12796            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12797            if (removedPackage != null) {
12798                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12799                        extras, null, null, removedUsers);
12800                if (fullRemove && !replacing) {
12801                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12802                            extras, null, null, removedUsers);
12803                }
12804            }
12805            if (removedAppId >= 0) {
12806                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12807                        removedUsers);
12808            }
12809        }
12810    }
12811
12812    /*
12813     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12814     * flag is not set, the data directory is removed as well.
12815     * make sure this flag is set for partially installed apps. If not its meaningless to
12816     * delete a partially installed application.
12817     */
12818    private void removePackageDataLI(PackageSetting ps,
12819            int[] allUserHandles, boolean[] perUserInstalled,
12820            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12821        String packageName = ps.name;
12822        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12823        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12824        // Retrieve object to delete permissions for shared user later on
12825        final PackageSetting deletedPs;
12826        // reader
12827        synchronized (mPackages) {
12828            deletedPs = mSettings.mPackages.get(packageName);
12829            if (outInfo != null) {
12830                outInfo.removedPackage = packageName;
12831                outInfo.removedUsers = deletedPs != null
12832                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12833                        : null;
12834            }
12835        }
12836        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12837            removeDataDirsLI(ps.volumeUuid, packageName);
12838            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12839        }
12840        // writer
12841        synchronized (mPackages) {
12842            if (deletedPs != null) {
12843                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12844                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12845                    clearDefaultBrowserIfNeeded(packageName);
12846                    if (outInfo != null) {
12847                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12848                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12849                    }
12850                    updatePermissionsLPw(deletedPs.name, null, 0);
12851                    if (deletedPs.sharedUser != null) {
12852                        // Remove permissions associated with package. Since runtime
12853                        // permissions are per user we have to kill the removed package
12854                        // or packages running under the shared user of the removed
12855                        // package if revoking the permissions requested only by the removed
12856                        // package is successful and this causes a change in gids.
12857                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12858                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12859                                    userId);
12860                            if (userIdToKill == UserHandle.USER_ALL
12861                                    || userIdToKill >= UserHandle.USER_OWNER) {
12862                                // If gids changed for this user, kill all affected packages.
12863                                mHandler.post(new Runnable() {
12864                                    @Override
12865                                    public void run() {
12866                                        // This has to happen with no lock held.
12867                                        killApplication(deletedPs.name, deletedPs.appId,
12868                                                KILL_APP_REASON_GIDS_CHANGED);
12869                                    }
12870                                });
12871                                break;
12872                            }
12873                        }
12874                    }
12875                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12876                }
12877                // make sure to preserve per-user disabled state if this removal was just
12878                // a downgrade of a system app to the factory package
12879                if (allUserHandles != null && perUserInstalled != null) {
12880                    if (DEBUG_REMOVE) {
12881                        Slog.d(TAG, "Propagating install state across downgrade");
12882                    }
12883                    for (int i = 0; i < allUserHandles.length; i++) {
12884                        if (DEBUG_REMOVE) {
12885                            Slog.d(TAG, "    user " + allUserHandles[i]
12886                                    + " => " + perUserInstalled[i]);
12887                        }
12888                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12889                    }
12890                }
12891            }
12892            // can downgrade to reader
12893            if (writeSettings) {
12894                // Save settings now
12895                mSettings.writeLPr();
12896            }
12897        }
12898        if (outInfo != null) {
12899            // A user ID was deleted here. Go through all users and remove it
12900            // from KeyStore.
12901            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12902        }
12903    }
12904
12905    static boolean locationIsPrivileged(File path) {
12906        try {
12907            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12908                    .getCanonicalPath();
12909            return path.getCanonicalPath().startsWith(privilegedAppDir);
12910        } catch (IOException e) {
12911            Slog.e(TAG, "Unable to access code path " + path);
12912        }
12913        return false;
12914    }
12915
12916    /*
12917     * Tries to delete system package.
12918     */
12919    private boolean deleteSystemPackageLI(PackageSetting newPs,
12920            int[] allUserHandles, boolean[] perUserInstalled,
12921            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12922        final boolean applyUserRestrictions
12923                = (allUserHandles != null) && (perUserInstalled != null);
12924        PackageSetting disabledPs = null;
12925        // Confirm if the system package has been updated
12926        // An updated system app can be deleted. This will also have to restore
12927        // the system pkg from system partition
12928        // reader
12929        synchronized (mPackages) {
12930            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12931        }
12932        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12933                + " disabledPs=" + disabledPs);
12934        if (disabledPs == null) {
12935            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12936            return false;
12937        } else if (DEBUG_REMOVE) {
12938            Slog.d(TAG, "Deleting system pkg from data partition");
12939        }
12940        if (DEBUG_REMOVE) {
12941            if (applyUserRestrictions) {
12942                Slog.d(TAG, "Remembering install states:");
12943                for (int i = 0; i < allUserHandles.length; i++) {
12944                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12945                }
12946            }
12947        }
12948        // Delete the updated package
12949        outInfo.isRemovedPackageSystemUpdate = true;
12950        if (disabledPs.versionCode < newPs.versionCode) {
12951            // Delete data for downgrades
12952            flags &= ~PackageManager.DELETE_KEEP_DATA;
12953        } else {
12954            // Preserve data by setting flag
12955            flags |= PackageManager.DELETE_KEEP_DATA;
12956        }
12957        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12958                allUserHandles, perUserInstalled, outInfo, writeSettings);
12959        if (!ret) {
12960            return false;
12961        }
12962        // writer
12963        synchronized (mPackages) {
12964            // Reinstate the old system package
12965            mSettings.enableSystemPackageLPw(newPs.name);
12966            // Remove any native libraries from the upgraded package.
12967            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12968        }
12969        // Install the system package
12970        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12971        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12972        if (locationIsPrivileged(disabledPs.codePath)) {
12973            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12974        }
12975
12976        final PackageParser.Package newPkg;
12977        try {
12978            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12979        } catch (PackageManagerException e) {
12980            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12981            return false;
12982        }
12983
12984        // writer
12985        synchronized (mPackages) {
12986            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12987
12988            // Propagate the permissions state as we do not want to drop on the floor
12989            // runtime permissions. The update permissions method below will take
12990            // care of removing obsolete permissions and grant install permissions.
12991            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
12992            updatePermissionsLPw(newPkg.packageName, newPkg,
12993                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12994
12995            if (applyUserRestrictions) {
12996                if (DEBUG_REMOVE) {
12997                    Slog.d(TAG, "Propagating install state across reinstall");
12998                }
12999                for (int i = 0; i < allUserHandles.length; i++) {
13000                    if (DEBUG_REMOVE) {
13001                        Slog.d(TAG, "    user " + allUserHandles[i]
13002                                + " => " + perUserInstalled[i]);
13003                    }
13004                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13005
13006                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13007                }
13008                // Regardless of writeSettings we need to ensure that this restriction
13009                // state propagation is persisted
13010                mSettings.writeAllUsersPackageRestrictionsLPr();
13011            }
13012            // can downgrade to reader here
13013            if (writeSettings) {
13014                mSettings.writeLPr();
13015            }
13016        }
13017        return true;
13018    }
13019
13020    private boolean deleteInstalledPackageLI(PackageSetting ps,
13021            boolean deleteCodeAndResources, int flags,
13022            int[] allUserHandles, boolean[] perUserInstalled,
13023            PackageRemovedInfo outInfo, boolean writeSettings) {
13024        if (outInfo != null) {
13025            outInfo.uid = ps.appId;
13026        }
13027
13028        // Delete package data from internal structures and also remove data if flag is set
13029        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13030
13031        // Delete application code and resources
13032        if (deleteCodeAndResources && (outInfo != null)) {
13033            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13034                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13035            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13036        }
13037        return true;
13038    }
13039
13040    @Override
13041    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13042            int userId) {
13043        mContext.enforceCallingOrSelfPermission(
13044                android.Manifest.permission.DELETE_PACKAGES, null);
13045        synchronized (mPackages) {
13046            PackageSetting ps = mSettings.mPackages.get(packageName);
13047            if (ps == null) {
13048                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13049                return false;
13050            }
13051            if (!ps.getInstalled(userId)) {
13052                // Can't block uninstall for an app that is not installed or enabled.
13053                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13054                return false;
13055            }
13056            ps.setBlockUninstall(blockUninstall, userId);
13057            mSettings.writePackageRestrictionsLPr(userId);
13058        }
13059        return true;
13060    }
13061
13062    @Override
13063    public boolean getBlockUninstallForUser(String packageName, int userId) {
13064        synchronized (mPackages) {
13065            PackageSetting ps = mSettings.mPackages.get(packageName);
13066            if (ps == null) {
13067                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13068                return false;
13069            }
13070            return ps.getBlockUninstall(userId);
13071        }
13072    }
13073
13074    /*
13075     * This method handles package deletion in general
13076     */
13077    private boolean deletePackageLI(String packageName, UserHandle user,
13078            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13079            int flags, PackageRemovedInfo outInfo,
13080            boolean writeSettings) {
13081        if (packageName == null) {
13082            Slog.w(TAG, "Attempt to delete null packageName.");
13083            return false;
13084        }
13085        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13086        PackageSetting ps;
13087        boolean dataOnly = false;
13088        int removeUser = -1;
13089        int appId = -1;
13090        synchronized (mPackages) {
13091            ps = mSettings.mPackages.get(packageName);
13092            if (ps == null) {
13093                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13094                return false;
13095            }
13096            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13097                    && user.getIdentifier() != UserHandle.USER_ALL) {
13098                // The caller is asking that the package only be deleted for a single
13099                // user.  To do this, we just mark its uninstalled state and delete
13100                // its data.  If this is a system app, we only allow this to happen if
13101                // they have set the special DELETE_SYSTEM_APP which requests different
13102                // semantics than normal for uninstalling system apps.
13103                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13104                final int userId = user.getIdentifier();
13105                ps.setUserState(userId,
13106                        COMPONENT_ENABLED_STATE_DEFAULT,
13107                        false, //installed
13108                        true,  //stopped
13109                        true,  //notLaunched
13110                        false, //hidden
13111                        null, null, null,
13112                        false, // blockUninstall
13113                        ps.readUserState(userId).domainVerificationStatus, 0);
13114                if (!isSystemApp(ps)) {
13115                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13116                        // Other user still have this package installed, so all
13117                        // we need to do is clear this user's data and save that
13118                        // it is uninstalled.
13119                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13120                        removeUser = user.getIdentifier();
13121                        appId = ps.appId;
13122                        scheduleWritePackageRestrictionsLocked(removeUser);
13123                    } else {
13124                        // We need to set it back to 'installed' so the uninstall
13125                        // broadcasts will be sent correctly.
13126                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13127                        ps.setInstalled(true, user.getIdentifier());
13128                    }
13129                } else {
13130                    // This is a system app, so we assume that the
13131                    // other users still have this package installed, so all
13132                    // we need to do is clear this user's data and save that
13133                    // it is uninstalled.
13134                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13135                    removeUser = user.getIdentifier();
13136                    appId = ps.appId;
13137                    scheduleWritePackageRestrictionsLocked(removeUser);
13138                }
13139            }
13140        }
13141
13142        if (removeUser >= 0) {
13143            // From above, we determined that we are deleting this only
13144            // for a single user.  Continue the work here.
13145            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13146            if (outInfo != null) {
13147                outInfo.removedPackage = packageName;
13148                outInfo.removedAppId = appId;
13149                outInfo.removedUsers = new int[] {removeUser};
13150            }
13151            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13152            removeKeystoreDataIfNeeded(removeUser, appId);
13153            schedulePackageCleaning(packageName, removeUser, false);
13154            synchronized (mPackages) {
13155                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13156                    scheduleWritePackageRestrictionsLocked(removeUser);
13157                }
13158                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13159            }
13160            return true;
13161        }
13162
13163        if (dataOnly) {
13164            // Delete application data first
13165            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13166            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13167            return true;
13168        }
13169
13170        boolean ret = false;
13171        if (isSystemApp(ps)) {
13172            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13173            // When an updated system application is deleted we delete the existing resources as well and
13174            // fall back to existing code in system partition
13175            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13176                    flags, outInfo, writeSettings);
13177        } else {
13178            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13179            // Kill application pre-emptively especially for apps on sd.
13180            killApplication(packageName, ps.appId, "uninstall pkg");
13181            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13182                    allUserHandles, perUserInstalled,
13183                    outInfo, writeSettings);
13184        }
13185
13186        return ret;
13187    }
13188
13189    private final class ClearStorageConnection implements ServiceConnection {
13190        IMediaContainerService mContainerService;
13191
13192        @Override
13193        public void onServiceConnected(ComponentName name, IBinder service) {
13194            synchronized (this) {
13195                mContainerService = IMediaContainerService.Stub.asInterface(service);
13196                notifyAll();
13197            }
13198        }
13199
13200        @Override
13201        public void onServiceDisconnected(ComponentName name) {
13202        }
13203    }
13204
13205    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13206        final boolean mounted;
13207        if (Environment.isExternalStorageEmulated()) {
13208            mounted = true;
13209        } else {
13210            final String status = Environment.getExternalStorageState();
13211
13212            mounted = status.equals(Environment.MEDIA_MOUNTED)
13213                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13214        }
13215
13216        if (!mounted) {
13217            return;
13218        }
13219
13220        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13221        int[] users;
13222        if (userId == UserHandle.USER_ALL) {
13223            users = sUserManager.getUserIds();
13224        } else {
13225            users = new int[] { userId };
13226        }
13227        final ClearStorageConnection conn = new ClearStorageConnection();
13228        if (mContext.bindServiceAsUser(
13229                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13230            try {
13231                for (int curUser : users) {
13232                    long timeout = SystemClock.uptimeMillis() + 5000;
13233                    synchronized (conn) {
13234                        long now = SystemClock.uptimeMillis();
13235                        while (conn.mContainerService == null && now < timeout) {
13236                            try {
13237                                conn.wait(timeout - now);
13238                            } catch (InterruptedException e) {
13239                            }
13240                        }
13241                    }
13242                    if (conn.mContainerService == null) {
13243                        return;
13244                    }
13245
13246                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13247                    clearDirectory(conn.mContainerService,
13248                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13249                    if (allData) {
13250                        clearDirectory(conn.mContainerService,
13251                                userEnv.buildExternalStorageAppDataDirs(packageName));
13252                        clearDirectory(conn.mContainerService,
13253                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13254                    }
13255                }
13256            } finally {
13257                mContext.unbindService(conn);
13258            }
13259        }
13260    }
13261
13262    @Override
13263    public void clearApplicationUserData(final String packageName,
13264            final IPackageDataObserver observer, final int userId) {
13265        mContext.enforceCallingOrSelfPermission(
13266                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13267        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13268        // Queue up an async operation since the package deletion may take a little while.
13269        mHandler.post(new Runnable() {
13270            public void run() {
13271                mHandler.removeCallbacks(this);
13272                final boolean succeeded;
13273                synchronized (mInstallLock) {
13274                    succeeded = clearApplicationUserDataLI(packageName, userId);
13275                }
13276                clearExternalStorageDataSync(packageName, userId, true);
13277                if (succeeded) {
13278                    // invoke DeviceStorageMonitor's update method to clear any notifications
13279                    DeviceStorageMonitorInternal
13280                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13281                    if (dsm != null) {
13282                        dsm.checkMemory();
13283                    }
13284                }
13285                if(observer != null) {
13286                    try {
13287                        observer.onRemoveCompleted(packageName, succeeded);
13288                    } catch (RemoteException e) {
13289                        Log.i(TAG, "Observer no longer exists.");
13290                    }
13291                } //end if observer
13292            } //end run
13293        });
13294    }
13295
13296    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13297        if (packageName == null) {
13298            Slog.w(TAG, "Attempt to delete null packageName.");
13299            return false;
13300        }
13301
13302        // Try finding details about the requested package
13303        PackageParser.Package pkg;
13304        synchronized (mPackages) {
13305            pkg = mPackages.get(packageName);
13306            if (pkg == null) {
13307                final PackageSetting ps = mSettings.mPackages.get(packageName);
13308                if (ps != null) {
13309                    pkg = ps.pkg;
13310                }
13311            }
13312
13313            if (pkg == null) {
13314                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13315                return false;
13316            }
13317
13318            PackageSetting ps = (PackageSetting) pkg.mExtras;
13319            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13320        }
13321
13322        // Always delete data directories for package, even if we found no other
13323        // record of app. This helps users recover from UID mismatches without
13324        // resorting to a full data wipe.
13325        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13326        if (retCode < 0) {
13327            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13328            return false;
13329        }
13330
13331        final int appId = pkg.applicationInfo.uid;
13332        removeKeystoreDataIfNeeded(userId, appId);
13333
13334        // Create a native library symlink only if we have native libraries
13335        // and if the native libraries are 32 bit libraries. We do not provide
13336        // this symlink for 64 bit libraries.
13337        if (pkg.applicationInfo.primaryCpuAbi != null &&
13338                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13339            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13340            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13341                    nativeLibPath, userId) < 0) {
13342                Slog.w(TAG, "Failed linking native library dir");
13343                return false;
13344            }
13345        }
13346
13347        return true;
13348    }
13349
13350    /**
13351     * Reverts user permission state changes (permissions and flags) in
13352     * all packages for a given user.
13353     *
13354     * @param userId The device user for which to do a reset.
13355     */
13356    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13357        final int packageCount = mPackages.size();
13358        for (int i = 0; i < packageCount; i++) {
13359            PackageParser.Package pkg = mPackages.valueAt(i);
13360            PackageSetting ps = (PackageSetting) pkg.mExtras;
13361            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13362        }
13363    }
13364
13365    /**
13366     * Reverts user permission state changes (permissions and flags).
13367     *
13368     * @param ps The package for which to reset.
13369     * @param userId The device user for which to do a reset.
13370     */
13371    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13372            final PackageSetting ps, final int userId) {
13373        if (ps.pkg == null) {
13374            return;
13375        }
13376
13377        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13378                | FLAG_PERMISSION_USER_FIXED
13379                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13380
13381        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13382                | FLAG_PERMISSION_POLICY_FIXED;
13383
13384        boolean writeInstallPermissions = false;
13385        boolean writeRuntimePermissions = false;
13386
13387        final int permissionCount = ps.pkg.requestedPermissions.size();
13388        for (int i = 0; i < permissionCount; i++) {
13389            String permission = ps.pkg.requestedPermissions.get(i);
13390
13391            BasePermission bp = mSettings.mPermissions.get(permission);
13392            if (bp == null) {
13393                continue;
13394            }
13395
13396            // If shared user we just reset the state to which only this app contributed.
13397            if (ps.sharedUser != null) {
13398                boolean used = false;
13399                final int packageCount = ps.sharedUser.packages.size();
13400                for (int j = 0; j < packageCount; j++) {
13401                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13402                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13403                            && pkg.pkg.requestedPermissions.contains(permission)) {
13404                        used = true;
13405                        break;
13406                    }
13407                }
13408                if (used) {
13409                    continue;
13410                }
13411            }
13412
13413            PermissionsState permissionsState = ps.getPermissionsState();
13414
13415            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13416
13417            // Always clear the user settable flags.
13418            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13419                    bp.name) != null;
13420            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13421                if (hasInstallState) {
13422                    writeInstallPermissions = true;
13423                } else {
13424                    writeRuntimePermissions = true;
13425                }
13426            }
13427
13428            // Below is only runtime permission handling.
13429            if (!bp.isRuntime()) {
13430                continue;
13431            }
13432
13433            // Never clobber system or policy.
13434            if ((oldFlags & policyOrSystemFlags) != 0) {
13435                continue;
13436            }
13437
13438            // If this permission was granted by default, make sure it is.
13439            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13440                if (permissionsState.grantRuntimePermission(bp, userId)
13441                        != PERMISSION_OPERATION_FAILURE) {
13442                    writeRuntimePermissions = true;
13443                }
13444            } else {
13445                // Otherwise, reset the permission.
13446                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13447                switch (revokeResult) {
13448                    case PERMISSION_OPERATION_SUCCESS: {
13449                        writeRuntimePermissions = true;
13450                    } break;
13451
13452                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13453                        writeRuntimePermissions = true;
13454                        final int appId = ps.appId;
13455                        mHandler.post(new Runnable() {
13456                            @Override
13457                            public void run() {
13458                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13459                            }
13460                        });
13461                    } break;
13462                }
13463            }
13464        }
13465
13466        // Synchronously write as we are taking permissions away.
13467        if (writeRuntimePermissions) {
13468            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13469        }
13470
13471        // Synchronously write as we are taking permissions away.
13472        if (writeInstallPermissions) {
13473            mSettings.writeLPr();
13474        }
13475    }
13476
13477    /**
13478     * Remove entries from the keystore daemon. Will only remove it if the
13479     * {@code appId} is valid.
13480     */
13481    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13482        if (appId < 0) {
13483            return;
13484        }
13485
13486        final KeyStore keyStore = KeyStore.getInstance();
13487        if (keyStore != null) {
13488            if (userId == UserHandle.USER_ALL) {
13489                for (final int individual : sUserManager.getUserIds()) {
13490                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13491                }
13492            } else {
13493                keyStore.clearUid(UserHandle.getUid(userId, appId));
13494            }
13495        } else {
13496            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13497        }
13498    }
13499
13500    @Override
13501    public void deleteApplicationCacheFiles(final String packageName,
13502            final IPackageDataObserver observer) {
13503        mContext.enforceCallingOrSelfPermission(
13504                android.Manifest.permission.DELETE_CACHE_FILES, null);
13505        // Queue up an async operation since the package deletion may take a little while.
13506        final int userId = UserHandle.getCallingUserId();
13507        mHandler.post(new Runnable() {
13508            public void run() {
13509                mHandler.removeCallbacks(this);
13510                final boolean succeded;
13511                synchronized (mInstallLock) {
13512                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13513                }
13514                clearExternalStorageDataSync(packageName, userId, false);
13515                if (observer != null) {
13516                    try {
13517                        observer.onRemoveCompleted(packageName, succeded);
13518                    } catch (RemoteException e) {
13519                        Log.i(TAG, "Observer no longer exists.");
13520                    }
13521                } //end if observer
13522            } //end run
13523        });
13524    }
13525
13526    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13527        if (packageName == null) {
13528            Slog.w(TAG, "Attempt to delete null packageName.");
13529            return false;
13530        }
13531        PackageParser.Package p;
13532        synchronized (mPackages) {
13533            p = mPackages.get(packageName);
13534        }
13535        if (p == null) {
13536            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13537            return false;
13538        }
13539        final ApplicationInfo applicationInfo = p.applicationInfo;
13540        if (applicationInfo == null) {
13541            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13542            return false;
13543        }
13544        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13545        if (retCode < 0) {
13546            Slog.w(TAG, "Couldn't remove cache files for package: "
13547                       + packageName + " u" + userId);
13548            return false;
13549        }
13550        return true;
13551    }
13552
13553    @Override
13554    public void getPackageSizeInfo(final String packageName, int userHandle,
13555            final IPackageStatsObserver observer) {
13556        mContext.enforceCallingOrSelfPermission(
13557                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13558        if (packageName == null) {
13559            throw new IllegalArgumentException("Attempt to get size of null packageName");
13560        }
13561
13562        PackageStats stats = new PackageStats(packageName, userHandle);
13563
13564        /*
13565         * Queue up an async operation since the package measurement may take a
13566         * little while.
13567         */
13568        Message msg = mHandler.obtainMessage(INIT_COPY);
13569        msg.obj = new MeasureParams(stats, observer);
13570        mHandler.sendMessage(msg);
13571    }
13572
13573    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13574            PackageStats pStats) {
13575        if (packageName == null) {
13576            Slog.w(TAG, "Attempt to get size of null packageName.");
13577            return false;
13578        }
13579        PackageParser.Package p;
13580        boolean dataOnly = false;
13581        String libDirRoot = null;
13582        String asecPath = null;
13583        PackageSetting ps = null;
13584        synchronized (mPackages) {
13585            p = mPackages.get(packageName);
13586            ps = mSettings.mPackages.get(packageName);
13587            if(p == null) {
13588                dataOnly = true;
13589                if((ps == null) || (ps.pkg == null)) {
13590                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13591                    return false;
13592                }
13593                p = ps.pkg;
13594            }
13595            if (ps != null) {
13596                libDirRoot = ps.legacyNativeLibraryPathString;
13597            }
13598            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13599                final long token = Binder.clearCallingIdentity();
13600                try {
13601                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13602                    if (secureContainerId != null) {
13603                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13604                    }
13605                } finally {
13606                    Binder.restoreCallingIdentity(token);
13607                }
13608            }
13609        }
13610        String publicSrcDir = null;
13611        if(!dataOnly) {
13612            final ApplicationInfo applicationInfo = p.applicationInfo;
13613            if (applicationInfo == null) {
13614                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13615                return false;
13616            }
13617            if (p.isForwardLocked()) {
13618                publicSrcDir = applicationInfo.getBaseResourcePath();
13619            }
13620        }
13621        // TODO: extend to measure size of split APKs
13622        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13623        // not just the first level.
13624        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13625        // just the primary.
13626        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13627        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13628                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13629        if (res < 0) {
13630            return false;
13631        }
13632
13633        // Fix-up for forward-locked applications in ASEC containers.
13634        if (!isExternal(p)) {
13635            pStats.codeSize += pStats.externalCodeSize;
13636            pStats.externalCodeSize = 0L;
13637        }
13638
13639        return true;
13640    }
13641
13642
13643    @Override
13644    public void addPackageToPreferred(String packageName) {
13645        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13646    }
13647
13648    @Override
13649    public void removePackageFromPreferred(String packageName) {
13650        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13651    }
13652
13653    @Override
13654    public List<PackageInfo> getPreferredPackages(int flags) {
13655        return new ArrayList<PackageInfo>();
13656    }
13657
13658    private int getUidTargetSdkVersionLockedLPr(int uid) {
13659        Object obj = mSettings.getUserIdLPr(uid);
13660        if (obj instanceof SharedUserSetting) {
13661            final SharedUserSetting sus = (SharedUserSetting) obj;
13662            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13663            final Iterator<PackageSetting> it = sus.packages.iterator();
13664            while (it.hasNext()) {
13665                final PackageSetting ps = it.next();
13666                if (ps.pkg != null) {
13667                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13668                    if (v < vers) vers = v;
13669                }
13670            }
13671            return vers;
13672        } else if (obj instanceof PackageSetting) {
13673            final PackageSetting ps = (PackageSetting) obj;
13674            if (ps.pkg != null) {
13675                return ps.pkg.applicationInfo.targetSdkVersion;
13676            }
13677        }
13678        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13679    }
13680
13681    @Override
13682    public void addPreferredActivity(IntentFilter filter, int match,
13683            ComponentName[] set, ComponentName activity, int userId) {
13684        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13685                "Adding preferred");
13686    }
13687
13688    private void addPreferredActivityInternal(IntentFilter filter, int match,
13689            ComponentName[] set, ComponentName activity, boolean always, int userId,
13690            String opname) {
13691        // writer
13692        int callingUid = Binder.getCallingUid();
13693        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13694        if (filter.countActions() == 0) {
13695            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13696            return;
13697        }
13698        synchronized (mPackages) {
13699            if (mContext.checkCallingOrSelfPermission(
13700                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13701                    != PackageManager.PERMISSION_GRANTED) {
13702                if (getUidTargetSdkVersionLockedLPr(callingUid)
13703                        < Build.VERSION_CODES.FROYO) {
13704                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13705                            + callingUid);
13706                    return;
13707                }
13708                mContext.enforceCallingOrSelfPermission(
13709                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13710            }
13711
13712            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13713            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13714                    + userId + ":");
13715            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13716            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13717            scheduleWritePackageRestrictionsLocked(userId);
13718        }
13719    }
13720
13721    @Override
13722    public void replacePreferredActivity(IntentFilter filter, int match,
13723            ComponentName[] set, ComponentName activity, int userId) {
13724        if (filter.countActions() != 1) {
13725            throw new IllegalArgumentException(
13726                    "replacePreferredActivity expects filter to have only 1 action.");
13727        }
13728        if (filter.countDataAuthorities() != 0
13729                || filter.countDataPaths() != 0
13730                || filter.countDataSchemes() > 1
13731                || filter.countDataTypes() != 0) {
13732            throw new IllegalArgumentException(
13733                    "replacePreferredActivity expects filter to have no data authorities, " +
13734                    "paths, or types; and at most one scheme.");
13735        }
13736
13737        final int callingUid = Binder.getCallingUid();
13738        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13739        synchronized (mPackages) {
13740            if (mContext.checkCallingOrSelfPermission(
13741                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13742                    != PackageManager.PERMISSION_GRANTED) {
13743                if (getUidTargetSdkVersionLockedLPr(callingUid)
13744                        < Build.VERSION_CODES.FROYO) {
13745                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13746                            + Binder.getCallingUid());
13747                    return;
13748                }
13749                mContext.enforceCallingOrSelfPermission(
13750                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13751            }
13752
13753            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13754            if (pir != null) {
13755                // Get all of the existing entries that exactly match this filter.
13756                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13757                if (existing != null && existing.size() == 1) {
13758                    PreferredActivity cur = existing.get(0);
13759                    if (DEBUG_PREFERRED) {
13760                        Slog.i(TAG, "Checking replace of preferred:");
13761                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13762                        if (!cur.mPref.mAlways) {
13763                            Slog.i(TAG, "  -- CUR; not mAlways!");
13764                        } else {
13765                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13766                            Slog.i(TAG, "  -- CUR: mSet="
13767                                    + Arrays.toString(cur.mPref.mSetComponents));
13768                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13769                            Slog.i(TAG, "  -- NEW: mMatch="
13770                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13771                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13772                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13773                        }
13774                    }
13775                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13776                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13777                            && cur.mPref.sameSet(set)) {
13778                        // Setting the preferred activity to what it happens to be already
13779                        if (DEBUG_PREFERRED) {
13780                            Slog.i(TAG, "Replacing with same preferred activity "
13781                                    + cur.mPref.mShortComponent + " for user "
13782                                    + userId + ":");
13783                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13784                        }
13785                        return;
13786                    }
13787                }
13788
13789                if (existing != null) {
13790                    if (DEBUG_PREFERRED) {
13791                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13792                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13793                    }
13794                    for (int i = 0; i < existing.size(); i++) {
13795                        PreferredActivity pa = existing.get(i);
13796                        if (DEBUG_PREFERRED) {
13797                            Slog.i(TAG, "Removing existing preferred activity "
13798                                    + pa.mPref.mComponent + ":");
13799                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13800                        }
13801                        pir.removeFilter(pa);
13802                    }
13803                }
13804            }
13805            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13806                    "Replacing preferred");
13807        }
13808    }
13809
13810    @Override
13811    public void clearPackagePreferredActivities(String packageName) {
13812        final int uid = Binder.getCallingUid();
13813        // writer
13814        synchronized (mPackages) {
13815            PackageParser.Package pkg = mPackages.get(packageName);
13816            if (pkg == null || pkg.applicationInfo.uid != uid) {
13817                if (mContext.checkCallingOrSelfPermission(
13818                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13819                        != PackageManager.PERMISSION_GRANTED) {
13820                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13821                            < Build.VERSION_CODES.FROYO) {
13822                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13823                                + Binder.getCallingUid());
13824                        return;
13825                    }
13826                    mContext.enforceCallingOrSelfPermission(
13827                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13828                }
13829            }
13830
13831            int user = UserHandle.getCallingUserId();
13832            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13833                scheduleWritePackageRestrictionsLocked(user);
13834            }
13835        }
13836    }
13837
13838    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13839    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13840        ArrayList<PreferredActivity> removed = null;
13841        boolean changed = false;
13842        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13843            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13844            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13845            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13846                continue;
13847            }
13848            Iterator<PreferredActivity> it = pir.filterIterator();
13849            while (it.hasNext()) {
13850                PreferredActivity pa = it.next();
13851                // Mark entry for removal only if it matches the package name
13852                // and the entry is of type "always".
13853                if (packageName == null ||
13854                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13855                                && pa.mPref.mAlways)) {
13856                    if (removed == null) {
13857                        removed = new ArrayList<PreferredActivity>();
13858                    }
13859                    removed.add(pa);
13860                }
13861            }
13862            if (removed != null) {
13863                for (int j=0; j<removed.size(); j++) {
13864                    PreferredActivity pa = removed.get(j);
13865                    pir.removeFilter(pa);
13866                }
13867                changed = true;
13868            }
13869        }
13870        return changed;
13871    }
13872
13873    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13874    private void clearIntentFilterVerificationsLPw(int userId) {
13875        final int packageCount = mPackages.size();
13876        for (int i = 0; i < packageCount; i++) {
13877            PackageParser.Package pkg = mPackages.valueAt(i);
13878            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13879        }
13880    }
13881
13882    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13883    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13884        if (userId == UserHandle.USER_ALL) {
13885            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13886                    sUserManager.getUserIds())) {
13887                for (int oneUserId : sUserManager.getUserIds()) {
13888                    scheduleWritePackageRestrictionsLocked(oneUserId);
13889                }
13890            }
13891        } else {
13892            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13893                scheduleWritePackageRestrictionsLocked(userId);
13894            }
13895        }
13896    }
13897
13898    void clearDefaultBrowserIfNeeded(String packageName) {
13899        for (int oneUserId : sUserManager.getUserIds()) {
13900            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13901            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13902            if (packageName.equals(defaultBrowserPackageName)) {
13903                setDefaultBrowserPackageName(null, oneUserId);
13904            }
13905        }
13906    }
13907
13908    @Override
13909    public void resetApplicationPreferences(int userId) {
13910        mContext.enforceCallingOrSelfPermission(
13911                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13912        // writer
13913        synchronized (mPackages) {
13914            final long identity = Binder.clearCallingIdentity();
13915            try {
13916                clearPackagePreferredActivitiesLPw(null, userId);
13917                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13918                // TODO: We have to reset the default SMS and Phone. This requires
13919                // significant refactoring to keep all default apps in the package
13920                // manager (cleaner but more work) or have the services provide
13921                // callbacks to the package manager to request a default app reset.
13922                applyFactoryDefaultBrowserLPw(userId);
13923                clearIntentFilterVerificationsLPw(userId);
13924                primeDomainVerificationsLPw(userId);
13925                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13926                scheduleWritePackageRestrictionsLocked(userId);
13927            } finally {
13928                Binder.restoreCallingIdentity(identity);
13929            }
13930        }
13931    }
13932
13933    @Override
13934    public int getPreferredActivities(List<IntentFilter> outFilters,
13935            List<ComponentName> outActivities, String packageName) {
13936
13937        int num = 0;
13938        final int userId = UserHandle.getCallingUserId();
13939        // reader
13940        synchronized (mPackages) {
13941            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13942            if (pir != null) {
13943                final Iterator<PreferredActivity> it = pir.filterIterator();
13944                while (it.hasNext()) {
13945                    final PreferredActivity pa = it.next();
13946                    if (packageName == null
13947                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13948                                    && pa.mPref.mAlways)) {
13949                        if (outFilters != null) {
13950                            outFilters.add(new IntentFilter(pa));
13951                        }
13952                        if (outActivities != null) {
13953                            outActivities.add(pa.mPref.mComponent);
13954                        }
13955                    }
13956                }
13957            }
13958        }
13959
13960        return num;
13961    }
13962
13963    @Override
13964    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13965            int userId) {
13966        int callingUid = Binder.getCallingUid();
13967        if (callingUid != Process.SYSTEM_UID) {
13968            throw new SecurityException(
13969                    "addPersistentPreferredActivity can only be run by the system");
13970        }
13971        if (filter.countActions() == 0) {
13972            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13973            return;
13974        }
13975        synchronized (mPackages) {
13976            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13977                    " :");
13978            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13979            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13980                    new PersistentPreferredActivity(filter, activity));
13981            scheduleWritePackageRestrictionsLocked(userId);
13982        }
13983    }
13984
13985    @Override
13986    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13987        int callingUid = Binder.getCallingUid();
13988        if (callingUid != Process.SYSTEM_UID) {
13989            throw new SecurityException(
13990                    "clearPackagePersistentPreferredActivities can only be run by the system");
13991        }
13992        ArrayList<PersistentPreferredActivity> removed = null;
13993        boolean changed = false;
13994        synchronized (mPackages) {
13995            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13996                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13997                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13998                        .valueAt(i);
13999                if (userId != thisUserId) {
14000                    continue;
14001                }
14002                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14003                while (it.hasNext()) {
14004                    PersistentPreferredActivity ppa = it.next();
14005                    // Mark entry for removal only if it matches the package name.
14006                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14007                        if (removed == null) {
14008                            removed = new ArrayList<PersistentPreferredActivity>();
14009                        }
14010                        removed.add(ppa);
14011                    }
14012                }
14013                if (removed != null) {
14014                    for (int j=0; j<removed.size(); j++) {
14015                        PersistentPreferredActivity ppa = removed.get(j);
14016                        ppir.removeFilter(ppa);
14017                    }
14018                    changed = true;
14019                }
14020            }
14021
14022            if (changed) {
14023                scheduleWritePackageRestrictionsLocked(userId);
14024            }
14025        }
14026    }
14027
14028    /**
14029     * Common machinery for picking apart a restored XML blob and passing
14030     * it to a caller-supplied functor to be applied to the running system.
14031     */
14032    private void restoreFromXml(XmlPullParser parser, int userId,
14033            String expectedStartTag, BlobXmlRestorer functor)
14034            throws IOException, XmlPullParserException {
14035        int type;
14036        while ((type = parser.next()) != XmlPullParser.START_TAG
14037                && type != XmlPullParser.END_DOCUMENT) {
14038        }
14039        if (type != XmlPullParser.START_TAG) {
14040            // oops didn't find a start tag?!
14041            if (DEBUG_BACKUP) {
14042                Slog.e(TAG, "Didn't find start tag during restore");
14043            }
14044            return;
14045        }
14046
14047        // this is supposed to be TAG_PREFERRED_BACKUP
14048        if (!expectedStartTag.equals(parser.getName())) {
14049            if (DEBUG_BACKUP) {
14050                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14051            }
14052            return;
14053        }
14054
14055        // skip interfering stuff, then we're aligned with the backing implementation
14056        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14057        functor.apply(parser, userId);
14058    }
14059
14060    private interface BlobXmlRestorer {
14061        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14062    }
14063
14064    /**
14065     * Non-Binder method, support for the backup/restore mechanism: write the
14066     * full set of preferred activities in its canonical XML format.  Returns the
14067     * XML output as a byte array, or null if there is none.
14068     */
14069    @Override
14070    public byte[] getPreferredActivityBackup(int userId) {
14071        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14072            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14073        }
14074
14075        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14076        try {
14077            final XmlSerializer serializer = new FastXmlSerializer();
14078            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14079            serializer.startDocument(null, true);
14080            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14081
14082            synchronized (mPackages) {
14083                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14084            }
14085
14086            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14087            serializer.endDocument();
14088            serializer.flush();
14089        } catch (Exception e) {
14090            if (DEBUG_BACKUP) {
14091                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14092            }
14093            return null;
14094        }
14095
14096        return dataStream.toByteArray();
14097    }
14098
14099    @Override
14100    public void restorePreferredActivities(byte[] backup, int userId) {
14101        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14102            throw new SecurityException("Only the system may call restorePreferredActivities()");
14103        }
14104
14105        try {
14106            final XmlPullParser parser = Xml.newPullParser();
14107            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14108            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14109                    new BlobXmlRestorer() {
14110                        @Override
14111                        public void apply(XmlPullParser parser, int userId)
14112                                throws XmlPullParserException, IOException {
14113                            synchronized (mPackages) {
14114                                mSettings.readPreferredActivitiesLPw(parser, userId);
14115                            }
14116                        }
14117                    } );
14118        } catch (Exception e) {
14119            if (DEBUG_BACKUP) {
14120                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14121            }
14122        }
14123    }
14124
14125    /**
14126     * Non-Binder method, support for the backup/restore mechanism: write the
14127     * default browser (etc) settings in its canonical XML format.  Returns the default
14128     * browser XML representation as a byte array, or null if there is none.
14129     */
14130    @Override
14131    public byte[] getDefaultAppsBackup(int userId) {
14132        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14133            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14134        }
14135
14136        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14137        try {
14138            final XmlSerializer serializer = new FastXmlSerializer();
14139            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14140            serializer.startDocument(null, true);
14141            serializer.startTag(null, TAG_DEFAULT_APPS);
14142
14143            synchronized (mPackages) {
14144                mSettings.writeDefaultAppsLPr(serializer, userId);
14145            }
14146
14147            serializer.endTag(null, TAG_DEFAULT_APPS);
14148            serializer.endDocument();
14149            serializer.flush();
14150        } catch (Exception e) {
14151            if (DEBUG_BACKUP) {
14152                Slog.e(TAG, "Unable to write default apps for backup", e);
14153            }
14154            return null;
14155        }
14156
14157        return dataStream.toByteArray();
14158    }
14159
14160    @Override
14161    public void restoreDefaultApps(byte[] backup, int userId) {
14162        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14163            throw new SecurityException("Only the system may call restoreDefaultApps()");
14164        }
14165
14166        try {
14167            final XmlPullParser parser = Xml.newPullParser();
14168            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14169            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14170                    new BlobXmlRestorer() {
14171                        @Override
14172                        public void apply(XmlPullParser parser, int userId)
14173                                throws XmlPullParserException, IOException {
14174                            synchronized (mPackages) {
14175                                mSettings.readDefaultAppsLPw(parser, userId);
14176                            }
14177                        }
14178                    } );
14179        } catch (Exception e) {
14180            if (DEBUG_BACKUP) {
14181                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14182            }
14183        }
14184    }
14185
14186    @Override
14187    public byte[] getIntentFilterVerificationBackup(int userId) {
14188        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14189            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14190        }
14191
14192        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14193        try {
14194            final XmlSerializer serializer = new FastXmlSerializer();
14195            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14196            serializer.startDocument(null, true);
14197            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14198
14199            synchronized (mPackages) {
14200                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14201            }
14202
14203            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14204            serializer.endDocument();
14205            serializer.flush();
14206        } catch (Exception e) {
14207            if (DEBUG_BACKUP) {
14208                Slog.e(TAG, "Unable to write default apps for backup", e);
14209            }
14210            return null;
14211        }
14212
14213        return dataStream.toByteArray();
14214    }
14215
14216    @Override
14217    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14218        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14219            throw new SecurityException("Only the system may call restorePreferredActivities()");
14220        }
14221
14222        try {
14223            final XmlPullParser parser = Xml.newPullParser();
14224            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14225            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14226                    new BlobXmlRestorer() {
14227                        @Override
14228                        public void apply(XmlPullParser parser, int userId)
14229                                throws XmlPullParserException, IOException {
14230                            synchronized (mPackages) {
14231                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14232                                mSettings.writeLPr();
14233                            }
14234                        }
14235                    } );
14236        } catch (Exception e) {
14237            if (DEBUG_BACKUP) {
14238                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14239            }
14240        }
14241    }
14242
14243    @Override
14244    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14245            int sourceUserId, int targetUserId, int flags) {
14246        mContext.enforceCallingOrSelfPermission(
14247                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14248        int callingUid = Binder.getCallingUid();
14249        enforceOwnerRights(ownerPackage, callingUid);
14250        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14251        if (intentFilter.countActions() == 0) {
14252            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14253            return;
14254        }
14255        synchronized (mPackages) {
14256            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14257                    ownerPackage, targetUserId, flags);
14258            CrossProfileIntentResolver resolver =
14259                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14260            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14261            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14262            if (existing != null) {
14263                int size = existing.size();
14264                for (int i = 0; i < size; i++) {
14265                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14266                        return;
14267                    }
14268                }
14269            }
14270            resolver.addFilter(newFilter);
14271            scheduleWritePackageRestrictionsLocked(sourceUserId);
14272        }
14273    }
14274
14275    @Override
14276    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14277        mContext.enforceCallingOrSelfPermission(
14278                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14279        int callingUid = Binder.getCallingUid();
14280        enforceOwnerRights(ownerPackage, callingUid);
14281        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14282        synchronized (mPackages) {
14283            CrossProfileIntentResolver resolver =
14284                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14285            ArraySet<CrossProfileIntentFilter> set =
14286                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14287            for (CrossProfileIntentFilter filter : set) {
14288                if (filter.getOwnerPackage().equals(ownerPackage)) {
14289                    resolver.removeFilter(filter);
14290                }
14291            }
14292            scheduleWritePackageRestrictionsLocked(sourceUserId);
14293        }
14294    }
14295
14296    // Enforcing that callingUid is owning pkg on userId
14297    private void enforceOwnerRights(String pkg, int callingUid) {
14298        // The system owns everything.
14299        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14300            return;
14301        }
14302        int callingUserId = UserHandle.getUserId(callingUid);
14303        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14304        if (pi == null) {
14305            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14306                    + callingUserId);
14307        }
14308        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14309            throw new SecurityException("Calling uid " + callingUid
14310                    + " does not own package " + pkg);
14311        }
14312    }
14313
14314    @Override
14315    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14316        Intent intent = new Intent(Intent.ACTION_MAIN);
14317        intent.addCategory(Intent.CATEGORY_HOME);
14318
14319        final int callingUserId = UserHandle.getCallingUserId();
14320        List<ResolveInfo> list = queryIntentActivities(intent, null,
14321                PackageManager.GET_META_DATA, callingUserId);
14322        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14323                true, false, false, callingUserId);
14324
14325        allHomeCandidates.clear();
14326        if (list != null) {
14327            for (ResolveInfo ri : list) {
14328                allHomeCandidates.add(ri);
14329            }
14330        }
14331        return (preferred == null || preferred.activityInfo == null)
14332                ? null
14333                : new ComponentName(preferred.activityInfo.packageName,
14334                        preferred.activityInfo.name);
14335    }
14336
14337    @Override
14338    public void setApplicationEnabledSetting(String appPackageName,
14339            int newState, int flags, int userId, String callingPackage) {
14340        if (!sUserManager.exists(userId)) return;
14341        if (callingPackage == null) {
14342            callingPackage = Integer.toString(Binder.getCallingUid());
14343        }
14344        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14345    }
14346
14347    @Override
14348    public void setComponentEnabledSetting(ComponentName componentName,
14349            int newState, int flags, int userId) {
14350        if (!sUserManager.exists(userId)) return;
14351        setEnabledSetting(componentName.getPackageName(),
14352                componentName.getClassName(), newState, flags, userId, null);
14353    }
14354
14355    private void setEnabledSetting(final String packageName, String className, int newState,
14356            final int flags, int userId, String callingPackage) {
14357        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14358              || newState == COMPONENT_ENABLED_STATE_ENABLED
14359              || newState == COMPONENT_ENABLED_STATE_DISABLED
14360              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14361              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14362            throw new IllegalArgumentException("Invalid new component state: "
14363                    + newState);
14364        }
14365        PackageSetting pkgSetting;
14366        final int uid = Binder.getCallingUid();
14367        final int permission = mContext.checkCallingOrSelfPermission(
14368                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14369        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14370        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14371        boolean sendNow = false;
14372        boolean isApp = (className == null);
14373        String componentName = isApp ? packageName : className;
14374        int packageUid = -1;
14375        ArrayList<String> components;
14376
14377        // writer
14378        synchronized (mPackages) {
14379            pkgSetting = mSettings.mPackages.get(packageName);
14380            if (pkgSetting == null) {
14381                if (className == null) {
14382                    throw new IllegalArgumentException(
14383                            "Unknown package: " + packageName);
14384                }
14385                throw new IllegalArgumentException(
14386                        "Unknown component: " + packageName
14387                        + "/" + className);
14388            }
14389            // Allow root and verify that userId is not being specified by a different user
14390            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14391                throw new SecurityException(
14392                        "Permission Denial: attempt to change component state from pid="
14393                        + Binder.getCallingPid()
14394                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14395            }
14396            if (className == null) {
14397                // We're dealing with an application/package level state change
14398                if (pkgSetting.getEnabled(userId) == newState) {
14399                    // Nothing to do
14400                    return;
14401                }
14402                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14403                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14404                    // Don't care about who enables an app.
14405                    callingPackage = null;
14406                }
14407                pkgSetting.setEnabled(newState, userId, callingPackage);
14408                // pkgSetting.pkg.mSetEnabled = newState;
14409            } else {
14410                // We're dealing with a component level state change
14411                // First, verify that this is a valid class name.
14412                PackageParser.Package pkg = pkgSetting.pkg;
14413                if (pkg == null || !pkg.hasComponentClassName(className)) {
14414                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14415                        throw new IllegalArgumentException("Component class " + className
14416                                + " does not exist in " + packageName);
14417                    } else {
14418                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14419                                + className + " does not exist in " + packageName);
14420                    }
14421                }
14422                switch (newState) {
14423                case COMPONENT_ENABLED_STATE_ENABLED:
14424                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14425                        return;
14426                    }
14427                    break;
14428                case COMPONENT_ENABLED_STATE_DISABLED:
14429                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14430                        return;
14431                    }
14432                    break;
14433                case COMPONENT_ENABLED_STATE_DEFAULT:
14434                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14435                        return;
14436                    }
14437                    break;
14438                default:
14439                    Slog.e(TAG, "Invalid new component state: " + newState);
14440                    return;
14441                }
14442            }
14443            scheduleWritePackageRestrictionsLocked(userId);
14444            components = mPendingBroadcasts.get(userId, packageName);
14445            final boolean newPackage = components == null;
14446            if (newPackage) {
14447                components = new ArrayList<String>();
14448            }
14449            if (!components.contains(componentName)) {
14450                components.add(componentName);
14451            }
14452            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14453                sendNow = true;
14454                // Purge entry from pending broadcast list if another one exists already
14455                // since we are sending one right away.
14456                mPendingBroadcasts.remove(userId, packageName);
14457            } else {
14458                if (newPackage) {
14459                    mPendingBroadcasts.put(userId, packageName, components);
14460                }
14461                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14462                    // Schedule a message
14463                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14464                }
14465            }
14466        }
14467
14468        long callingId = Binder.clearCallingIdentity();
14469        try {
14470            if (sendNow) {
14471                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14472                sendPackageChangedBroadcast(packageName,
14473                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14474            }
14475        } finally {
14476            Binder.restoreCallingIdentity(callingId);
14477        }
14478    }
14479
14480    private void sendPackageChangedBroadcast(String packageName,
14481            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14482        if (DEBUG_INSTALL)
14483            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14484                    + componentNames);
14485        Bundle extras = new Bundle(4);
14486        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14487        String nameList[] = new String[componentNames.size()];
14488        componentNames.toArray(nameList);
14489        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14490        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14491        extras.putInt(Intent.EXTRA_UID, packageUid);
14492        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14493                new int[] {UserHandle.getUserId(packageUid)});
14494    }
14495
14496    @Override
14497    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14498        if (!sUserManager.exists(userId)) return;
14499        final int uid = Binder.getCallingUid();
14500        final int permission = mContext.checkCallingOrSelfPermission(
14501                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14502        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14503        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14504        // writer
14505        synchronized (mPackages) {
14506            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14507                    allowedByPermission, uid, userId)) {
14508                scheduleWritePackageRestrictionsLocked(userId);
14509            }
14510        }
14511    }
14512
14513    @Override
14514    public String getInstallerPackageName(String packageName) {
14515        // reader
14516        synchronized (mPackages) {
14517            return mSettings.getInstallerPackageNameLPr(packageName);
14518        }
14519    }
14520
14521    @Override
14522    public int getApplicationEnabledSetting(String packageName, int userId) {
14523        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14524        int uid = Binder.getCallingUid();
14525        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14526        // reader
14527        synchronized (mPackages) {
14528            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14529        }
14530    }
14531
14532    @Override
14533    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14534        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14535        int uid = Binder.getCallingUid();
14536        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14537        // reader
14538        synchronized (mPackages) {
14539            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14540        }
14541    }
14542
14543    @Override
14544    public void enterSafeMode() {
14545        enforceSystemOrRoot("Only the system can request entering safe mode");
14546
14547        if (!mSystemReady) {
14548            mSafeMode = true;
14549        }
14550    }
14551
14552    @Override
14553    public void systemReady() {
14554        mSystemReady = true;
14555
14556        // Read the compatibilty setting when the system is ready.
14557        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14558                mContext.getContentResolver(),
14559                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14560        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14561        if (DEBUG_SETTINGS) {
14562            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14563        }
14564
14565        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14566
14567        synchronized (mPackages) {
14568            // Verify that all of the preferred activity components actually
14569            // exist.  It is possible for applications to be updated and at
14570            // that point remove a previously declared activity component that
14571            // had been set as a preferred activity.  We try to clean this up
14572            // the next time we encounter that preferred activity, but it is
14573            // possible for the user flow to never be able to return to that
14574            // situation so here we do a sanity check to make sure we haven't
14575            // left any junk around.
14576            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14577            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14578                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14579                removed.clear();
14580                for (PreferredActivity pa : pir.filterSet()) {
14581                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14582                        removed.add(pa);
14583                    }
14584                }
14585                if (removed.size() > 0) {
14586                    for (int r=0; r<removed.size(); r++) {
14587                        PreferredActivity pa = removed.get(r);
14588                        Slog.w(TAG, "Removing dangling preferred activity: "
14589                                + pa.mPref.mComponent);
14590                        pir.removeFilter(pa);
14591                    }
14592                    mSettings.writePackageRestrictionsLPr(
14593                            mSettings.mPreferredActivities.keyAt(i));
14594                }
14595            }
14596
14597            for (int userId : UserManagerService.getInstance().getUserIds()) {
14598                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14599                    grantPermissionsUserIds = ArrayUtils.appendInt(
14600                            grantPermissionsUserIds, userId);
14601                }
14602            }
14603        }
14604        sUserManager.systemReady();
14605
14606        // If we upgraded grant all default permissions before kicking off.
14607        for (int userId : grantPermissionsUserIds) {
14608            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14609        }
14610
14611        // Kick off any messages waiting for system ready
14612        if (mPostSystemReadyMessages != null) {
14613            for (Message msg : mPostSystemReadyMessages) {
14614                msg.sendToTarget();
14615            }
14616            mPostSystemReadyMessages = null;
14617        }
14618
14619        // Watch for external volumes that come and go over time
14620        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14621        storage.registerListener(mStorageListener);
14622
14623        mInstallerService.systemReady();
14624        mPackageDexOptimizer.systemReady();
14625
14626        MountServiceInternal mountServiceInternal = LocalServices.getService(
14627                MountServiceInternal.class);
14628        mountServiceInternal.addExternalStoragePolicy(
14629                new MountServiceInternal.ExternalStorageMountPolicy() {
14630            @Override
14631            public int getMountMode(int uid, String packageName) {
14632                if (Process.isIsolated(uid)) {
14633                    return Zygote.MOUNT_EXTERNAL_NONE;
14634                }
14635                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14636                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14637                }
14638                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14639                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14640                }
14641                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14642                    return Zygote.MOUNT_EXTERNAL_READ;
14643                }
14644                return Zygote.MOUNT_EXTERNAL_WRITE;
14645            }
14646
14647            @Override
14648            public boolean hasExternalStorage(int uid, String packageName) {
14649                return true;
14650            }
14651        });
14652    }
14653
14654    @Override
14655    public boolean isSafeMode() {
14656        return mSafeMode;
14657    }
14658
14659    @Override
14660    public boolean hasSystemUidErrors() {
14661        return mHasSystemUidErrors;
14662    }
14663
14664    static String arrayToString(int[] array) {
14665        StringBuffer buf = new StringBuffer(128);
14666        buf.append('[');
14667        if (array != null) {
14668            for (int i=0; i<array.length; i++) {
14669                if (i > 0) buf.append(", ");
14670                buf.append(array[i]);
14671            }
14672        }
14673        buf.append(']');
14674        return buf.toString();
14675    }
14676
14677    static class DumpState {
14678        public static final int DUMP_LIBS = 1 << 0;
14679        public static final int DUMP_FEATURES = 1 << 1;
14680        public static final int DUMP_RESOLVERS = 1 << 2;
14681        public static final int DUMP_PERMISSIONS = 1 << 3;
14682        public static final int DUMP_PACKAGES = 1 << 4;
14683        public static final int DUMP_SHARED_USERS = 1 << 5;
14684        public static final int DUMP_MESSAGES = 1 << 6;
14685        public static final int DUMP_PROVIDERS = 1 << 7;
14686        public static final int DUMP_VERIFIERS = 1 << 8;
14687        public static final int DUMP_PREFERRED = 1 << 9;
14688        public static final int DUMP_PREFERRED_XML = 1 << 10;
14689        public static final int DUMP_KEYSETS = 1 << 11;
14690        public static final int DUMP_VERSION = 1 << 12;
14691        public static final int DUMP_INSTALLS = 1 << 13;
14692        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14693        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14694
14695        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14696
14697        private int mTypes;
14698
14699        private int mOptions;
14700
14701        private boolean mTitlePrinted;
14702
14703        private SharedUserSetting mSharedUser;
14704
14705        public boolean isDumping(int type) {
14706            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14707                return true;
14708            }
14709
14710            return (mTypes & type) != 0;
14711        }
14712
14713        public void setDump(int type) {
14714            mTypes |= type;
14715        }
14716
14717        public boolean isOptionEnabled(int option) {
14718            return (mOptions & option) != 0;
14719        }
14720
14721        public void setOptionEnabled(int option) {
14722            mOptions |= option;
14723        }
14724
14725        public boolean onTitlePrinted() {
14726            final boolean printed = mTitlePrinted;
14727            mTitlePrinted = true;
14728            return printed;
14729        }
14730
14731        public boolean getTitlePrinted() {
14732            return mTitlePrinted;
14733        }
14734
14735        public void setTitlePrinted(boolean enabled) {
14736            mTitlePrinted = enabled;
14737        }
14738
14739        public SharedUserSetting getSharedUser() {
14740            return mSharedUser;
14741        }
14742
14743        public void setSharedUser(SharedUserSetting user) {
14744            mSharedUser = user;
14745        }
14746    }
14747
14748    @Override
14749    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14750        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14751                != PackageManager.PERMISSION_GRANTED) {
14752            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14753                    + Binder.getCallingPid()
14754                    + ", uid=" + Binder.getCallingUid()
14755                    + " without permission "
14756                    + android.Manifest.permission.DUMP);
14757            return;
14758        }
14759
14760        DumpState dumpState = new DumpState();
14761        boolean fullPreferred = false;
14762        boolean checkin = false;
14763
14764        String packageName = null;
14765        ArraySet<String> permissionNames = null;
14766
14767        int opti = 0;
14768        while (opti < args.length) {
14769            String opt = args[opti];
14770            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14771                break;
14772            }
14773            opti++;
14774
14775            if ("-a".equals(opt)) {
14776                // Right now we only know how to print all.
14777            } else if ("-h".equals(opt)) {
14778                pw.println("Package manager dump options:");
14779                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14780                pw.println("    --checkin: dump for a checkin");
14781                pw.println("    -f: print details of intent filters");
14782                pw.println("    -h: print this help");
14783                pw.println("  cmd may be one of:");
14784                pw.println("    l[ibraries]: list known shared libraries");
14785                pw.println("    f[ibraries]: list device features");
14786                pw.println("    k[eysets]: print known keysets");
14787                pw.println("    r[esolvers]: dump intent resolvers");
14788                pw.println("    perm[issions]: dump permissions");
14789                pw.println("    permission [name ...]: dump declaration and use of given permission");
14790                pw.println("    pref[erred]: print preferred package settings");
14791                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14792                pw.println("    prov[iders]: dump content providers");
14793                pw.println("    p[ackages]: dump installed packages");
14794                pw.println("    s[hared-users]: dump shared user IDs");
14795                pw.println("    m[essages]: print collected runtime messages");
14796                pw.println("    v[erifiers]: print package verifier info");
14797                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14798                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14799                pw.println("    version: print database version info");
14800                pw.println("    write: write current settings now");
14801                pw.println("    installs: details about install sessions");
14802                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14803                pw.println("    <package.name>: info about given package");
14804                return;
14805            } else if ("--checkin".equals(opt)) {
14806                checkin = true;
14807            } else if ("-f".equals(opt)) {
14808                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14809            } else {
14810                pw.println("Unknown argument: " + opt + "; use -h for help");
14811            }
14812        }
14813
14814        // Is the caller requesting to dump a particular piece of data?
14815        if (opti < args.length) {
14816            String cmd = args[opti];
14817            opti++;
14818            // Is this a package name?
14819            if ("android".equals(cmd) || cmd.contains(".")) {
14820                packageName = cmd;
14821                // When dumping a single package, we always dump all of its
14822                // filter information since the amount of data will be reasonable.
14823                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14824            } else if ("check-permission".equals(cmd)) {
14825                if (opti >= args.length) {
14826                    pw.println("Error: check-permission missing permission argument");
14827                    return;
14828                }
14829                String perm = args[opti];
14830                opti++;
14831                if (opti >= args.length) {
14832                    pw.println("Error: check-permission missing package argument");
14833                    return;
14834                }
14835                String pkg = args[opti];
14836                opti++;
14837                int user = UserHandle.getUserId(Binder.getCallingUid());
14838                if (opti < args.length) {
14839                    try {
14840                        user = Integer.parseInt(args[opti]);
14841                    } catch (NumberFormatException e) {
14842                        pw.println("Error: check-permission user argument is not a number: "
14843                                + args[opti]);
14844                        return;
14845                    }
14846                }
14847                pw.println(checkPermission(perm, pkg, user));
14848                return;
14849            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14850                dumpState.setDump(DumpState.DUMP_LIBS);
14851            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14852                dumpState.setDump(DumpState.DUMP_FEATURES);
14853            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14854                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14855            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14856                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14857            } else if ("permission".equals(cmd)) {
14858                if (opti >= args.length) {
14859                    pw.println("Error: permission requires permission name");
14860                    return;
14861                }
14862                permissionNames = new ArraySet<>();
14863                while (opti < args.length) {
14864                    permissionNames.add(args[opti]);
14865                    opti++;
14866                }
14867                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14868                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14869            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14870                dumpState.setDump(DumpState.DUMP_PREFERRED);
14871            } else if ("preferred-xml".equals(cmd)) {
14872                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14873                if (opti < args.length && "--full".equals(args[opti])) {
14874                    fullPreferred = true;
14875                    opti++;
14876                }
14877            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14878                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14879            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14880                dumpState.setDump(DumpState.DUMP_PACKAGES);
14881            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14882                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14883            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14884                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14885            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14886                dumpState.setDump(DumpState.DUMP_MESSAGES);
14887            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14888                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14889            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14890                    || "intent-filter-verifiers".equals(cmd)) {
14891                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14892            } else if ("version".equals(cmd)) {
14893                dumpState.setDump(DumpState.DUMP_VERSION);
14894            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14895                dumpState.setDump(DumpState.DUMP_KEYSETS);
14896            } else if ("installs".equals(cmd)) {
14897                dumpState.setDump(DumpState.DUMP_INSTALLS);
14898            } else if ("write".equals(cmd)) {
14899                synchronized (mPackages) {
14900                    mSettings.writeLPr();
14901                    pw.println("Settings written.");
14902                    return;
14903                }
14904            }
14905        }
14906
14907        if (checkin) {
14908            pw.println("vers,1");
14909        }
14910
14911        // reader
14912        synchronized (mPackages) {
14913            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14914                if (!checkin) {
14915                    if (dumpState.onTitlePrinted())
14916                        pw.println();
14917                    pw.println("Database versions:");
14918                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14919                }
14920            }
14921
14922            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14923                if (!checkin) {
14924                    if (dumpState.onTitlePrinted())
14925                        pw.println();
14926                    pw.println("Verifiers:");
14927                    pw.print("  Required: ");
14928                    pw.print(mRequiredVerifierPackage);
14929                    pw.print(" (uid=");
14930                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14931                    pw.println(")");
14932                } else if (mRequiredVerifierPackage != null) {
14933                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14934                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14935                }
14936            }
14937
14938            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14939                    packageName == null) {
14940                if (mIntentFilterVerifierComponent != null) {
14941                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14942                    if (!checkin) {
14943                        if (dumpState.onTitlePrinted())
14944                            pw.println();
14945                        pw.println("Intent Filter Verifier:");
14946                        pw.print("  Using: ");
14947                        pw.print(verifierPackageName);
14948                        pw.print(" (uid=");
14949                        pw.print(getPackageUid(verifierPackageName, 0));
14950                        pw.println(")");
14951                    } else if (verifierPackageName != null) {
14952                        pw.print("ifv,"); pw.print(verifierPackageName);
14953                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14954                    }
14955                } else {
14956                    pw.println();
14957                    pw.println("No Intent Filter Verifier available!");
14958                }
14959            }
14960
14961            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14962                boolean printedHeader = false;
14963                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14964                while (it.hasNext()) {
14965                    String name = it.next();
14966                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14967                    if (!checkin) {
14968                        if (!printedHeader) {
14969                            if (dumpState.onTitlePrinted())
14970                                pw.println();
14971                            pw.println("Libraries:");
14972                            printedHeader = true;
14973                        }
14974                        pw.print("  ");
14975                    } else {
14976                        pw.print("lib,");
14977                    }
14978                    pw.print(name);
14979                    if (!checkin) {
14980                        pw.print(" -> ");
14981                    }
14982                    if (ent.path != null) {
14983                        if (!checkin) {
14984                            pw.print("(jar) ");
14985                            pw.print(ent.path);
14986                        } else {
14987                            pw.print(",jar,");
14988                            pw.print(ent.path);
14989                        }
14990                    } else {
14991                        if (!checkin) {
14992                            pw.print("(apk) ");
14993                            pw.print(ent.apk);
14994                        } else {
14995                            pw.print(",apk,");
14996                            pw.print(ent.apk);
14997                        }
14998                    }
14999                    pw.println();
15000                }
15001            }
15002
15003            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15004                if (dumpState.onTitlePrinted())
15005                    pw.println();
15006                if (!checkin) {
15007                    pw.println("Features:");
15008                }
15009                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15010                while (it.hasNext()) {
15011                    String name = it.next();
15012                    if (!checkin) {
15013                        pw.print("  ");
15014                    } else {
15015                        pw.print("feat,");
15016                    }
15017                    pw.println(name);
15018                }
15019            }
15020
15021            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15022                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15023                        : "Activity Resolver Table:", "  ", packageName,
15024                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15025                    dumpState.setTitlePrinted(true);
15026                }
15027                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15028                        : "Receiver Resolver Table:", "  ", packageName,
15029                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15030                    dumpState.setTitlePrinted(true);
15031                }
15032                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15033                        : "Service Resolver Table:", "  ", packageName,
15034                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15035                    dumpState.setTitlePrinted(true);
15036                }
15037                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15038                        : "Provider Resolver Table:", "  ", packageName,
15039                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15040                    dumpState.setTitlePrinted(true);
15041                }
15042            }
15043
15044            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15045                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15046                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15047                    int user = mSettings.mPreferredActivities.keyAt(i);
15048                    if (pir.dump(pw,
15049                            dumpState.getTitlePrinted()
15050                                ? "\nPreferred Activities User " + user + ":"
15051                                : "Preferred Activities User " + user + ":", "  ",
15052                            packageName, true, false)) {
15053                        dumpState.setTitlePrinted(true);
15054                    }
15055                }
15056            }
15057
15058            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15059                pw.flush();
15060                FileOutputStream fout = new FileOutputStream(fd);
15061                BufferedOutputStream str = new BufferedOutputStream(fout);
15062                XmlSerializer serializer = new FastXmlSerializer();
15063                try {
15064                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15065                    serializer.startDocument(null, true);
15066                    serializer.setFeature(
15067                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15068                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15069                    serializer.endDocument();
15070                    serializer.flush();
15071                } catch (IllegalArgumentException e) {
15072                    pw.println("Failed writing: " + e);
15073                } catch (IllegalStateException e) {
15074                    pw.println("Failed writing: " + e);
15075                } catch (IOException e) {
15076                    pw.println("Failed writing: " + e);
15077                }
15078            }
15079
15080            if (!checkin
15081                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15082                    && packageName == null) {
15083                pw.println();
15084                int count = mSettings.mPackages.size();
15085                if (count == 0) {
15086                    pw.println("No applications!");
15087                    pw.println();
15088                } else {
15089                    final String prefix = "  ";
15090                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15091                    if (allPackageSettings.size() == 0) {
15092                        pw.println("No domain preferred apps!");
15093                        pw.println();
15094                    } else {
15095                        pw.println("App verification status:");
15096                        pw.println();
15097                        count = 0;
15098                        for (PackageSetting ps : allPackageSettings) {
15099                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15100                            if (ivi == null || ivi.getPackageName() == null) continue;
15101                            pw.println(prefix + "Package: " + ivi.getPackageName());
15102                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15103                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15104                            pw.println();
15105                            count++;
15106                        }
15107                        if (count == 0) {
15108                            pw.println(prefix + "No app verification established.");
15109                            pw.println();
15110                        }
15111                        for (int userId : sUserManager.getUserIds()) {
15112                            pw.println("App linkages for user " + userId + ":");
15113                            pw.println();
15114                            count = 0;
15115                            for (PackageSetting ps : allPackageSettings) {
15116                                final long status = ps.getDomainVerificationStatusForUser(userId);
15117                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15118                                    continue;
15119                                }
15120                                pw.println(prefix + "Package: " + ps.name);
15121                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15122                                String statusStr = IntentFilterVerificationInfo.
15123                                        getStatusStringFromValue(status);
15124                                pw.println(prefix + "Status:  " + statusStr);
15125                                pw.println();
15126                                count++;
15127                            }
15128                            if (count == 0) {
15129                                pw.println(prefix + "No configured app linkages.");
15130                                pw.println();
15131                            }
15132                        }
15133                    }
15134                }
15135            }
15136
15137            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15138                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15139                if (packageName == null && permissionNames == null) {
15140                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15141                        if (iperm == 0) {
15142                            if (dumpState.onTitlePrinted())
15143                                pw.println();
15144                            pw.println("AppOp Permissions:");
15145                        }
15146                        pw.print("  AppOp Permission ");
15147                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15148                        pw.println(":");
15149                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15150                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15151                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15152                        }
15153                    }
15154                }
15155            }
15156
15157            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15158                boolean printedSomething = false;
15159                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15160                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15161                        continue;
15162                    }
15163                    if (!printedSomething) {
15164                        if (dumpState.onTitlePrinted())
15165                            pw.println();
15166                        pw.println("Registered ContentProviders:");
15167                        printedSomething = true;
15168                    }
15169                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15170                    pw.print("    "); pw.println(p.toString());
15171                }
15172                printedSomething = false;
15173                for (Map.Entry<String, PackageParser.Provider> entry :
15174                        mProvidersByAuthority.entrySet()) {
15175                    PackageParser.Provider p = entry.getValue();
15176                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15177                        continue;
15178                    }
15179                    if (!printedSomething) {
15180                        if (dumpState.onTitlePrinted())
15181                            pw.println();
15182                        pw.println("ContentProvider Authorities:");
15183                        printedSomething = true;
15184                    }
15185                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15186                    pw.print("    "); pw.println(p.toString());
15187                    if (p.info != null && p.info.applicationInfo != null) {
15188                        final String appInfo = p.info.applicationInfo.toString();
15189                        pw.print("      applicationInfo="); pw.println(appInfo);
15190                    }
15191                }
15192            }
15193
15194            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15195                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15196            }
15197
15198            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15199                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15200            }
15201
15202            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15203                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15204            }
15205
15206            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15207                // XXX should handle packageName != null by dumping only install data that
15208                // the given package is involved with.
15209                if (dumpState.onTitlePrinted()) pw.println();
15210                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15211            }
15212
15213            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15214                if (dumpState.onTitlePrinted()) pw.println();
15215                mSettings.dumpReadMessagesLPr(pw, dumpState);
15216
15217                pw.println();
15218                pw.println("Package warning messages:");
15219                BufferedReader in = null;
15220                String line = null;
15221                try {
15222                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15223                    while ((line = in.readLine()) != null) {
15224                        if (line.contains("ignored: updated version")) continue;
15225                        pw.println(line);
15226                    }
15227                } catch (IOException ignored) {
15228                } finally {
15229                    IoUtils.closeQuietly(in);
15230                }
15231            }
15232
15233            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15234                BufferedReader in = null;
15235                String line = null;
15236                try {
15237                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15238                    while ((line = in.readLine()) != null) {
15239                        if (line.contains("ignored: updated version")) continue;
15240                        pw.print("msg,");
15241                        pw.println(line);
15242                    }
15243                } catch (IOException ignored) {
15244                } finally {
15245                    IoUtils.closeQuietly(in);
15246                }
15247            }
15248        }
15249    }
15250
15251    private String dumpDomainString(String packageName) {
15252        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15253        List<IntentFilter> filters = getAllIntentFilters(packageName);
15254
15255        ArraySet<String> result = new ArraySet<>();
15256        if (iviList.size() > 0) {
15257            for (IntentFilterVerificationInfo ivi : iviList) {
15258                for (String host : ivi.getDomains()) {
15259                    result.add(host);
15260                }
15261            }
15262        }
15263        if (filters != null && filters.size() > 0) {
15264            for (IntentFilter filter : filters) {
15265                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15266                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15267                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15268                    result.addAll(filter.getHostsList());
15269                }
15270            }
15271        }
15272
15273        StringBuilder sb = new StringBuilder(result.size() * 16);
15274        for (String domain : result) {
15275            if (sb.length() > 0) sb.append(" ");
15276            sb.append(domain);
15277        }
15278        return sb.toString();
15279    }
15280
15281    // ------- apps on sdcard specific code -------
15282    static final boolean DEBUG_SD_INSTALL = false;
15283
15284    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15285
15286    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15287
15288    private boolean mMediaMounted = false;
15289
15290    static String getEncryptKey() {
15291        try {
15292            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15293                    SD_ENCRYPTION_KEYSTORE_NAME);
15294            if (sdEncKey == null) {
15295                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15296                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15297                if (sdEncKey == null) {
15298                    Slog.e(TAG, "Failed to create encryption keys");
15299                    return null;
15300                }
15301            }
15302            return sdEncKey;
15303        } catch (NoSuchAlgorithmException nsae) {
15304            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15305            return null;
15306        } catch (IOException ioe) {
15307            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15308            return null;
15309        }
15310    }
15311
15312    /*
15313     * Update media status on PackageManager.
15314     */
15315    @Override
15316    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15317        int callingUid = Binder.getCallingUid();
15318        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15319            throw new SecurityException("Media status can only be updated by the system");
15320        }
15321        // reader; this apparently protects mMediaMounted, but should probably
15322        // be a different lock in that case.
15323        synchronized (mPackages) {
15324            Log.i(TAG, "Updating external media status from "
15325                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15326                    + (mediaStatus ? "mounted" : "unmounted"));
15327            if (DEBUG_SD_INSTALL)
15328                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15329                        + ", mMediaMounted=" + mMediaMounted);
15330            if (mediaStatus == mMediaMounted) {
15331                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15332                        : 0, -1);
15333                mHandler.sendMessage(msg);
15334                return;
15335            }
15336            mMediaMounted = mediaStatus;
15337        }
15338        // Queue up an async operation since the package installation may take a
15339        // little while.
15340        mHandler.post(new Runnable() {
15341            public void run() {
15342                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15343            }
15344        });
15345    }
15346
15347    /**
15348     * Called by MountService when the initial ASECs to scan are available.
15349     * Should block until all the ASEC containers are finished being scanned.
15350     */
15351    public void scanAvailableAsecs() {
15352        updateExternalMediaStatusInner(true, false, false);
15353        if (mShouldRestoreconData) {
15354            SELinuxMMAC.setRestoreconDone();
15355            mShouldRestoreconData = false;
15356        }
15357    }
15358
15359    /*
15360     * Collect information of applications on external media, map them against
15361     * existing containers and update information based on current mount status.
15362     * Please note that we always have to report status if reportStatus has been
15363     * set to true especially when unloading packages.
15364     */
15365    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15366            boolean externalStorage) {
15367        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15368        int[] uidArr = EmptyArray.INT;
15369
15370        final String[] list = PackageHelper.getSecureContainerList();
15371        if (ArrayUtils.isEmpty(list)) {
15372            Log.i(TAG, "No secure containers found");
15373        } else {
15374            // Process list of secure containers and categorize them
15375            // as active or stale based on their package internal state.
15376
15377            // reader
15378            synchronized (mPackages) {
15379                for (String cid : list) {
15380                    // Leave stages untouched for now; installer service owns them
15381                    if (PackageInstallerService.isStageName(cid)) continue;
15382
15383                    if (DEBUG_SD_INSTALL)
15384                        Log.i(TAG, "Processing container " + cid);
15385                    String pkgName = getAsecPackageName(cid);
15386                    if (pkgName == null) {
15387                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15388                        continue;
15389                    }
15390                    if (DEBUG_SD_INSTALL)
15391                        Log.i(TAG, "Looking for pkg : " + pkgName);
15392
15393                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15394                    if (ps == null) {
15395                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15396                        continue;
15397                    }
15398
15399                    /*
15400                     * Skip packages that are not external if we're unmounting
15401                     * external storage.
15402                     */
15403                    if (externalStorage && !isMounted && !isExternal(ps)) {
15404                        continue;
15405                    }
15406
15407                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15408                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15409                    // The package status is changed only if the code path
15410                    // matches between settings and the container id.
15411                    if (ps.codePathString != null
15412                            && ps.codePathString.startsWith(args.getCodePath())) {
15413                        if (DEBUG_SD_INSTALL) {
15414                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15415                                    + " at code path: " + ps.codePathString);
15416                        }
15417
15418                        // We do have a valid package installed on sdcard
15419                        processCids.put(args, ps.codePathString);
15420                        final int uid = ps.appId;
15421                        if (uid != -1) {
15422                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15423                        }
15424                    } else {
15425                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15426                                + ps.codePathString);
15427                    }
15428                }
15429            }
15430
15431            Arrays.sort(uidArr);
15432        }
15433
15434        // Process packages with valid entries.
15435        if (isMounted) {
15436            if (DEBUG_SD_INSTALL)
15437                Log.i(TAG, "Loading packages");
15438            loadMediaPackages(processCids, uidArr);
15439            startCleaningPackages();
15440            mInstallerService.onSecureContainersAvailable();
15441        } else {
15442            if (DEBUG_SD_INSTALL)
15443                Log.i(TAG, "Unloading packages");
15444            unloadMediaPackages(processCids, uidArr, reportStatus);
15445        }
15446    }
15447
15448    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15449            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15450        final int size = infos.size();
15451        final String[] packageNames = new String[size];
15452        final int[] packageUids = new int[size];
15453        for (int i = 0; i < size; i++) {
15454            final ApplicationInfo info = infos.get(i);
15455            packageNames[i] = info.packageName;
15456            packageUids[i] = info.uid;
15457        }
15458        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15459                finishedReceiver);
15460    }
15461
15462    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15463            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15464        sendResourcesChangedBroadcast(mediaStatus, replacing,
15465                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15466    }
15467
15468    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15469            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15470        int size = pkgList.length;
15471        if (size > 0) {
15472            // Send broadcasts here
15473            Bundle extras = new Bundle();
15474            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15475            if (uidArr != null) {
15476                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15477            }
15478            if (replacing) {
15479                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15480            }
15481            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15482                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15483            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15484        }
15485    }
15486
15487   /*
15488     * Look at potentially valid container ids from processCids If package
15489     * information doesn't match the one on record or package scanning fails,
15490     * the cid is added to list of removeCids. We currently don't delete stale
15491     * containers.
15492     */
15493    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15494        ArrayList<String> pkgList = new ArrayList<String>();
15495        Set<AsecInstallArgs> keys = processCids.keySet();
15496
15497        for (AsecInstallArgs args : keys) {
15498            String codePath = processCids.get(args);
15499            if (DEBUG_SD_INSTALL)
15500                Log.i(TAG, "Loading container : " + args.cid);
15501            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15502            try {
15503                // Make sure there are no container errors first.
15504                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15505                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15506                            + " when installing from sdcard");
15507                    continue;
15508                }
15509                // Check code path here.
15510                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15511                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15512                            + " does not match one in settings " + codePath);
15513                    continue;
15514                }
15515                // Parse package
15516                int parseFlags = mDefParseFlags;
15517                if (args.isExternalAsec()) {
15518                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15519                }
15520                if (args.isFwdLocked()) {
15521                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15522                }
15523
15524                synchronized (mInstallLock) {
15525                    PackageParser.Package pkg = null;
15526                    try {
15527                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15528                    } catch (PackageManagerException e) {
15529                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15530                    }
15531                    // Scan the package
15532                    if (pkg != null) {
15533                        /*
15534                         * TODO why is the lock being held? doPostInstall is
15535                         * called in other places without the lock. This needs
15536                         * to be straightened out.
15537                         */
15538                        // writer
15539                        synchronized (mPackages) {
15540                            retCode = PackageManager.INSTALL_SUCCEEDED;
15541                            pkgList.add(pkg.packageName);
15542                            // Post process args
15543                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15544                                    pkg.applicationInfo.uid);
15545                        }
15546                    } else {
15547                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15548                    }
15549                }
15550
15551            } finally {
15552                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15553                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15554                }
15555            }
15556        }
15557        // writer
15558        synchronized (mPackages) {
15559            // If the platform SDK has changed since the last time we booted,
15560            // we need to re-grant app permission to catch any new ones that
15561            // appear. This is really a hack, and means that apps can in some
15562            // cases get permissions that the user didn't initially explicitly
15563            // allow... it would be nice to have some better way to handle
15564            // this situation.
15565            final VersionInfo ver = mSettings.getExternalVersion();
15566
15567            int updateFlags = UPDATE_PERMISSIONS_ALL;
15568            if (ver.sdkVersion != mSdkVersion) {
15569                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15570                        + mSdkVersion + "; regranting permissions for external");
15571                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15572            }
15573            updatePermissionsLPw(null, null, updateFlags);
15574
15575            // Yay, everything is now upgraded
15576            ver.forceCurrent();
15577
15578            // can downgrade to reader
15579            // Persist settings
15580            mSettings.writeLPr();
15581        }
15582        // Send a broadcast to let everyone know we are done processing
15583        if (pkgList.size() > 0) {
15584            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15585        }
15586    }
15587
15588   /*
15589     * Utility method to unload a list of specified containers
15590     */
15591    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15592        // Just unmount all valid containers.
15593        for (AsecInstallArgs arg : cidArgs) {
15594            synchronized (mInstallLock) {
15595                arg.doPostDeleteLI(false);
15596           }
15597       }
15598   }
15599
15600    /*
15601     * Unload packages mounted on external media. This involves deleting package
15602     * data from internal structures, sending broadcasts about diabled packages,
15603     * gc'ing to free up references, unmounting all secure containers
15604     * corresponding to packages on external media, and posting a
15605     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15606     * that we always have to post this message if status has been requested no
15607     * matter what.
15608     */
15609    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15610            final boolean reportStatus) {
15611        if (DEBUG_SD_INSTALL)
15612            Log.i(TAG, "unloading media packages");
15613        ArrayList<String> pkgList = new ArrayList<String>();
15614        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15615        final Set<AsecInstallArgs> keys = processCids.keySet();
15616        for (AsecInstallArgs args : keys) {
15617            String pkgName = args.getPackageName();
15618            if (DEBUG_SD_INSTALL)
15619                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15620            // Delete package internally
15621            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15622            synchronized (mInstallLock) {
15623                boolean res = deletePackageLI(pkgName, null, false, null, null,
15624                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15625                if (res) {
15626                    pkgList.add(pkgName);
15627                } else {
15628                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15629                    failedList.add(args);
15630                }
15631            }
15632        }
15633
15634        // reader
15635        synchronized (mPackages) {
15636            // We didn't update the settings after removing each package;
15637            // write them now for all packages.
15638            mSettings.writeLPr();
15639        }
15640
15641        // We have to absolutely send UPDATED_MEDIA_STATUS only
15642        // after confirming that all the receivers processed the ordered
15643        // broadcast when packages get disabled, force a gc to clean things up.
15644        // and unload all the containers.
15645        if (pkgList.size() > 0) {
15646            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15647                    new IIntentReceiver.Stub() {
15648                public void performReceive(Intent intent, int resultCode, String data,
15649                        Bundle extras, boolean ordered, boolean sticky,
15650                        int sendingUser) throws RemoteException {
15651                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15652                            reportStatus ? 1 : 0, 1, keys);
15653                    mHandler.sendMessage(msg);
15654                }
15655            });
15656        } else {
15657            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15658                    keys);
15659            mHandler.sendMessage(msg);
15660        }
15661    }
15662
15663    private void loadPrivatePackages(VolumeInfo vol) {
15664        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15665        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15666        synchronized (mInstallLock) {
15667        synchronized (mPackages) {
15668            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15669            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15670            for (PackageSetting ps : packages) {
15671                final PackageParser.Package pkg;
15672                try {
15673                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15674                    loaded.add(pkg.applicationInfo);
15675                } catch (PackageManagerException e) {
15676                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15677                }
15678
15679                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15680                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15681                }
15682            }
15683
15684            int updateFlags = UPDATE_PERMISSIONS_ALL;
15685            if (ver.sdkVersion != mSdkVersion) {
15686                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15687                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15688                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15689            }
15690            updatePermissionsLPw(null, null, updateFlags);
15691
15692            // Yay, everything is now upgraded
15693            ver.forceCurrent();
15694
15695            mSettings.writeLPr();
15696        }
15697        }
15698
15699        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15700        sendResourcesChangedBroadcast(true, false, loaded, null);
15701    }
15702
15703    private void unloadPrivatePackages(VolumeInfo vol) {
15704        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15705        synchronized (mInstallLock) {
15706        synchronized (mPackages) {
15707            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15708            for (PackageSetting ps : packages) {
15709                if (ps.pkg == null) continue;
15710
15711                final ApplicationInfo info = ps.pkg.applicationInfo;
15712                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15713                if (deletePackageLI(ps.name, null, false, null, null,
15714                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15715                    unloaded.add(info);
15716                } else {
15717                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15718                }
15719            }
15720
15721            mSettings.writeLPr();
15722        }
15723        }
15724
15725        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15726        sendResourcesChangedBroadcast(false, false, unloaded, null);
15727    }
15728
15729    /**
15730     * Examine all users present on given mounted volume, and destroy data
15731     * belonging to users that are no longer valid, or whose user ID has been
15732     * recycled.
15733     */
15734    private void reconcileUsers(String volumeUuid) {
15735        final File[] files = FileUtils
15736                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15737        for (File file : files) {
15738            if (!file.isDirectory()) continue;
15739
15740            final int userId;
15741            final UserInfo info;
15742            try {
15743                userId = Integer.parseInt(file.getName());
15744                info = sUserManager.getUserInfo(userId);
15745            } catch (NumberFormatException e) {
15746                Slog.w(TAG, "Invalid user directory " + file);
15747                continue;
15748            }
15749
15750            boolean destroyUser = false;
15751            if (info == null) {
15752                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15753                        + " because no matching user was found");
15754                destroyUser = true;
15755            } else {
15756                try {
15757                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15758                } catch (IOException e) {
15759                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15760                            + " because we failed to enforce serial number: " + e);
15761                    destroyUser = true;
15762                }
15763            }
15764
15765            if (destroyUser) {
15766                synchronized (mInstallLock) {
15767                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15768                }
15769            }
15770        }
15771
15772        final UserManager um = mContext.getSystemService(UserManager.class);
15773        for (UserInfo user : um.getUsers()) {
15774            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15775            if (userDir.exists()) continue;
15776
15777            try {
15778                UserManagerService.prepareUserDirectory(userDir);
15779                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15780            } catch (IOException e) {
15781                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15782            }
15783        }
15784    }
15785
15786    /**
15787     * Examine all apps present on given mounted volume, and destroy apps that
15788     * aren't expected, either due to uninstallation or reinstallation on
15789     * another volume.
15790     */
15791    private void reconcileApps(String volumeUuid) {
15792        final File[] files = FileUtils
15793                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15794        for (File file : files) {
15795            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15796                    && !PackageInstallerService.isStageName(file.getName());
15797            if (!isPackage) {
15798                // Ignore entries which are not packages
15799                continue;
15800            }
15801
15802            boolean destroyApp = false;
15803            String packageName = null;
15804            try {
15805                final PackageLite pkg = PackageParser.parsePackageLite(file,
15806                        PackageParser.PARSE_MUST_BE_APK);
15807                packageName = pkg.packageName;
15808
15809                synchronized (mPackages) {
15810                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15811                    if (ps == null) {
15812                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15813                                + volumeUuid + " because we found no install record");
15814                        destroyApp = true;
15815                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15816                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15817                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15818                        destroyApp = true;
15819                    }
15820                }
15821
15822            } catch (PackageParserException e) {
15823                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15824                destroyApp = true;
15825            }
15826
15827            if (destroyApp) {
15828                synchronized (mInstallLock) {
15829                    if (packageName != null) {
15830                        removeDataDirsLI(volumeUuid, packageName);
15831                    }
15832                    if (file.isDirectory()) {
15833                        mInstaller.rmPackageDir(file.getAbsolutePath());
15834                    } else {
15835                        file.delete();
15836                    }
15837                }
15838            }
15839        }
15840    }
15841
15842    private void unfreezePackage(String packageName) {
15843        synchronized (mPackages) {
15844            final PackageSetting ps = mSettings.mPackages.get(packageName);
15845            if (ps != null) {
15846                ps.frozen = false;
15847            }
15848        }
15849    }
15850
15851    @Override
15852    public int movePackage(final String packageName, final String volumeUuid) {
15853        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15854
15855        final int moveId = mNextMoveId.getAndIncrement();
15856        try {
15857            movePackageInternal(packageName, volumeUuid, moveId);
15858        } catch (PackageManagerException e) {
15859            Slog.w(TAG, "Failed to move " + packageName, e);
15860            mMoveCallbacks.notifyStatusChanged(moveId,
15861                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15862        }
15863        return moveId;
15864    }
15865
15866    private void movePackageInternal(final String packageName, final String volumeUuid,
15867            final int moveId) throws PackageManagerException {
15868        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15869        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15870        final PackageManager pm = mContext.getPackageManager();
15871
15872        final boolean currentAsec;
15873        final String currentVolumeUuid;
15874        final File codeFile;
15875        final String installerPackageName;
15876        final String packageAbiOverride;
15877        final int appId;
15878        final String seinfo;
15879        final String label;
15880
15881        // reader
15882        synchronized (mPackages) {
15883            final PackageParser.Package pkg = mPackages.get(packageName);
15884            final PackageSetting ps = mSettings.mPackages.get(packageName);
15885            if (pkg == null || ps == null) {
15886                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15887            }
15888
15889            if (pkg.applicationInfo.isSystemApp()) {
15890                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15891                        "Cannot move system application");
15892            }
15893
15894            if (pkg.applicationInfo.isExternalAsec()) {
15895                currentAsec = true;
15896                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
15897            } else if (pkg.applicationInfo.isForwardLocked()) {
15898                currentAsec = true;
15899                currentVolumeUuid = "forward_locked";
15900            } else {
15901                currentAsec = false;
15902                currentVolumeUuid = ps.volumeUuid;
15903
15904                final File probe = new File(pkg.codePath);
15905                final File probeOat = new File(probe, "oat");
15906                if (!probe.isDirectory() || !probeOat.isDirectory()) {
15907                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15908                            "Move only supported for modern cluster style installs");
15909                }
15910            }
15911
15912            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
15913                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15914                        "Package already moved to " + volumeUuid);
15915            }
15916
15917            if (ps.frozen) {
15918                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15919                        "Failed to move already frozen package");
15920            }
15921            ps.frozen = true;
15922
15923            codeFile = new File(pkg.codePath);
15924            installerPackageName = ps.installerPackageName;
15925            packageAbiOverride = ps.cpuAbiOverrideString;
15926            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15927            seinfo = pkg.applicationInfo.seinfo;
15928            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15929        }
15930
15931        // Now that we're guarded by frozen state, kill app during move
15932        final long token = Binder.clearCallingIdentity();
15933        try {
15934            killApplication(packageName, appId, "move pkg");
15935        } finally {
15936            Binder.restoreCallingIdentity(token);
15937        }
15938
15939        final Bundle extras = new Bundle();
15940        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15941        extras.putString(Intent.EXTRA_TITLE, label);
15942        mMoveCallbacks.notifyCreated(moveId, extras);
15943
15944        int installFlags;
15945        final boolean moveCompleteApp;
15946        final File measurePath;
15947
15948        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15949            installFlags = INSTALL_INTERNAL;
15950            moveCompleteApp = !currentAsec;
15951            measurePath = Environment.getDataAppDirectory(volumeUuid);
15952        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15953            installFlags = INSTALL_EXTERNAL;
15954            moveCompleteApp = false;
15955            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15956        } else {
15957            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15958            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15959                    || !volume.isMountedWritable()) {
15960                unfreezePackage(packageName);
15961                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15962                        "Move location not mounted private volume");
15963            }
15964
15965            Preconditions.checkState(!currentAsec);
15966
15967            installFlags = INSTALL_INTERNAL;
15968            moveCompleteApp = true;
15969            measurePath = Environment.getDataAppDirectory(volumeUuid);
15970        }
15971
15972        final PackageStats stats = new PackageStats(null, -1);
15973        synchronized (mInstaller) {
15974            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15975                unfreezePackage(packageName);
15976                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15977                        "Failed to measure package size");
15978            }
15979        }
15980
15981        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15982                + stats.dataSize);
15983
15984        final long startFreeBytes = measurePath.getFreeSpace();
15985        final long sizeBytes;
15986        if (moveCompleteApp) {
15987            sizeBytes = stats.codeSize + stats.dataSize;
15988        } else {
15989            sizeBytes = stats.codeSize;
15990        }
15991
15992        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15993            unfreezePackage(packageName);
15994            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15995                    "Not enough free space to move");
15996        }
15997
15998        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15999
16000        final CountDownLatch installedLatch = new CountDownLatch(1);
16001        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16002            @Override
16003            public void onUserActionRequired(Intent intent) throws RemoteException {
16004                throw new IllegalStateException();
16005            }
16006
16007            @Override
16008            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16009                    Bundle extras) throws RemoteException {
16010                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16011                        + PackageManager.installStatusToString(returnCode, msg));
16012
16013                installedLatch.countDown();
16014
16015                // Regardless of success or failure of the move operation,
16016                // always unfreeze the package
16017                unfreezePackage(packageName);
16018
16019                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16020                switch (status) {
16021                    case PackageInstaller.STATUS_SUCCESS:
16022                        mMoveCallbacks.notifyStatusChanged(moveId,
16023                                PackageManager.MOVE_SUCCEEDED);
16024                        break;
16025                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16026                        mMoveCallbacks.notifyStatusChanged(moveId,
16027                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16028                        break;
16029                    default:
16030                        mMoveCallbacks.notifyStatusChanged(moveId,
16031                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16032                        break;
16033                }
16034            }
16035        };
16036
16037        final MoveInfo move;
16038        if (moveCompleteApp) {
16039            // Kick off a thread to report progress estimates
16040            new Thread() {
16041                @Override
16042                public void run() {
16043                    while (true) {
16044                        try {
16045                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16046                                break;
16047                            }
16048                        } catch (InterruptedException ignored) {
16049                        }
16050
16051                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16052                        final int progress = 10 + (int) MathUtils.constrain(
16053                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16054                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16055                    }
16056                }
16057            }.start();
16058
16059            final String dataAppName = codeFile.getName();
16060            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16061                    dataAppName, appId, seinfo);
16062        } else {
16063            move = null;
16064        }
16065
16066        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16067
16068        final Message msg = mHandler.obtainMessage(INIT_COPY);
16069        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16070        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16071                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16072        mHandler.sendMessage(msg);
16073    }
16074
16075    @Override
16076    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16077        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16078
16079        final int realMoveId = mNextMoveId.getAndIncrement();
16080        final Bundle extras = new Bundle();
16081        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16082        mMoveCallbacks.notifyCreated(realMoveId, extras);
16083
16084        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16085            @Override
16086            public void onCreated(int moveId, Bundle extras) {
16087                // Ignored
16088            }
16089
16090            @Override
16091            public void onStatusChanged(int moveId, int status, long estMillis) {
16092                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16093            }
16094        };
16095
16096        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16097        storage.setPrimaryStorageUuid(volumeUuid, callback);
16098        return realMoveId;
16099    }
16100
16101    @Override
16102    public int getMoveStatus(int moveId) {
16103        mContext.enforceCallingOrSelfPermission(
16104                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16105        return mMoveCallbacks.mLastStatus.get(moveId);
16106    }
16107
16108    @Override
16109    public void registerMoveCallback(IPackageMoveObserver callback) {
16110        mContext.enforceCallingOrSelfPermission(
16111                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16112        mMoveCallbacks.register(callback);
16113    }
16114
16115    @Override
16116    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16117        mContext.enforceCallingOrSelfPermission(
16118                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16119        mMoveCallbacks.unregister(callback);
16120    }
16121
16122    @Override
16123    public boolean setInstallLocation(int loc) {
16124        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16125                null);
16126        if (getInstallLocation() == loc) {
16127            return true;
16128        }
16129        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16130                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16131            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16132                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16133            return true;
16134        }
16135        return false;
16136   }
16137
16138    @Override
16139    public int getInstallLocation() {
16140        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16141                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16142                PackageHelper.APP_INSTALL_AUTO);
16143    }
16144
16145    /** Called by UserManagerService */
16146    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16147        mDirtyUsers.remove(userHandle);
16148        mSettings.removeUserLPw(userHandle);
16149        mPendingBroadcasts.remove(userHandle);
16150        if (mInstaller != null) {
16151            // Technically, we shouldn't be doing this with the package lock
16152            // held.  However, this is very rare, and there is already so much
16153            // other disk I/O going on, that we'll let it slide for now.
16154            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16155            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16156                final String volumeUuid = vol.getFsUuid();
16157                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16158                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16159            }
16160        }
16161        mUserNeedsBadging.delete(userHandle);
16162        removeUnusedPackagesLILPw(userManager, userHandle);
16163    }
16164
16165    /**
16166     * We're removing userHandle and would like to remove any downloaded packages
16167     * that are no longer in use by any other user.
16168     * @param userHandle the user being removed
16169     */
16170    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16171        final boolean DEBUG_CLEAN_APKS = false;
16172        int [] users = userManager.getUserIdsLPr();
16173        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16174        while (psit.hasNext()) {
16175            PackageSetting ps = psit.next();
16176            if (ps.pkg == null) {
16177                continue;
16178            }
16179            final String packageName = ps.pkg.packageName;
16180            // Skip over if system app
16181            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16182                continue;
16183            }
16184            if (DEBUG_CLEAN_APKS) {
16185                Slog.i(TAG, "Checking package " + packageName);
16186            }
16187            boolean keep = false;
16188            for (int i = 0; i < users.length; i++) {
16189                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16190                    keep = true;
16191                    if (DEBUG_CLEAN_APKS) {
16192                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16193                                + users[i]);
16194                    }
16195                    break;
16196                }
16197            }
16198            if (!keep) {
16199                if (DEBUG_CLEAN_APKS) {
16200                    Slog.i(TAG, "  Removing package " + packageName);
16201                }
16202                mHandler.post(new Runnable() {
16203                    public void run() {
16204                        deletePackageX(packageName, userHandle, 0);
16205                    } //end run
16206                });
16207            }
16208        }
16209    }
16210
16211    /** Called by UserManagerService */
16212    void createNewUserLILPw(int userHandle) {
16213        if (mInstaller != null) {
16214            mInstaller.createUserConfig(userHandle);
16215            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16216            applyFactoryDefaultBrowserLPw(userHandle);
16217            primeDomainVerificationsLPw(userHandle);
16218        }
16219    }
16220
16221    void newUserCreated(final int userHandle) {
16222        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16223    }
16224
16225    @Override
16226    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16227        mContext.enforceCallingOrSelfPermission(
16228                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16229                "Only package verification agents can read the verifier device identity");
16230
16231        synchronized (mPackages) {
16232            return mSettings.getVerifierDeviceIdentityLPw();
16233        }
16234    }
16235
16236    @Override
16237    public void setPermissionEnforced(String permission, boolean enforced) {
16238        // TODO: Now that we no longer change GID for storage, this should to away.
16239        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16240                "setPermissionEnforced");
16241        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16242            synchronized (mPackages) {
16243                if (mSettings.mReadExternalStorageEnforced == null
16244                        || mSettings.mReadExternalStorageEnforced != enforced) {
16245                    mSettings.mReadExternalStorageEnforced = enforced;
16246                    mSettings.writeLPr();
16247                }
16248            }
16249            // kill any non-foreground processes so we restart them and
16250            // grant/revoke the GID.
16251            final IActivityManager am = ActivityManagerNative.getDefault();
16252            if (am != null) {
16253                final long token = Binder.clearCallingIdentity();
16254                try {
16255                    am.killProcessesBelowForeground("setPermissionEnforcement");
16256                } catch (RemoteException e) {
16257                } finally {
16258                    Binder.restoreCallingIdentity(token);
16259                }
16260            }
16261        } else {
16262            throw new IllegalArgumentException("No selective enforcement for " + permission);
16263        }
16264    }
16265
16266    @Override
16267    @Deprecated
16268    public boolean isPermissionEnforced(String permission) {
16269        return true;
16270    }
16271
16272    @Override
16273    public boolean isStorageLow() {
16274        final long token = Binder.clearCallingIdentity();
16275        try {
16276            final DeviceStorageMonitorInternal
16277                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16278            if (dsm != null) {
16279                return dsm.isMemoryLow();
16280            } else {
16281                return false;
16282            }
16283        } finally {
16284            Binder.restoreCallingIdentity(token);
16285        }
16286    }
16287
16288    @Override
16289    public IPackageInstaller getPackageInstaller() {
16290        return mInstallerService;
16291    }
16292
16293    private boolean userNeedsBadging(int userId) {
16294        int index = mUserNeedsBadging.indexOfKey(userId);
16295        if (index < 0) {
16296            final UserInfo userInfo;
16297            final long token = Binder.clearCallingIdentity();
16298            try {
16299                userInfo = sUserManager.getUserInfo(userId);
16300            } finally {
16301                Binder.restoreCallingIdentity(token);
16302            }
16303            final boolean b;
16304            if (userInfo != null && userInfo.isManagedProfile()) {
16305                b = true;
16306            } else {
16307                b = false;
16308            }
16309            mUserNeedsBadging.put(userId, b);
16310            return b;
16311        }
16312        return mUserNeedsBadging.valueAt(index);
16313    }
16314
16315    @Override
16316    public KeySet getKeySetByAlias(String packageName, String alias) {
16317        if (packageName == null || alias == null) {
16318            return null;
16319        }
16320        synchronized(mPackages) {
16321            final PackageParser.Package pkg = mPackages.get(packageName);
16322            if (pkg == null) {
16323                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16324                throw new IllegalArgumentException("Unknown package: " + packageName);
16325            }
16326            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16327            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16328        }
16329    }
16330
16331    @Override
16332    public KeySet getSigningKeySet(String packageName) {
16333        if (packageName == null) {
16334            return null;
16335        }
16336        synchronized(mPackages) {
16337            final PackageParser.Package pkg = mPackages.get(packageName);
16338            if (pkg == null) {
16339                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16340                throw new IllegalArgumentException("Unknown package: " + packageName);
16341            }
16342            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16343                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16344                throw new SecurityException("May not access signing KeySet of other apps.");
16345            }
16346            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16347            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16348        }
16349    }
16350
16351    @Override
16352    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16353        if (packageName == null || ks == null) {
16354            return false;
16355        }
16356        synchronized(mPackages) {
16357            final PackageParser.Package pkg = mPackages.get(packageName);
16358            if (pkg == null) {
16359                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16360                throw new IllegalArgumentException("Unknown package: " + packageName);
16361            }
16362            IBinder ksh = ks.getToken();
16363            if (ksh instanceof KeySetHandle) {
16364                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16365                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16366            }
16367            return false;
16368        }
16369    }
16370
16371    @Override
16372    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16373        if (packageName == null || ks == null) {
16374            return false;
16375        }
16376        synchronized(mPackages) {
16377            final PackageParser.Package pkg = mPackages.get(packageName);
16378            if (pkg == null) {
16379                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16380                throw new IllegalArgumentException("Unknown package: " + packageName);
16381            }
16382            IBinder ksh = ks.getToken();
16383            if (ksh instanceof KeySetHandle) {
16384                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16385                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16386            }
16387            return false;
16388        }
16389    }
16390
16391    public void getUsageStatsIfNoPackageUsageInfo() {
16392        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16393            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16394            if (usm == null) {
16395                throw new IllegalStateException("UsageStatsManager must be initialized");
16396            }
16397            long now = System.currentTimeMillis();
16398            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16399            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16400                String packageName = entry.getKey();
16401                PackageParser.Package pkg = mPackages.get(packageName);
16402                if (pkg == null) {
16403                    continue;
16404                }
16405                UsageStats usage = entry.getValue();
16406                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16407                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16408            }
16409        }
16410    }
16411
16412    /**
16413     * Check and throw if the given before/after packages would be considered a
16414     * downgrade.
16415     */
16416    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16417            throws PackageManagerException {
16418        if (after.versionCode < before.mVersionCode) {
16419            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16420                    "Update version code " + after.versionCode + " is older than current "
16421                    + before.mVersionCode);
16422        } else if (after.versionCode == before.mVersionCode) {
16423            if (after.baseRevisionCode < before.baseRevisionCode) {
16424                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16425                        "Update base revision code " + after.baseRevisionCode
16426                        + " is older than current " + before.baseRevisionCode);
16427            }
16428
16429            if (!ArrayUtils.isEmpty(after.splitNames)) {
16430                for (int i = 0; i < after.splitNames.length; i++) {
16431                    final String splitName = after.splitNames[i];
16432                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16433                    if (j != -1) {
16434                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16435                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16436                                    "Update split " + splitName + " revision code "
16437                                    + after.splitRevisionCodes[i] + " is older than current "
16438                                    + before.splitRevisionCodes[j]);
16439                        }
16440                    }
16441                }
16442            }
16443        }
16444    }
16445
16446    private static class MoveCallbacks extends Handler {
16447        private static final int MSG_CREATED = 1;
16448        private static final int MSG_STATUS_CHANGED = 2;
16449
16450        private final RemoteCallbackList<IPackageMoveObserver>
16451                mCallbacks = new RemoteCallbackList<>();
16452
16453        private final SparseIntArray mLastStatus = new SparseIntArray();
16454
16455        public MoveCallbacks(Looper looper) {
16456            super(looper);
16457        }
16458
16459        public void register(IPackageMoveObserver callback) {
16460            mCallbacks.register(callback);
16461        }
16462
16463        public void unregister(IPackageMoveObserver callback) {
16464            mCallbacks.unregister(callback);
16465        }
16466
16467        @Override
16468        public void handleMessage(Message msg) {
16469            final SomeArgs args = (SomeArgs) msg.obj;
16470            final int n = mCallbacks.beginBroadcast();
16471            for (int i = 0; i < n; i++) {
16472                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16473                try {
16474                    invokeCallback(callback, msg.what, args);
16475                } catch (RemoteException ignored) {
16476                }
16477            }
16478            mCallbacks.finishBroadcast();
16479            args.recycle();
16480        }
16481
16482        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16483                throws RemoteException {
16484            switch (what) {
16485                case MSG_CREATED: {
16486                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16487                    break;
16488                }
16489                case MSG_STATUS_CHANGED: {
16490                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16491                    break;
16492                }
16493            }
16494        }
16495
16496        private void notifyCreated(int moveId, Bundle extras) {
16497            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16498
16499            final SomeArgs args = SomeArgs.obtain();
16500            args.argi1 = moveId;
16501            args.arg2 = extras;
16502            obtainMessage(MSG_CREATED, args).sendToTarget();
16503        }
16504
16505        private void notifyStatusChanged(int moveId, int status) {
16506            notifyStatusChanged(moveId, status, -1);
16507        }
16508
16509        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16510            Slog.v(TAG, "Move " + moveId + " status " + status);
16511
16512            final SomeArgs args = SomeArgs.obtain();
16513            args.argi1 = moveId;
16514            args.argi2 = status;
16515            args.arg3 = estMillis;
16516            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16517
16518            synchronized (mLastStatus) {
16519                mLastStatus.put(moveId, status);
16520            }
16521        }
16522    }
16523
16524    private final class OnPermissionChangeListeners extends Handler {
16525        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16526
16527        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16528                new RemoteCallbackList<>();
16529
16530        public OnPermissionChangeListeners(Looper looper) {
16531            super(looper);
16532        }
16533
16534        @Override
16535        public void handleMessage(Message msg) {
16536            switch (msg.what) {
16537                case MSG_ON_PERMISSIONS_CHANGED: {
16538                    final int uid = msg.arg1;
16539                    handleOnPermissionsChanged(uid);
16540                } break;
16541            }
16542        }
16543
16544        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16545            mPermissionListeners.register(listener);
16546
16547        }
16548
16549        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16550            mPermissionListeners.unregister(listener);
16551        }
16552
16553        public void onPermissionsChanged(int uid) {
16554            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16555                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16556            }
16557        }
16558
16559        private void handleOnPermissionsChanged(int uid) {
16560            final int count = mPermissionListeners.beginBroadcast();
16561            try {
16562                for (int i = 0; i < count; i++) {
16563                    IOnPermissionsChangeListener callback = mPermissionListeners
16564                            .getBroadcastItem(i);
16565                    try {
16566                        callback.onPermissionsChanged(uid);
16567                    } catch (RemoteException e) {
16568                        Log.e(TAG, "Permission listener is dead", e);
16569                    }
16570                }
16571            } finally {
16572                mPermissionListeners.finishBroadcast();
16573            }
16574        }
16575    }
16576
16577    private class PackageManagerInternalImpl extends PackageManagerInternal {
16578        @Override
16579        public void setLocationPackagesProvider(PackagesProvider provider) {
16580            synchronized (mPackages) {
16581                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16582            }
16583        }
16584
16585        @Override
16586        public void setImePackagesProvider(PackagesProvider provider) {
16587            synchronized (mPackages) {
16588                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16589            }
16590        }
16591
16592        @Override
16593        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16594            synchronized (mPackages) {
16595                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16596            }
16597        }
16598
16599        @Override
16600        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16601            synchronized (mPackages) {
16602                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16603            }
16604        }
16605
16606        @Override
16607        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16608            synchronized (mPackages) {
16609                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16610            }
16611        }
16612
16613        @Override
16614        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16615            synchronized (mPackages) {
16616                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16617            }
16618        }
16619
16620        @Override
16621        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16622            synchronized (mPackages) {
16623                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16624            }
16625        }
16626
16627        @Override
16628        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16629            synchronized (mPackages) {
16630                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16631                        packageName, userId);
16632            }
16633        }
16634
16635        @Override
16636        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16637            synchronized (mPackages) {
16638                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16639                        packageName, userId);
16640            }
16641        }
16642        @Override
16643        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16644            synchronized (mPackages) {
16645                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16646                        packageName, userId);
16647            }
16648        }
16649    }
16650
16651    @Override
16652    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16653        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16654        synchronized (mPackages) {
16655            final long identity = Binder.clearCallingIdentity();
16656            try {
16657                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16658                        packageNames, userId);
16659            } finally {
16660                Binder.restoreCallingIdentity(identity);
16661            }
16662        }
16663    }
16664
16665    private static void enforceSystemOrPhoneCaller(String tag) {
16666        int callingUid = Binder.getCallingUid();
16667        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16668            throw new SecurityException(
16669                    "Cannot call " + tag + " from UID " + callingUid);
16670        }
16671    }
16672}
16673